From 1b1cf93b2a1b62521ade0f7b5fae4e25ba474b84 Mon Sep 17 00:00:00 2001 From: Xiao-MoMi <70987828+Xiao-MoMi@users.noreply.github.com> Date: Fri, 3 Mar 2023 23:15:37 +0800 Subject: [PATCH] 1.3-beta-1 --- build.gradle | 2 +- .../customfishing/CustomFishing.java | 170 +++--- .../customfishing/api/CustomFishingAPI.java | 10 +- .../api/event/FishFinderEvent.java | 2 +- .../api/event/FishHookEvent.java | 11 +- .../api/event/FishResultEvent.java | 2 +- .../customfishing/api/event/RodCastEvent.java | 12 +- .../api/event/TotemActivationEvent.java | 2 +- .../{PluginCommand.java => MainCommand.java} | 4 +- .../commands/SellFishCommand.java | 2 +- .../commands/subcmd/BaitCommand.java | 8 +- .../commands/subcmd/CompetitionCommand.java | 35 +- .../commands/subcmd/LootCommand.java | 10 +- .../commands/subcmd/OpenBagCommand.java | 7 +- .../commands/subcmd/OpenCommand.java | 4 +- .../commands/subcmd/ReloadCommand.java | 4 +- .../commands/subcmd/RodCommand.java | 8 +- .../commands/subcmd/SellShopCommand.java | 2 +- .../commands/subcmd/UtilCommand.java | 8 +- .../data/storage/FileStorageImpl.java | 37 +- .../data/storage/MySQLStorageImpl.java | 68 +-- .../data/storage/SqlConnection.java | 21 +- .../data/storage/SqlConstants.java | 14 +- .../{object => }/fishing/BobberCheckTask.java | 85 +-- .../Bonus.java => fishing/Effect.java} | 68 ++- .../{object => }/fishing/FishResult.java | 8 +- .../fishing/FishingCondition.java | 6 +- .../{object => }/fishing/LavaEffect.java | 2 +- .../customfishing/fishing/MiniGameConfig.java | 30 + .../{object => }/fishing/VanillaLoot.java | 2 +- .../customfishing/fishing/bar/FishingBar.java | 30 + .../customfishing/fishing/bar/ModeOneBar.java | 73 +++ .../customfishing/fishing/bar/ModeTwoBar.java | 67 +++ .../competition/Competition.java | 52 +- .../competition/CompetitionConfig.java | 6 +- .../competition/CompetitionGoal.java | 2 +- .../competition/CompetitionPlayer.java | 2 +- .../competition/CompetitionSchedule.java | 9 +- .../competition/bossbar/BossBarConfig.java | 2 +- .../competition/bossbar/BossBarManager.java | 14 +- .../competition/bossbar/BossBarOverlay.java | 2 +- .../competition/bossbar/BossBarSender.java | 24 +- .../competition/ranking/LocalRankingImpl.java | 4 +- .../competition/ranking/RankingInterface.java | 4 +- .../competition/ranking/RedisRankingImpl.java | 4 +- .../{object => fishing}/loot/DroppedItem.java | 18 +- .../{object => fishing}/loot/Item.java | 45 +- .../{object => fishing}/loot/Loot.java | 85 +-- .../{object => fishing}/loot/Mob.java | 12 +- .../{object => fishing}/loot/MobVector.java | 2 +- .../fishing/mode/FishingGame.java | 69 +++ .../fishing/mode/ModeOneGame.java | 70 +++ .../fishing/mode/ModeTwoGame.java | 139 +++++ .../requirements/BiomeImpl.java | 5 +- .../requirements/CustomPapi.java | 6 +- .../requirements/PermissionImpl.java | 4 +- .../requirements/RequirementInterface.java | 4 +- .../requirements/SeasonImpl.java | 6 +- .../fishing/requirements/SkillLevelImpl.java | 12 + .../requirements/TimeImpl.java | 4 +- .../requirements/WeatherImpl.java | 4 +- .../requirements/WorldImpl.java | 4 +- .../requirements/YPosImpl.java | 4 +- .../requirements/papi/ExpressionAnd.java | 2 +- .../requirements/papi/ExpressionOr.java | 2 +- .../requirements/papi/PapiEquals.java | 2 +- .../requirements/papi/PapiGreater.java | 2 +- .../requirements/papi/PapiNoLarger.java | 2 +- .../requirements/papi/PapiNoLess.java | 2 +- .../requirements/papi/PapiNotEquals.java | 2 +- .../requirements/papi/PapiRequirement.java | 2 +- .../requirements/papi/PapiSmaller.java | 2 +- .../totem/ActivatedTotem.java | 16 +- .../{object => fishing}/totem/CorePos.java | 2 +- .../{object => fishing}/totem/FinalModel.java | 2 +- .../totem/OriginalModel.java | 2 +- .../{object => fishing}/totem/Totem.java | 16 +- .../totem/TotemConfig.java | 16 +- .../totem/TotemParticle.java | 2 +- .../customfishing/helper/LibraryLoader.java | 4 +- .../momirealms/customfishing/helper/Log.java | 10 +- .../customfishing/helper/VersionHelper.java | 48 +- .../integration/AntiGriefInterface.java | 47 -- .../integration/MobInterface.java | 2 +- .../customfishing/integration/VaultHook.java | 2 +- .../integration/antigrief/BentoBoxHook.java | 45 -- .../integration/antigrief/CrashClaimHook.java | 39 -- .../antigrief/GriefDefenderHook.java | 35 -- .../antigrief/GriefPreventionHook.java | 35 -- .../integration/antigrief/KingdomsXHook.java | 53 -- .../integration/antigrief/LandsHook.java | 53 -- .../antigrief/PlotSquaredHook.java | 42 -- .../integration/antigrief/ResidenceHook.java | 48 -- .../integration/antigrief/TownyHook.java | 41 -- .../integration/antigrief/WorldGuardHook.java | 68 --- .../block/ItemsAdderBlockImpl.java | 8 +- .../integration/block/OraxenBlockImpl.java | 8 +- .../integration/block/VanillaBlockImpl.java | 8 +- .../item/CustomFishingItemImpl.java | 10 +- .../integration/item/EcoItemRegister.java | 13 +- .../integration/mob/MythicMobsMobImpl.java | 4 +- .../integration/papi/CompetitionPapi.java | 4 +- .../integration/papi/PlaceholderManager.java | 1 - .../integration/quest/BattlePassCFQuest.java | 4 +- .../integration/quest/ClueScrollCFQuest.java | 12 +- .../quest/NewBetonQuestCFQuest.java | 2 +- .../quest/OldBetonQuestCFQuest.java | 4 +- .../integration/skill/MMOCoreImpl.java | 4 +- .../ConsumeItemListener.java} | 23 +- ...pleListener.java => JoinQuitListener.java} | 2 +- .../listener/PlayerFishListener.java | 2 +- .../listener/WindowPacketListener.java | 2 +- .../customfishing/manager/BagDataManager.java | 95 ++-- .../manager/BarMechanicManager.java | 127 +++++ .../customfishing/manager/BonusManager.java | 237 -------- .../manager/CompetitionManager.java | 74 ++- .../customfishing/manager/ConfigManager.java | 116 ++-- .../customfishing/manager/DataManager.java | 9 +- .../customfishing/manager/EffectManager.java | 250 ++++++++ .../customfishing/manager/FishingManager.java | 488 ++++++++-------- .../manager/IntegrationManager.java | 292 ++++------ .../customfishing/manager/LayoutManager.java | 67 --- .../customfishing/manager/LootManager.java | 354 ++++++------ .../customfishing/manager/OffsetManager.java | 135 +++++ .../customfishing/manager/SellManager.java | 127 ++--- .../customfishing/manager/TotemManager.java | 99 +++- .../{TextCache.java => DynamicText.java} | 14 +- .../customfishing/object/Function.java | 4 + .../object/{loot => }/LeveledEnchantment.java | 2 +- .../object/action/CommandActionImpl.java | 3 +- .../object/action/SkillXPImpl.java | 2 +- .../object/action/SoundActionImpl.java | 4 +- .../object/fishing/FishingPlayer.java | 133 ----- .../customfishing/object/fishing/Layout.java | 85 --- .../object/fishing/Modifier.java | 49 -- .../object/requirements/SkillLevelImpl.java | 13 - .../customfishing/util/AdventureUtil.java | 177 +++--- .../customfishing/util/ArmorStandUtil.java | 39 +- .../customfishing/util/ConfigUtil.java | 46 +- .../customfishing/util/FakeItemUtil.java | 10 +- .../customfishing/util/InventoryUtil.java | 19 +- .../customfishing/util/ItemStackUtil.java | 76 ++- .../customfishing/util/JedisUtil.java | 12 +- src/main/resources/baits/default.yml | 8 +- src/main/resources/bars.yml | 460 --------------- src/main/resources/bars/default.yml | 536 ++++++++++++++++++ .../default.yml} | 0 src/main/resources/config.yml | 89 ++- src/main/resources/database.yml | 5 + .../default.yml} | 0 src/main/resources/loots/default.yml | 95 ---- src/main/resources/loots/example.yml | 36 +- .../resources/messages/messages_english.yml | 2 +- src/main/resources/minigames/default.yml | 75 +++ .../mobs/{example.yml => default.yml} | 2 - src/main/resources/plugin.yml | 9 - .../{sell-fish.yml => sell-fish-gui.yml} | 19 +- .../default.yml} | 0 .../{totems.yml => totems/default.yml} | 0 .../utils/{fishfinder.yml => fish_finder.yml} | 0 160 files changed, 3406 insertions(+), 3277 deletions(-) rename src/main/java/net/momirealms/customfishing/commands/{PluginCommand.java => MainCommand.java} (97%) rename src/main/java/net/momirealms/customfishing/{object => }/fishing/BobberCheckTask.java (70%) rename src/main/java/net/momirealms/customfishing/{object/fishing/Bonus.java => fishing/Effect.java} (56%) rename src/main/java/net/momirealms/customfishing/{object => }/fishing/FishResult.java (87%) rename src/main/java/net/momirealms/customfishing/{object => }/fishing/FishingCondition.java (88%) rename src/main/java/net/momirealms/customfishing/{object => }/fishing/LavaEffect.java (97%) create mode 100644 src/main/java/net/momirealms/customfishing/fishing/MiniGameConfig.java rename src/main/java/net/momirealms/customfishing/{object => }/fishing/VanillaLoot.java (95%) create mode 100644 src/main/java/net/momirealms/customfishing/fishing/bar/FishingBar.java create mode 100644 src/main/java/net/momirealms/customfishing/fishing/bar/ModeOneBar.java create mode 100644 src/main/java/net/momirealms/customfishing/fishing/bar/ModeTwoBar.java rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/Competition.java (88%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/CompetitionConfig.java (95%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/CompetitionGoal.java (93%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/CompetitionPlayer.java (97%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/CompetitionSchedule.java (87%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/bossbar/BossBarConfig.java (95%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/bossbar/BossBarManager.java (85%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/bossbar/BossBarOverlay.java (92%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/bossbar/BossBarSender.java (89%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/ranking/LocalRankingImpl.java (96%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/ranking/RankingInterface.java (89%) rename src/main/java/net/momirealms/customfishing/{ => fishing}/competition/ranking/RedisRankingImpl.java (96%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/loot/DroppedItem.java (78%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/loot/Item.java (60%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/loot/Loot.java (65%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/loot/Mob.java (72%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/loot/MobVector.java (94%) create mode 100644 src/main/java/net/momirealms/customfishing/fishing/mode/FishingGame.java create mode 100644 src/main/java/net/momirealms/customfishing/fishing/mode/ModeOneGame.java create mode 100644 src/main/java/net/momirealms/customfishing/fishing/mode/ModeTwoGame.java rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/BiomeImpl.java (86%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/CustomPapi.java (96%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/PermissionImpl.java (88%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/RequirementInterface.java (86%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/SeasonImpl.java (84%) create mode 100644 src/main/java/net/momirealms/customfishing/fishing/requirements/SkillLevelImpl.java rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/TimeImpl.java (90%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/WeatherImpl.java (91%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/WorldImpl.java (89%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/YPosImpl.java (90%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/papi/ExpressionAnd.java (94%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/papi/ExpressionOr.java (94%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/papi/PapiEquals.java (94%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/papi/PapiGreater.java (94%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/papi/PapiNoLarger.java (94%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/papi/PapiNoLess.java (94%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/papi/PapiNotEquals.java (94%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/papi/PapiRequirement.java (93%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/requirements/papi/PapiSmaller.java (94%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/totem/ActivatedTotem.java (83%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/totem/CorePos.java (95%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/totem/FinalModel.java (97%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/totem/OriginalModel.java (97%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/totem/Totem.java (89%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/totem/TotemConfig.java (89%) rename src/main/java/net/momirealms/customfishing/{object => fishing}/totem/TotemParticle.java (97%) delete mode 100644 src/main/java/net/momirealms/customfishing/integration/AntiGriefInterface.java delete mode 100644 src/main/java/net/momirealms/customfishing/integration/antigrief/BentoBoxHook.java delete mode 100644 src/main/java/net/momirealms/customfishing/integration/antigrief/CrashClaimHook.java delete mode 100644 src/main/java/net/momirealms/customfishing/integration/antigrief/GriefDefenderHook.java delete mode 100644 src/main/java/net/momirealms/customfishing/integration/antigrief/GriefPreventionHook.java delete mode 100644 src/main/java/net/momirealms/customfishing/integration/antigrief/KingdomsXHook.java delete mode 100644 src/main/java/net/momirealms/customfishing/integration/antigrief/LandsHook.java delete mode 100644 src/main/java/net/momirealms/customfishing/integration/antigrief/PlotSquaredHook.java delete mode 100644 src/main/java/net/momirealms/customfishing/integration/antigrief/ResidenceHook.java delete mode 100644 src/main/java/net/momirealms/customfishing/integration/antigrief/TownyHook.java delete mode 100644 src/main/java/net/momirealms/customfishing/integration/antigrief/WorldGuardHook.java rename src/main/java/net/momirealms/customfishing/{object/fishing/Difficulty.java => listener/ConsumeItemListener.java} (55%) rename src/main/java/net/momirealms/customfishing/listener/{SimpleListener.java => JoinQuitListener.java} (94%) create mode 100644 src/main/java/net/momirealms/customfishing/manager/BarMechanicManager.java delete mode 100644 src/main/java/net/momirealms/customfishing/manager/BonusManager.java create mode 100644 src/main/java/net/momirealms/customfishing/manager/EffectManager.java delete mode 100644 src/main/java/net/momirealms/customfishing/manager/LayoutManager.java create mode 100644 src/main/java/net/momirealms/customfishing/manager/OffsetManager.java rename src/main/java/net/momirealms/customfishing/object/{TextCache.java => DynamicText.java} (88%) rename src/main/java/net/momirealms/customfishing/object/{loot => }/LeveledEnchantment.java (95%) delete mode 100644 src/main/java/net/momirealms/customfishing/object/fishing/FishingPlayer.java delete mode 100644 src/main/java/net/momirealms/customfishing/object/fishing/Layout.java delete mode 100644 src/main/java/net/momirealms/customfishing/object/fishing/Modifier.java delete mode 100644 src/main/java/net/momirealms/customfishing/object/requirements/SkillLevelImpl.java delete mode 100644 src/main/resources/bars.yml create mode 100644 src/main/resources/bars/default.yml rename src/main/resources/{competition.yml => competitions/default.yml} (100%) rename src/main/resources/{enchant-bonus.yml => enchants/default.yml} (100%) create mode 100644 src/main/resources/minigames/default.yml rename src/main/resources/mobs/{example.yml => default.yml} (94%) rename src/main/resources/{sell-fish.yml => sell-fish-gui.yml} (91%) rename src/main/resources/{totem-blocks.yml => totem-blocks/default.yml} (100%) rename src/main/resources/{totems.yml => totems/default.yml} (100%) rename src/main/resources/utils/{fishfinder.yml => fish_finder.yml} (100%) diff --git a/build.gradle b/build.gradle index 5cc96776..b1254a80 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } group = 'net.momirealms' -version = '1.2.23.2' +version = '1.3.0-beta-1' repositories { mavenCentral() diff --git a/src/main/java/net/momirealms/customfishing/CustomFishing.java b/src/main/java/net/momirealms/customfishing/CustomFishing.java index d1395990..11493e82 100644 --- a/src/main/java/net/momirealms/customfishing/CustomFishing.java +++ b/src/main/java/net/momirealms/customfishing/CustomFishing.java @@ -20,88 +20,61 @@ package net.momirealms.customfishing; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import net.kyori.adventure.platform.bukkit.BukkitAudiences; -import net.momirealms.biomeapi.BiomeAPI; import net.momirealms.customfishing.commands.FishingBagCommand; -import net.momirealms.customfishing.commands.PluginCommand; +import net.momirealms.customfishing.commands.MainCommand; import net.momirealms.customfishing.commands.SellFishCommand; import net.momirealms.customfishing.helper.LibraryLoader; import net.momirealms.customfishing.helper.VersionHelper; import net.momirealms.customfishing.manager.*; import net.momirealms.customfishing.util.AdventureUtil; -import net.momirealms.customfishing.util.ConfigUtil; import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; +import org.bukkit.command.PluginCommand; import org.bukkit.plugin.java.JavaPlugin; public final class CustomFishing extends JavaPlugin { - public static CustomFishing plugin; - public static BukkitAudiences adventure; - public static ProtocolManager protocolManager; + private static CustomFishing plugin; + private static BukkitAudiences adventure; + private static ProtocolManager protocolManager; private IntegrationManager integrationManager; private FishingManager fishingManager; private CompetitionManager competitionManager; - private BonusManager bonusManager; + private EffectManager effectManager; private LootManager lootManager; - private LayoutManager layoutManager; + private BarMechanicManager barMechanicManager; private BagDataManager bagDataManager; private TotemManager totemManager; private DataManager dataManager; private SellManager sellManager; + private OffsetManager offsetManager; private VersionHelper versionHelper; -// _ooOoo_ -// o8888888o -// 88" . "88 -// (| -_- |) -// O\ = /O -// ____/`---'\____ -// .' \\| |// `. -// / \\||| : |||// \ -// / _||||| -:- |||||_ \ -// | | \\\ - /'| | | -// | \_| `\`---'// |_/ | -// \ .-\__ `-. -'__/-. / -// ___`. .' /--.--\ `. .'___ -// ."" '< `.___\_<|>_/___.' _> \"". -// | | : `- \`. ;`. _/; .'/ / .' ; | -// \ \ `-. \_\_`. _.'_/_/ -' _.' / -// ================-.`___`-.__\ \___ /__.-'_.'_.-'================ -// `=--=-' -// 佛祖保佑 永无BUG 永不卡服 - @Override public void onLoad() { plugin = this; - LibraryLoader.load("redis.clients","jedis","4.3.1","https://repo.maven.apache.org/maven2/"); - LibraryLoader.load("org.apache.commons","commons-pool2","2.11.1","https://repo.maven.apache.org/maven2/"); - LibraryLoader.load("dev.dejvokep","boosted-yaml","1.3","https://repo.maven.apache.org/maven2/"); - LibraryLoader.load("com.zaxxer","HikariCP","5.0.1","https://repo.maven.apache.org/maven2/"); - LibraryLoader.load("net.objecthunter","exp4j","0.4.8","https://repo.maven.apache.org/maven2/"); - LibraryLoader.load("org.mariadb.jdbc","mariadb-java-client","3.0.6","https://repo.maven.apache.org/maven2/"); + loadLibs(); } @Override public void onEnable() { adventure = BukkitAudiences.create(this); protocolManager = ProtocolLibrary.getProtocolManager(); - - this.fishingManager = new FishingManager(); - this.dataManager = new DataManager(); - this.integrationManager = new IntegrationManager(); - this.competitionManager = new CompetitionManager(); - this.bonusManager = new BonusManager(); - this.lootManager = new LootManager(); - this.layoutManager = new LayoutManager(); + this.versionHelper = new VersionHelper(this); + this.fishingManager = new FishingManager(this); + this.dataManager = new DataManager(this); + this.integrationManager = new IntegrationManager(this); + this.competitionManager = new CompetitionManager(this); + this.effectManager = new EffectManager(this); + this.lootManager = new LootManager(this); + this.barMechanicManager = new BarMechanicManager(this); this.totemManager = new TotemManager(this); - this.sellManager = new SellManager(); - this.bagDataManager = new BagDataManager(); - this.versionHelper = new VersionHelper(); - - reloadConfig(); - registerCommands(); - registerQuests(); - + this.sellManager = new SellManager(this); + this.bagDataManager = new BagDataManager(this); + this.offsetManager = new OffsetManager(this); + this.reload(); + this.registerCommands(); + this.registerQuests(); AdventureUtil.consoleMessage("[CustomFishing] Plugin Enabled!"); new Metrics(this, 16648); } @@ -111,40 +84,46 @@ public final class CustomFishing extends JavaPlugin { this.fishingManager.unload(); this.integrationManager.unload(); this.competitionManager.unload(); - this.bonusManager.unload(); + this.effectManager.unload(); this.lootManager.unload(); - this.layoutManager.unload(); - this.bagDataManager.unload(); + this.barMechanicManager.unload(); this.bagDataManager.disable(); this.totemManager.unload(); - this.sellManager.unload(); this.sellManager.disable(); this.dataManager.unload(); - if (adventure != null) { adventure.close(); - adventure = null; } } private void registerCommands() { - PluginCommand pluginCommand = new PluginCommand(); - Bukkit.getPluginCommand("customfishing").setExecutor(pluginCommand); - Bukkit.getPluginCommand("customfishing").setTabCompleter(pluginCommand); + MainCommand mainCommand = new MainCommand(); + PluginCommand cfCommand = Bukkit.getPluginCommand("customfishing"); + if (cfCommand != null) { + cfCommand.setExecutor(mainCommand); + cfCommand.setTabCompleter(mainCommand); + } FishingBagCommand fishingBagCommand = new FishingBagCommand(); - Bukkit.getPluginCommand("fishingbag").setExecutor(fishingBagCommand); - Bukkit.getPluginCommand("fishingbag").setTabCompleter(fishingBagCommand); + PluginCommand fbCommand = Bukkit.getPluginCommand("fishingbag"); + if (fbCommand != null) { + fbCommand.setExecutor(fishingBagCommand); + fbCommand.setTabCompleter(fishingBagCommand); + } SellFishCommand sellFishCommand = new SellFishCommand(); - Bukkit.getPluginCommand("sellfish").setExecutor(sellFishCommand); - Bukkit.getPluginCommand("sellfish").setTabCompleter(sellFishCommand); + PluginCommand sfCommand = Bukkit.getPluginCommand("sellfish"); + if (sfCommand != null) { + sfCommand.setExecutor(sellFishCommand); + sfCommand.setTabCompleter(sellFishCommand); + } } - public static CustomFishing getInstance() { - return plugin; - } - - public void reloadConfig() { - ConfigUtil.reload(); + private void loadLibs() { + LibraryLoader.load("redis.clients","jedis","4.3.1","https://repo.maven.apache.org/maven2/"); + LibraryLoader.load("org.apache.commons","commons-pool2","2.11.1","https://repo.maven.apache.org/maven2/"); + LibraryLoader.load("dev.dejvokep","boosted-yaml","1.3","https://repo.maven.apache.org/maven2/"); + LibraryLoader.load("com.zaxxer","HikariCP","5.0.1","https://repo.maven.apache.org/maven2/"); + LibraryLoader.load("net.objecthunter","exp4j","0.4.8","https://repo.maven.apache.org/maven2/"); + LibraryLoader.load("org.mariadb.jdbc","mariadb-java-client","3.0.6","https://repo.maven.apache.org/maven2/"); } private void registerQuests() { @@ -163,18 +142,14 @@ public final class CustomFishing extends JavaPlugin { return competitionManager; } - public BonusManager getBonusManager() { - return bonusManager; + public EffectManager getEffectManager() { + return effectManager; } public LootManager getLootManager() { return lootManager; } - public LayoutManager getLayoutManager() { - return layoutManager; - } - public TotemManager getTotemManager() { return totemManager; } @@ -194,4 +169,49 @@ public final class CustomFishing extends JavaPlugin { public VersionHelper getVersionHelper() { return versionHelper; } + + public BarMechanicManager getBarMechanicManager() { + return barMechanicManager; + } + + public OffsetManager getOffsetManager() { + return offsetManager; + } + + public void reload() { + ConfigManager.load(); + MessageManager.load(); + getIntegrationManager().unload(); + getIntegrationManager().load(); + getBarMechanicManager().unload(); + getBarMechanicManager().load(); + getEffectManager().unload(); + getEffectManager().load(); + getOffsetManager().unload(); + getOffsetManager().load(); + getLootManager().unload(); + getLootManager().load(); + getTotemManager().unload(); + getTotemManager().load(); + getFishingManager().unload(); + getFishingManager().load(); + getSellManager().unload(); + getSellManager().load(); + getCompetitionManager().unload(); + getCompetitionManager().load(); + getBagDataManager().unload(); + getBagDataManager().load(); + } + + public static BukkitAudiences getAdventure() { + return adventure; + } + + public static ProtocolManager getProtocolManager() { + return protocolManager; + } + + public static CustomFishing getInstance() { + return plugin; + } } diff --git a/src/main/java/net/momirealms/customfishing/api/CustomFishingAPI.java b/src/main/java/net/momirealms/customfishing/api/CustomFishingAPI.java index edc6ea7a..d87e0089 100644 --- a/src/main/java/net/momirealms/customfishing/api/CustomFishingAPI.java +++ b/src/main/java/net/momirealms/customfishing/api/CustomFishingAPI.java @@ -18,7 +18,7 @@ package net.momirealms.customfishing.api; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.competition.Competition; +import net.momirealms.customfishing.fishing.competition.Competition; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Nullable; @@ -38,7 +38,7 @@ public class CustomFishingAPI { * @return size */ public static float getFishSize(ItemStack fish) { - return CustomFishing.plugin.getFishingManager().getSize(fish); + return CustomFishing.getInstance().getFishingManager().getSize(fish); } /** @@ -46,7 +46,7 @@ public class CustomFishingAPI { * @return plugin instance */ public static CustomFishing getInstance() { - return CustomFishing.plugin; + return CustomFishing.getInstance(); } /** @@ -55,7 +55,7 @@ public class CustomFishingAPI { * @return price */ public static double getItemPrice(ItemStack itemStack) { - return CustomFishing.plugin.getSellManager().getSingleItemPrice(itemStack); + return CustomFishing.getInstance().getSellManager().getSingleItemPrice(itemStack); } /** @@ -64,6 +64,6 @@ public class CustomFishingAPI { * @return itemStack */ public static ItemStack buildItem(String id) { - return CustomFishing.plugin.getIntegrationManager().build(id); + return CustomFishing.getInstance().getIntegrationManager().build(id); } } diff --git a/src/main/java/net/momirealms/customfishing/api/event/FishFinderEvent.java b/src/main/java/net/momirealms/customfishing/api/event/FishFinderEvent.java index 8f2a6416..bdd7507f 100644 --- a/src/main/java/net/momirealms/customfishing/api/event/FishFinderEvent.java +++ b/src/main/java/net/momirealms/customfishing/api/event/FishFinderEvent.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.api.event; -import net.momirealms.customfishing.object.loot.Loot; +import net.momirealms.customfishing.fishing.loot.Loot; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; diff --git a/src/main/java/net/momirealms/customfishing/api/event/FishHookEvent.java b/src/main/java/net/momirealms/customfishing/api/event/FishHookEvent.java index 72460710..b289455e 100644 --- a/src/main/java/net/momirealms/customfishing/api/event/FishHookEvent.java +++ b/src/main/java/net/momirealms/customfishing/api/event/FishHookEvent.java @@ -17,7 +17,6 @@ package net.momirealms.customfishing.api.event; -import net.momirealms.customfishing.object.fishing.Difficulty; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; @@ -27,10 +26,10 @@ import org.jetbrains.annotations.NotNull; public class FishHookEvent extends PlayerEvent implements Cancellable { private boolean cancelled; - private final Difficulty difficulty; + private int difficulty; private static final HandlerList handlerList = new HandlerList(); - public FishHookEvent(@NotNull Player who, Difficulty difficulty) { + public FishHookEvent(@NotNull Player who, int difficulty) { super(who); this.cancelled = false; this.difficulty = difficulty; @@ -56,7 +55,11 @@ public class FishHookEvent extends PlayerEvent implements Cancellable { return getHandlerList(); } - public Difficulty getDifficulty() { + public int getDifficulty() { return difficulty; } + + public void setDifficulty(int difficulty) { + this.difficulty = difficulty; + } } diff --git a/src/main/java/net/momirealms/customfishing/api/event/FishResultEvent.java b/src/main/java/net/momirealms/customfishing/api/event/FishResultEvent.java index 531cb7a5..9f1e016c 100644 --- a/src/main/java/net/momirealms/customfishing/api/event/FishResultEvent.java +++ b/src/main/java/net/momirealms/customfishing/api/event/FishResultEvent.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.api.event; -import net.momirealms.customfishing.object.fishing.FishResult; +import net.momirealms.customfishing.fishing.FishResult; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; diff --git a/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java b/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java index e8e070a9..40346870 100644 --- a/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java +++ b/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.api.event; -import net.momirealms.customfishing.object.fishing.Bonus; +import net.momirealms.customfishing.fishing.Effect; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; @@ -26,14 +26,14 @@ import org.jetbrains.annotations.NotNull; public class RodCastEvent extends PlayerEvent implements Cancellable { - private final Bonus bonus; + private final Effect effect; private boolean isCancelled; private static final HandlerList handlerList = new HandlerList(); - public RodCastEvent(@NotNull Player who, @NotNull Bonus bonus) { + public RodCastEvent(@NotNull Player who, @NotNull Effect effect) { super(who); this.isCancelled = false; - this.bonus = bonus; + this.effect = effect; } @Override @@ -56,7 +56,7 @@ public class RodCastEvent extends PlayerEvent implements Cancellable { return getHandlerList(); } - public Bonus getBonus() { - return bonus; + public Effect getBonus() { + return effect; } } diff --git a/src/main/java/net/momirealms/customfishing/api/event/TotemActivationEvent.java b/src/main/java/net/momirealms/customfishing/api/event/TotemActivationEvent.java index 639e1540..e3238feb 100644 --- a/src/main/java/net/momirealms/customfishing/api/event/TotemActivationEvent.java +++ b/src/main/java/net/momirealms/customfishing/api/event/TotemActivationEvent.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.api.event; -import net.momirealms.customfishing.object.totem.TotemConfig; +import net.momirealms.customfishing.fishing.totem.TotemConfig; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; diff --git a/src/main/java/net/momirealms/customfishing/commands/PluginCommand.java b/src/main/java/net/momirealms/customfishing/commands/MainCommand.java similarity index 97% rename from src/main/java/net/momirealms/customfishing/commands/PluginCommand.java rename to src/main/java/net/momirealms/customfishing/commands/MainCommand.java index e7c0efeb..7e29bf37 100644 --- a/src/main/java/net/momirealms/customfishing/commands/PluginCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/MainCommand.java @@ -29,11 +29,11 @@ import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.ConcurrentHashMap; -public class PluginCommand implements TabExecutor { +public class MainCommand implements TabExecutor { private final Map subCommandMap; - public PluginCommand() { + public MainCommand() { subCommandMap = new ConcurrentHashMap<>(); regDefaultSubCommands(); } diff --git a/src/main/java/net/momirealms/customfishing/commands/SellFishCommand.java b/src/main/java/net/momirealms/customfishing/commands/SellFishCommand.java index ae3a141c..103db704 100644 --- a/src/main/java/net/momirealms/customfishing/commands/SellFishCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/SellFishCommand.java @@ -38,7 +38,7 @@ public class SellFishCommand implements TabExecutor { return true; } player.closeInventory(); - CustomFishing.plugin.getSellManager().openGuiForPlayer(player); + CustomFishing.getInstance().getSellManager().openGuiForPlayer(player); return true; } diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/BaitCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/BaitCommand.java index d3e72411..4b0d3f90 100644 --- a/src/main/java/net/momirealms/customfishing/commands/subcmd/BaitCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/BaitCommand.java @@ -17,9 +17,9 @@ package net.momirealms.customfishing.commands.subcmd; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.commands.AbstractSubCommand; import net.momirealms.customfishing.commands.SubCommand; -import net.momirealms.customfishing.manager.BonusManager; import net.momirealms.customfishing.manager.MessageManager; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ItemStackUtil; @@ -45,7 +45,7 @@ public class BaitCommand extends AbstractSubCommand { } else if (args.get(0).equalsIgnoreCase("get")) { if (sender instanceof Player player){ - if (!BonusManager.BAITITEMS.containsKey(args.get(1))){ + if (!CustomFishing.getInstance().getEffectManager().getBaitItems().containsKey(args.get(1))) { AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.itemNotExist); return true; } @@ -74,7 +74,7 @@ public class BaitCommand extends AbstractSubCommand { AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1))); return true; } - if (!BonusManager.BAITITEMS.containsKey(args.get(2))){ + if (!CustomFishing.getInstance().getEffectManager().getBaitItems().containsKey(args.get(1))) { AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.itemNotExist); return true; } @@ -138,6 +138,6 @@ public class BaitCommand extends AbstractSubCommand { } private List baits() { - return new ArrayList<>(BonusManager.BAITITEMS.keySet()); + return new ArrayList<>(CustomFishing.getInstance().getEffectManager().getBaitItems().keySet()); } } diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/CompetitionCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/CompetitionCommand.java index 1e2b8543..6daca7b6 100644 --- a/src/main/java/net/momirealms/customfishing/commands/subcmd/CompetitionCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/CompetitionCommand.java @@ -17,10 +17,10 @@ package net.momirealms.customfishing.commands.subcmd; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.commands.AbstractSubCommand; import net.momirealms.customfishing.commands.SubCommand; -import net.momirealms.customfishing.competition.CompetitionSchedule; -import net.momirealms.customfishing.manager.CompetitionManager; +import net.momirealms.customfishing.fishing.competition.CompetitionSchedule; import net.momirealms.customfishing.manager.MessageManager; import net.momirealms.customfishing.util.AdventureUtil; import org.bukkit.command.CommandSender; @@ -42,22 +42,23 @@ public class CompetitionCommand extends AbstractSubCommand { AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); return true; } - if (args.get(0).equals("start")){ - if (args.size() < 2){ - AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); - return true; + switch (args.get(0)) { + case "start" -> { + if (args.size() < 2) { + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); + return true; + } + if (CompetitionSchedule.startCompetition(args.get(1))) AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceSuccess); + else AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceFailure); } - if (CompetitionSchedule.startCompetition(args.get(1))){ - AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceSuccess); - } else { - AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceFailure); + case "end" -> { + CompetitionSchedule.endCompetition(); + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceEnd); + } + case "cancel" -> { + CompetitionSchedule.cancelCompetition(); + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceCancel); } - } else if (args.get(0).equals("end")) { - CompetitionSchedule.endCompetition(); - AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceEnd); - } else if (args.get(0).equals("cancel")) { - CompetitionSchedule.cancelCompetition(); - AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceCancel); } return true; } @@ -79,6 +80,6 @@ public class CompetitionCommand extends AbstractSubCommand { } private List competitions() { - return new ArrayList<>(CompetitionManager.competitionsC.keySet()); + return new ArrayList<>(CustomFishing.getInstance().getCompetitionManager().getCompetitionsC().keySet()); } } diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/LootCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/LootCommand.java index ba3e1b4d..3ebf49aa 100644 --- a/src/main/java/net/momirealms/customfishing/commands/subcmd/LootCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/LootCommand.java @@ -17,12 +17,12 @@ package net.momirealms.customfishing.commands.subcmd; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.commands.AbstractSubCommand; import net.momirealms.customfishing.commands.SubCommand; -import net.momirealms.customfishing.manager.LootManager; +import net.momirealms.customfishing.fishing.loot.DroppedItem; +import net.momirealms.customfishing.fishing.loot.Loot; import net.momirealms.customfishing.manager.MessageManager; -import net.momirealms.customfishing.object.loot.DroppedItem; -import net.momirealms.customfishing.object.loot.Loot; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ItemStackUtil; import org.bukkit.Bukkit; @@ -142,12 +142,12 @@ public class LootCommand extends AbstractSubCommand { private List loots() { List loots = new ArrayList<>(); - for (Map.Entry en : LootManager.WATERLOOTS.entrySet()) { + for (Map.Entry en : CustomFishing.getInstance().getLootManager().getWaterLoots().entrySet()) { if (en.getValue() instanceof DroppedItem) { loots.add(en.getKey()); } } - for (Map.Entry en : LootManager.LAVALOOTS.entrySet()) { + for (Map.Entry en : CustomFishing.getInstance().getLootManager().getLavaLoots().entrySet()) { if (en.getValue() instanceof DroppedItem) { loots.add(en.getKey()); } diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/OpenBagCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/OpenBagCommand.java index 370197d3..a0ca3807 100644 --- a/src/main/java/net/momirealms/customfishing/commands/subcmd/OpenBagCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/OpenBagCommand.java @@ -29,17 +29,13 @@ public class OpenBagCommand extends AbstractSubCommand { return true; } if (args.size() == 1) { - if (!sender.hasPermission("customfishing.admin")) { - AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.noPerm); - return true; - } Player viewer = Bukkit.getPlayer(args.get(0)); if (viewer == null) { AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.playerNotExist); return true; } viewer.closeInventory(); - CustomFishing.plugin.getBagDataManager().openFishingBag(viewer, viewer); + CustomFishing.getInstance().getBagDataManager().openFishingBag(viewer, viewer); } return true; } @@ -47,7 +43,6 @@ public class OpenBagCommand extends AbstractSubCommand { @Override public List onTabComplete(CommandSender sender, List args) { if (!ConfigManager.enableFishingBag) return null; - if (!sender.hasPermission("customfishing.admin")) return null; if (args.size() == 1) { List arrayList = new ArrayList<>(); for (String cmd : online_players()) { diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/OpenCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/OpenCommand.java index eea0e5b9..44086f75 100644 --- a/src/main/java/net/momirealms/customfishing/commands/subcmd/OpenCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/OpenCommand.java @@ -52,7 +52,7 @@ public class OpenCommand extends AbstractSubCommand { return true; } player.closeInventory(); - CustomFishing.plugin.getBagDataManager().openFishingBag(player, player); + CustomFishing.getInstance().getBagDataManager().openFishingBag(player, player); } if (args.size() == 1) { if (!sender.hasPermission("customfishing.admin")) { @@ -65,7 +65,7 @@ public class OpenCommand extends AbstractSubCommand { return true; } player.closeInventory(); - CustomFishing.plugin.getBagDataManager().openFishingBag(player, offlinePlayer); + CustomFishing.getInstance().getBagDataManager().openFishingBag(player, offlinePlayer); } return true; } diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/ReloadCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/ReloadCommand.java index 7ac6c70e..221b8804 100644 --- a/src/main/java/net/momirealms/customfishing/commands/subcmd/ReloadCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/ReloadCommand.java @@ -18,11 +18,11 @@ package net.momirealms.customfishing.commands.subcmd; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.commands.AbstractSubCommand; import net.momirealms.customfishing.commands.SubCommand; import net.momirealms.customfishing.manager.MessageManager; import net.momirealms.customfishing.util.AdventureUtil; -import net.momirealms.customfishing.util.ConfigUtil; import org.bukkit.command.CommandSender; import java.util.List; @@ -39,7 +39,7 @@ public final class ReloadCommand extends AbstractSubCommand { public boolean onCommand(CommandSender sender, List args) { if (args.size() < 1) { long time1 = System.currentTimeMillis(); - ConfigUtil.reload(); + CustomFishing.getInstance().reload(); AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.reload.replace("{time}", String.valueOf(System.currentTimeMillis() - time1))); return true; } diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/RodCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/RodCommand.java index 76256827..2b232c43 100644 --- a/src/main/java/net/momirealms/customfishing/commands/subcmd/RodCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/RodCommand.java @@ -17,9 +17,9 @@ package net.momirealms.customfishing.commands.subcmd; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.commands.AbstractSubCommand; import net.momirealms.customfishing.commands.SubCommand; -import net.momirealms.customfishing.manager.BonusManager; import net.momirealms.customfishing.manager.MessageManager; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ItemStackUtil; @@ -46,7 +46,7 @@ public class RodCommand extends AbstractSubCommand { } if (args.get(0).equalsIgnoreCase("get")) { if (sender instanceof Player player){ - if (!BonusManager.RODITEMS.containsKey(args.get(1))){ + if (!CustomFishing.getInstance().getEffectManager().getRodItems().containsKey(args.get(1))){ AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.itemNotExist); return true; } @@ -75,7 +75,7 @@ public class RodCommand extends AbstractSubCommand { AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1))); return true; } - if (!BonusManager.RODITEMS.containsKey(args.get(2))){ + if (!CustomFishing.getInstance().getEffectManager().getRodItems().containsKey(args.get(2))){ AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.itemNotExist); return true; } @@ -139,6 +139,6 @@ public class RodCommand extends AbstractSubCommand { } private List rods() { - return new ArrayList<>(BonusManager.RODITEMS.keySet()); + return new ArrayList<>(CustomFishing.getInstance().getEffectManager().getRodItems().keySet()); } } diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/SellShopCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/SellShopCommand.java index e29a5b57..5f2e2678 100644 --- a/src/main/java/net/momirealms/customfishing/commands/subcmd/SellShopCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/SellShopCommand.java @@ -33,7 +33,7 @@ public class SellShopCommand extends AbstractSubCommand { } player.closeInventory(); - CustomFishing.plugin.getSellManager().openGuiForPlayer(player); + CustomFishing.getInstance().getSellManager().openGuiForPlayer(player); return true; } diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/UtilCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/UtilCommand.java index edc413ad..66584b1b 100644 --- a/src/main/java/net/momirealms/customfishing/commands/subcmd/UtilCommand.java +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/UtilCommand.java @@ -17,9 +17,9 @@ package net.momirealms.customfishing.commands.subcmd; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.commands.AbstractSubCommand; import net.momirealms.customfishing.commands.SubCommand; -import net.momirealms.customfishing.manager.BonusManager; import net.momirealms.customfishing.manager.MessageManager; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ItemStackUtil; @@ -45,7 +45,7 @@ public class UtilCommand extends AbstractSubCommand { } else if (args.get(0).equalsIgnoreCase("get")) { if (sender instanceof Player player){ - if (!BonusManager.UTILITEMS.containsKey(args.get(1))){ + if (!CustomFishing.getInstance().getEffectManager().getUtilItems().containsKey(args.get(1))){ AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.itemNotExist); return true; } @@ -74,7 +74,7 @@ public class UtilCommand extends AbstractSubCommand { AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1))); return true; } - if (!BonusManager.UTILITEMS.containsKey(args.get(2))){ + if (!CustomFishing.getInstance().getEffectManager().getUtilItems().containsKey(args.get(2))){ AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.itemNotExist); return true; } @@ -138,6 +138,6 @@ public class UtilCommand extends AbstractSubCommand { } private List utils() { - return new ArrayList<>(BonusManager.UTILITEMS.keySet()); + return new ArrayList<>(CustomFishing.getInstance().getEffectManager().getUtilItems().keySet()); } } diff --git a/src/main/java/net/momirealms/customfishing/data/storage/FileStorageImpl.java b/src/main/java/net/momirealms/customfishing/data/storage/FileStorageImpl.java index 5583a248..02c1e6fc 100644 --- a/src/main/java/net/momirealms/customfishing/data/storage/FileStorageImpl.java +++ b/src/main/java/net/momirealms/customfishing/data/storage/FileStorageImpl.java @@ -35,26 +35,25 @@ import java.util.UUID; public class FileStorageImpl implements DataStorageInterface { - private YamlConfiguration data; + private final CustomFishing plugin; + + public FileStorageImpl(CustomFishing plugin) { + this.plugin = plugin; + } @Override public void initialize() { - data = ConfigUtil.readData(new File(CustomFishing.plugin.getDataFolder(), "sell-cache.yml")); + } @Override public void disable() { - try { - data.save(new File(CustomFishing.plugin.getDataFolder(), "sell-cache.yml")); - } - catch (IOException e) { - e.printStackTrace(); - } + } @Override public Inventory loadBagData(OfflinePlayer player) { - YamlConfiguration config = ConfigUtil.readData(new File(CustomFishing.plugin.getDataFolder(), "fishingbag_data" + File.separator + player.getUniqueId() + ".yml")); + YamlConfiguration config = ConfigUtil.readData(new File(plugin.getDataFolder(), "fishingbag_data" + File.separator + player.getUniqueId() + ".yml")); String contents = config.getString("contents"); int size = config.getInt("size", 9); ItemStack[] itemStacks = InventoryUtil.getInventoryItems(contents); @@ -71,7 +70,7 @@ public class FileStorageImpl implements DataStorageInterface { data.set("contents", contents); data.set("size", inventory.getSize()); try { - data.save(new File(CustomFishing.plugin.getDataFolder(), "fishingbag_data" + File.separator + playerBagData.getPlayer().getUniqueId() + ".yml")); + data.save(new File(plugin.getDataFolder(), "fishingbag_data" + File.separator + playerBagData.getPlayer().getUniqueId() + ".yml")); } catch (IOException e) { e.printStackTrace(); @@ -81,14 +80,22 @@ public class FileStorageImpl implements DataStorageInterface { @Override public void loadSellCache(Player player) { UUID uuid = player.getUniqueId(); - int date = data.getInt(uuid + ".date"); - double money = data.getDouble(uuid + ".sell"); - CustomFishing.plugin.getSellManager().loadPlayerToCache(player.getUniqueId(), date, money); + YamlConfiguration data = ConfigUtil.readData(new File(plugin.getDataFolder(), "sell-data" + File.separator + uuid + ".yml")); + int date = data.getInt("date"); + double money = data.getDouble("earnings"); + plugin.getSellManager().loadPlayerToCache(player.getUniqueId(), date, money); } @Override public void saveSellCache(UUID uuid, PlayerSellData playerSellData) { - data.set(uuid + ".date", playerSellData.getDate()); - data.set(uuid + ".sell", playerSellData.getMoney()); + YamlConfiguration data = new YamlConfiguration(); + data.set("date", playerSellData.getDate()); + data.set("earnings", playerSellData.getMoney()); + try { + data.save(new File(plugin.getDataFolder(), "sell-data" + File.separator + uuid + ".yml")); + } + catch (IOException e) { + e.printStackTrace(); + } } } diff --git a/src/main/java/net/momirealms/customfishing/data/storage/MySQLStorageImpl.java b/src/main/java/net/momirealms/customfishing/data/storage/MySQLStorageImpl.java index 90d2c867..5169af40 100644 --- a/src/main/java/net/momirealms/customfishing/data/storage/MySQLStorageImpl.java +++ b/src/main/java/net/momirealms/customfishing/data/storage/MySQLStorageImpl.java @@ -37,7 +37,13 @@ import java.util.UUID; public class MySQLStorageImpl implements DataStorageInterface { - public static SqlConnection sqlConnection = new SqlConnection(); + private final SqlConnection sqlConnection; + private final CustomFishing plugin; + + public MySQLStorageImpl(CustomFishing plugin) { + this.plugin = plugin; + this.sqlConnection = new SqlConnection(this); + } @Override public void initialize() { @@ -54,10 +60,8 @@ public class MySQLStorageImpl implements DataStorageInterface { @Override public Inventory loadBagData(OfflinePlayer player) { Inventory inventory = null; - try { - Connection connection = sqlConnection.getConnectionAndCheck(); - String sql = String.format(SqlConstants.SQL_SELECT_BAG_BY_UUID, sqlConnection.getTablePrefix() + "_fishingbag");; - PreparedStatement statement = connection.prepareStatement(sql); + String sql = String.format(SqlConstants.SQL_SELECT_BAG_BY_UUID, sqlConnection.getTablePrefix() + "_fishingbag"); + try (Connection connection = sqlConnection.getConnectionAndCheck(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, player.getUniqueId().toString()); ResultSet rs = statement.executeQuery(); if (rs.next()) { @@ -70,7 +74,6 @@ public class MySQLStorageImpl implements DataStorageInterface { else { inventory = Bukkit.createInventory(null, 9, "{CustomFishing_Bag_" + player.getName() + "}"); } - connection.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -93,21 +96,18 @@ public class MySQLStorageImpl implements DataStorageInterface { @Override public void loadSellCache(Player player) { - try { - Connection connection = sqlConnection.getConnectionAndCheck(); - String sql = String.format(SqlConstants.SQL_SELECT_SELL_BY_UUID, sqlConnection.getTablePrefix() + "_sellcache"); - PreparedStatement statement = connection.prepareStatement(sql); + String sql = String.format(SqlConstants.SQL_SELECT_SELL_BY_UUID, sqlConnection.getTablePrefix() + "_sellcache"); + try (Connection connection = sqlConnection.getConnectionAndCheck(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, player.getUniqueId().toString()); ResultSet rs = statement.executeQuery(); if (rs.next()) { int date = rs.getInt(2); int money = rs.getInt(3); - CustomFishing.plugin.getSellManager().loadPlayerToCache(player.getUniqueId(), date, money); + plugin.getSellManager().loadPlayerToCache(player.getUniqueId(), date, money); } else { - CustomFishing.plugin.getSellManager().loadPlayerToCache(player.getUniqueId(), Calendar.getInstance().get(Calendar.DATE), 0); + plugin.getSellManager().loadPlayerToCache(player.getUniqueId(), Calendar.getInstance().get(Calendar.DATE), 0); } - connection.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -125,11 +125,8 @@ public class MySQLStorageImpl implements DataStorageInterface { private void createTableIfNotExist(String table, String sqlStat) { String sql = String.format(sqlStat, table); - try { - Connection connection = sqlConnection.getConnection(); - PreparedStatement statement = connection.prepareStatement(sql); + try (Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.executeUpdate(); - connection.close(); } catch (SQLException ex) { AdventureUtil.consoleMessage("[CustomFishing] Failed to create table"); } @@ -137,13 +134,11 @@ public class MySQLStorageImpl implements DataStorageInterface { private void insertBagData(UUID uuid, int size, String contents) { String sql = String.format(SqlConstants.SQL_INSERT_BAG, sqlConnection.getTablePrefix() + "_fishingbag"); - try { - Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql); + try (Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, uuid.toString()); statement.setInt(2, size); statement.setString(3, contents); statement.executeUpdate(); - connection.close(); } catch (SQLException ex) { AdventureUtil.consoleMessage("[CustomFishing] Failed to insert data for " + uuid); } @@ -151,13 +146,11 @@ public class MySQLStorageImpl implements DataStorageInterface { private void insertSellData(UUID uuid, int date, int money) { String sql = String.format(SqlConstants.SQL_INSERT_SELL, sqlConnection.getTablePrefix() + "_sellcache"); - try { - Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql); + try (Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, uuid.toString()); statement.setInt(2, date); statement.setInt(3, money); statement.executeUpdate(); - connection.close(); } catch (SQLException ex) { AdventureUtil.consoleMessage("[CustomFishing] Failed to insert data for " + uuid); } @@ -165,13 +158,11 @@ public class MySQLStorageImpl implements DataStorageInterface { private void updateBagData(UUID uuid, int size, String contents) { String sql = String.format(SqlConstants.SQL_UPDATE_BAG_BY_UUID, sqlConnection.getTablePrefix() + "_fishingbag"); - try { - Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql); + try (Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, size); statement.setString(2, contents); statement.setString(3, uuid.toString()); statement.executeUpdate(); - connection.close(); } catch (SQLException ex) { AdventureUtil.consoleMessage("[CustomFishing] Failed to update data for " + uuid); } @@ -179,13 +170,11 @@ public class MySQLStorageImpl implements DataStorageInterface { private void updateSellData(UUID uuid, int date, int money) { String sql = String.format(SqlConstants.SQL_UPDATE_SELL_BY_UUID, sqlConnection.getTablePrefix() + "_sellcache"); - try { - Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql); + try (Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, date); statement.setInt(2, money); statement.setString(3, uuid.toString()); statement.executeUpdate(); - connection.close(); } catch (SQLException ex) { AdventureUtil.consoleMessage("[CustomFishing] Failed to update data for " + uuid); } @@ -194,16 +183,31 @@ public class MySQLStorageImpl implements DataStorageInterface { public boolean exists(UUID uuid, String sqlStat, String suffix) { String sql = String.format(sqlStat, sqlConnection.getTablePrefix() + "_" + suffix); boolean exist; - try { - Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql); + try (Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, uuid.toString()); ResultSet rs = statement.executeQuery(); exist = rs.next(); - connection.close(); } catch (SQLException ex) { AdventureUtil.consoleMessage("[CustomFishing] Failed to select data for " + uuid); return false; } return exist; } + + public void migrate() { + String sql_1 = String.format(SqlConstants.SQL_ALTER_TABLE, sqlConnection.getTablePrefix() + "_fishingbag"); + try (Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql_1)) { + statement.executeUpdate(); + AdventureUtil.consoleMessage("[CustomFishing] 1/2 tables updated"); + } catch (SQLException ex) { + AdventureUtil.consoleMessage("[CustomFishing] Failed to migrate data"); + } + String sql_2 = String.format(SqlConstants.SQL_ALTER_TABLE, sqlConnection.getTablePrefix() + "_sellcache"); + try (Connection connection = sqlConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(sql_2)) { + statement.executeUpdate(); + AdventureUtil.consoleMessage("[CustomFishing] 2/2 tables updated"); + } catch (SQLException ex) { + AdventureUtil.consoleMessage("[CustomFishing] Failed to migrate data"); + } + } } diff --git a/src/main/java/net/momirealms/customfishing/data/storage/SqlConnection.java b/src/main/java/net/momirealms/customfishing/data/storage/SqlConnection.java index 3f2d348c..04d5c878 100644 --- a/src/main/java/net/momirealms/customfishing/data/storage/SqlConnection.java +++ b/src/main/java/net/momirealms/customfishing/data/storage/SqlConnection.java @@ -20,10 +20,13 @@ package net.momirealms.customfishing.data.storage; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.pool.HikariPool; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ConfigUtil; import org.bukkit.configuration.file.YamlConfiguration; +import java.io.File; +import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; @@ -33,9 +36,14 @@ public class SqlConnection { private boolean firstTry = false; private HikariDataSource hikariDataSource; private String tablePrefix; + private final MySQLStorageImpl mySQLStorage; + + public SqlConnection(MySQLStorageImpl mySQLStorage) { + this.mySQLStorage = mySQLStorage; + } public void createNewHikariConfiguration() { - + ConfigUtil.update("database.yml"); YamlConfiguration config = ConfigUtil.getConfig("database.yml"); String storageMode = config.getString("data-storage-method", "MySQL"); @@ -68,6 +76,17 @@ public class SqlConnection { } catch (HikariPool.PoolInitializationException e) { AdventureUtil.consoleMessage("[CustomFishing] Failed to create sql connection"); } + + if (config.getBoolean("migration", false)) { + mySQLStorage.migrate(); + config.set("migration", false); + try { + config.save(new File(CustomFishing.getInstance().getDataFolder(), "database.yml")); + } + catch (IOException e) { + AdventureUtil.consoleMessage("[CustomFishing] Error occurred when saving database config"); + } + } } public boolean setGlobalConnection() { diff --git a/src/main/java/net/momirealms/customfishing/data/storage/SqlConstants.java b/src/main/java/net/momirealms/customfishing/data/storage/SqlConstants.java index fb15ac2e..1b8f6b05 100644 --- a/src/main/java/net/momirealms/customfishing/data/storage/SqlConstants.java +++ b/src/main/java/net/momirealms/customfishing/data/storage/SqlConstants.java @@ -19,12 +19,14 @@ package net.momirealms.customfishing.data.storage; public class SqlConstants { - public static final String SQL_CREATE_BAG_TABLE = "CREATE TABLE IF NOT EXISTS `%s` ( `uuid` VARCHAR(36) NOT NULL , `size` INT(8) NOT NULL , `contents` LONGTEXT NOT NULL , PRIMARY KEY (`uuid`) )"; - public static final String SQL_CREATE_SELL_TABLE = "CREATE TABLE IF NOT EXISTS `%s` ( `uuid` VARCHAR(36) NOT NULL , `date` INT(4) NOT NULL , `money` INT(12) NOT NULL , PRIMARY KEY (`uuid`) )"; - public static final String SQL_INSERT_BAG = "INSERT INTO `%s`(`uuid`, `size`, `contents`) VALUES (?, ?, ?)"; - public static final String SQL_INSERT_SELL = "INSERT INTO `%s`(`uuid`, `date`, `money`) VALUES (?, ?, ?)"; - public static final String SQL_UPDATE_BAG_BY_UUID = "UPDATE `%s` SET `size` = ?, `contents` = ? WHERE `uuid` = ?"; - public static final String SQL_UPDATE_SELL_BY_UUID = "UPDATE `%s` SET `date` = ?, `money` = ? WHERE `uuid` = ?"; + public static final String SQL_CREATE_BAG_TABLE = "CREATE TABLE IF NOT EXISTS `%s` ( `uuid` VARCHAR(36) NOT NULL, `version` INT(2) NOT NULL, `size` INT(8) NOT NULL, `contents` LONGTEXT NOT NULL, PRIMARY KEY (`uuid`) )"; + public static final String SQL_CREATE_SELL_TABLE = "CREATE TABLE IF NOT EXISTS `%s` ( `uuid` VARCHAR(36) NOT NULL, `version` INT(2) NOT NULL, `date` INT(4) NOT NULL, `money` INT(12) NOT NULL, PRIMARY KEY (`uuid`) )"; + public static final String SQL_INSERT_BAG = "INSERT INTO `%s`(`uuid`, `version`, `size`, `contents`) VALUES (?, ?, ?)"; + public static final String SQL_INSERT_SELL = "INSERT INTO `%s`(`uuid`, `version`, `date`, `money`) VALUES (?, ?, ?)"; + public static final String SQL_UPDATE_BAG_BY_UUID = "UPDATE `%s` SET `version` = 0, `size` = ?, `contents` = ? WHERE `uuid` = ?"; + public static final String SQL_UPDATE_SELL_BY_UUID = "UPDATE `%s` SET `version` = 0, `date` = ?, `money` = ? WHERE `uuid` = ?"; public static final String SQL_SELECT_BAG_BY_UUID = "SELECT * FROM `%s` WHERE `uuid` = ?"; public static final String SQL_SELECT_SELL_BY_UUID = "SELECT * FROM `%s` WHERE `uuid` = ?"; + public static final String SQL_LOCK_BY_UUID = "UPDATE `%s` SET `version` = 1 WHERE `uuid` = ?"; + public static final String SQL_ALTER_TABLE = "ALTER TABLE `%s` ADD COLUMN `version` INT(2) NOT NULL AFTER `uuid`"; } diff --git a/src/main/java/net/momirealms/customfishing/object/fishing/BobberCheckTask.java b/src/main/java/net/momirealms/customfishing/fishing/BobberCheckTask.java similarity index 70% rename from src/main/java/net/momirealms/customfishing/object/fishing/BobberCheckTask.java rename to src/main/java/net/momirealms/customfishing/fishing/BobberCheckTask.java index 76cd4276..014e5b73 100644 --- a/src/main/java/net/momirealms/customfishing/object/fishing/BobberCheckTask.java +++ b/src/main/java/net/momirealms/customfishing/fishing/BobberCheckTask.java @@ -15,15 +15,14 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.fishing; +package net.momirealms.customfishing.fishing; import net.kyori.adventure.key.Key; import net.kyori.adventure.sound.Sound; import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.loot.Loot; import net.momirealms.customfishing.manager.ConfigManager; import net.momirealms.customfishing.manager.FishingManager; -import net.momirealms.customfishing.manager.LootManager; -import net.momirealms.customfishing.object.loot.Loot; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ArmorStandUtil; import net.momirealms.customfishing.util.FakeItemUtil; @@ -45,28 +44,30 @@ import java.util.Random; public class BobberCheckTask extends BukkitRunnable { private final FishHook fishHook; + private final CustomFishing plugin; private int timer; private final Player player; - private final Bonus bonus; + private final Effect effect; private final FishingManager fishingManager; private boolean hooked; private boolean reserve; private int jump_timer; private final int lureLevel; - private BukkitTask cache_1; - private BukkitTask cache_2; - private BukkitTask cache_3; - private ArmorStand entityCache; + private BukkitTask task_1; + private BukkitTask task_2; + private BukkitTask task_3; + private ArmorStand hookedEntity; private final int entityID; private boolean land; private boolean first; - public BobberCheckTask(Player player, Bonus bonus, FishHook fishHook, FishingManager fishingManager, int lureLevel, int entityID) { + public BobberCheckTask(CustomFishing plugin, Player player, Effect effect, FishHook fishHook, FishingManager fishingManager, int lureLevel, int entityID) { this.fishHook = fishHook; + this.plugin = plugin; this.fishingManager = fishingManager; this.player = player; this.timer = 0; - this.bonus = bonus; + this.effect = effect; this.reserve = true; this.jump_timer = 0; this.lureLevel = lureLevel; @@ -79,8 +80,8 @@ public class BobberCheckTask extends BukkitRunnable { public void run() { timer ++; if (!land && entityID != 0) { - CustomFishing.protocolManager.sendServerPacket(player, FakeItemUtil.getVelocity(entityID, fishHook.getVelocity())); - CustomFishing.protocolManager.sendServerPacket(player, FakeItemUtil.getTpPacket(entityID, fishHook.getLocation())); + CustomFishing.getProtocolManager().sendServerPacket(player, FakeItemUtil.getVelocity(entityID, fishHook.getVelocity())); + CustomFishing.getProtocolManager().sendServerPacket(player, FakeItemUtil.getTpPacket(entityID, fishHook.getLocation())); } if (timer > 3600) { stop(); @@ -96,7 +97,7 @@ public class BobberCheckTask extends BukkitRunnable { } if (fishHook.getLocation().getBlock().getType() == Material.LAVA) { land = true; - if (!bonus.canLavaFishing()) { + if (!effect.canLavaFishing()) { stop(); return; } @@ -128,12 +129,12 @@ public class BobberCheckTask extends BukkitRunnable { } if (fishHook.isInWater()) { stop(); - Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.plugin, () -> { + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { List possibleLoots = new ArrayList<>(); - if (!(ConfigManager.needRodForLoot && !bonus.hasSpecialRod())) { - possibleLoots = fishingManager.getPossibleLootList(new FishingCondition(fishHook.getLocation(), player), false, LootManager.WATERLOOTS.values()); + if (!(ConfigManager.needRodForLoot && !effect.hasSpecialRod())) { + possibleLoots = fishingManager.getPossibleLootList(new FishingCondition(fishHook.getLocation(), player), false, plugin.getLootManager().getWaterLoots().values()); } - fishingManager.getNextLoot(player, bonus, possibleLoots); + fishingManager.getNextLoot(player, effect, possibleLoots); if (ConfigManager.enableWaterAnimation) { ArmorStandUtil.sendAnimationToPlayer(fishHook.getLocation(), player, ConfigManager.water_item, ConfigManager.water_time); } @@ -149,63 +150,63 @@ public class BobberCheckTask extends BukkitRunnable { cancel(); cancelTask(); fishingManager.removePlayerFromLavaFishing(player); - if (entityCache != null && !entityCache.isDead()) { - entityCache.remove(); - entityCache = null; + if (hookedEntity != null && !hookedEntity.isDead()) { + hookedEntity.remove(); + hookedEntity = null; } sendRemovePacket(); } private void sendRemovePacket() { if (entityID == 0) return; - CustomFishing.protocolManager.sendServerPacket(player, FakeItemUtil.getDestroyPacket(entityID)); + CustomFishing.getProtocolManager().sendServerPacket(player, FakeItemUtil.getDestroyPacket(entityID)); } public void cancelTask() { - if (cache_1 != null) { - cache_1.cancel(); - cache_1 = null; + if (task_1 != null) { + task_1.cancel(); + task_1 = null; } - if (cache_2 != null) { - cache_2.cancel(); - cache_2 = null; + if (task_2 != null) { + task_2.cancel(); + task_2 = null; } - if (cache_3 != null) { - cache_3.cancel(); - cache_3 = null; + if (task_3 != null) { + task_3.cancel(); + task_3 = null; } } private void randomTime() { - Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.plugin, () -> { + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { List possibleLoots = new ArrayList<>(); - if (!(ConfigManager.needRodForLoot && !bonus.hasSpecialRod())) { - possibleLoots = fishingManager.getPossibleLootList(new FishingCondition(fishHook.getLocation(), player), false, LootManager.LAVALOOTS.values()); + if (!(ConfigManager.needRodForLoot && !effect.hasSpecialRod())) { + possibleLoots = fishingManager.getPossibleLootList(new FishingCondition(fishHook.getLocation(), player), false, plugin.getLootManager().getLavaLoots().values()); } - fishingManager.getNextLoot(player, bonus, possibleLoots); + fishingManager.getNextLoot(player, effect, possibleLoots); }); cancelTask(); int random = new Random().nextInt(ConfigManager.lavaMaxTime) + ConfigManager.lavaMinTime; random -= lureLevel * 100; - random *= bonus.getTime(); + random *= effect.getTimeModifier(); if (random < ConfigManager.lavaMinTime) random = ConfigManager.lavaMinTime; - cache_1 = Bukkit.getScheduler().runTaskLater(CustomFishing.plugin, () -> { + task_1 = Bukkit.getScheduler().runTaskLater(plugin, () -> { hooked = true; - if (entityCache != null && !entityCache.isDead()) entityCache.remove(); + if (hookedEntity != null && !hookedEntity.isDead()) hookedEntity.remove(); AdventureUtil.playerSound(player, Sound.Source.NEUTRAL, Key.key("minecraft:block.pointed_dripstone.drip_lava_into_cauldron"), 1, 1); if (ConfigManager.instantBar) fishingManager.showBar(player); }, random); - cache_2 = Bukkit.getScheduler().runTaskLater(CustomFishing.plugin, () -> { + task_2 = Bukkit.getScheduler().runTaskLater(plugin, () -> { hooked = false; reserve = true; }, random + 40); - cache_3 = new LavaEffect(fishHook.getLocation()).runTaskTimerAsynchronously(CustomFishing.plugin,random - 60,1); + task_3 = new LavaEffect(fishHook.getLocation()).runTaskTimerAsynchronously(plugin,random - 60,1); } private void spawnArmorStand(Location armorLoc) { armorLoc.setY(armorLoc.getBlockY() + 0.2); - if (entityCache != null && !entityCache.isDead()) entityCache.remove(); - entityCache = armorLoc.getWorld().spawn(armorLoc, ArmorStand.class, a -> { + if (hookedEntity != null && !hookedEntity.isDead()) hookedEntity.remove(); + hookedEntity = armorLoc.getWorld().spawn(armorLoc, ArmorStand.class, a -> { a.setInvisible(true); a.setCollidable(false); a.setInvulnerable(true); @@ -214,7 +215,7 @@ public class BobberCheckTask extends BukkitRunnable { a.setSmall(true); a.setGravity(false); }); - fishHook.setHookedEntity(entityCache); + fishHook.setHookedEntity(hookedEntity); } public boolean isHooked() { diff --git a/src/main/java/net/momirealms/customfishing/object/fishing/Bonus.java b/src/main/java/net/momirealms/customfishing/fishing/Effect.java similarity index 56% rename from src/main/java/net/momirealms/customfishing/object/fishing/Bonus.java rename to src/main/java/net/momirealms/customfishing/fishing/Effect.java index 8b790a46..efbdd3c3 100644 --- a/src/main/java/net/momirealms/customfishing/object/fishing/Bonus.java +++ b/src/main/java/net/momirealms/customfishing/fishing/Effect.java @@ -15,23 +15,34 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.fishing; +package net.momirealms.customfishing.fishing; + +import net.momirealms.customfishing.manager.ConfigManager; import java.util.HashMap; import java.util.Map; import java.util.Optional; -public class Bonus { +public class Effect { private HashMap weightMD; private HashMap weightAS; - private double time; - private double score; + private double timeModifier; + private double sizeMultiplier; + private double scoreMultiplier; private int difficulty; - private double doubleLoot; + private double doubleLootChance; private boolean canLavaFishing; private boolean hasSpecialRod; + public double getSizeMultiplier() { + return sizeMultiplier + 1; + } + + public void setSizeMultiplier(double sizeMultiplier) { + this.sizeMultiplier = sizeMultiplier; + } + public HashMap getWeightMD() { return weightMD; } @@ -48,20 +59,16 @@ public class Bonus { this.weightAS = weightAS; } - public double getTime() { - return time; + public double getTimeModifier() { + return timeModifier; } - public void setTime(double time) { - this.time = time; + public void setTimeModifier(double timeModifier) { + this.timeModifier = timeModifier; } - private double getScore() { - return score; - } - - public void setScore(double score) { - this.score = score; + public void setScoreMultiplier(double scoreMultiplier) { + this.scoreMultiplier = scoreMultiplier; } public int getDifficulty() { @@ -72,46 +79,47 @@ public class Bonus { this.difficulty = difficulty; } - public double getDoubleLoot() { - return doubleLoot; + public double getDoubleLootChance() { + return doubleLootChance; } - public void setDoubleLoot(double doubleLoot) { - this.doubleLoot = doubleLoot; + public void setDoubleLootChance(double doubleLootChance) { + this.doubleLootChance = doubleLootChance; } public boolean canLavaFishing() { - return canLavaFishing; + return canLavaFishing || ConfigManager.allRodsFishInLava; } public void setCanLavaFishing(boolean canLavaFishing) { this.canLavaFishing = canLavaFishing; } - public void addBonus(Bonus anotherBonus) { - HashMap weightAS = anotherBonus.getWeightAS(); + public void addEffect(Effect anotherEffect) { + HashMap weightAS = anotherEffect.getWeightAS(); if (weightAS != null) { for (Map.Entry en : weightAS.entrySet()) { String group = en.getKey(); this.weightAS.put(group, Optional.ofNullable(this.weightAS.get(group)).orElse(0) + en.getValue()); } } - HashMap weightMD = anotherBonus.getWeightMD(); + HashMap weightMD = anotherEffect.getWeightMD(); if (weightMD != null){ for (Map.Entry en : weightMD.entrySet()) { String group = en.getKey(); this.weightMD.put(group, Optional.ofNullable(this.weightMD.get(group)).orElse(1d) + en.getValue()); } } - if (anotherBonus.getTime() != 0) this.time += (anotherBonus.getTime() - 1); - if (anotherBonus.getDoubleLoot() != 0) this.doubleLoot += anotherBonus.getDoubleLoot(); - if (anotherBonus.getDifficulty() != 0) this.difficulty += anotherBonus.getDifficulty(); - if (anotherBonus.getScore() != 0) this.score += anotherBonus.getScore(); - if (anotherBonus.canLavaFishing()) this.canLavaFishing = true; + if (anotherEffect.getTimeModifier() != 0) this.timeModifier += (anotherEffect.getTimeModifier() - 1); + if (anotherEffect.getDoubleLootChance() != 0) this.doubleLootChance += anotherEffect.getDoubleLootChance(); + if (anotherEffect.getDifficulty() != 0) this.difficulty += anotherEffect.getDifficulty(); + if (anotherEffect.getScoreMultiplier() != 0) this.scoreMultiplier += anotherEffect.getScoreMultiplier(); + if (anotherEffect.getSizeMultiplier() != 0) this.sizeMultiplier += anotherEffect.getSizeMultiplier(); + if (anotherEffect.canLavaFishing()) this.canLavaFishing = true; } - public double getScoreBonus() { - return score + 1; + public double getScoreMultiplier() { + return scoreMultiplier + 1; } public boolean hasSpecialRod() { diff --git a/src/main/java/net/momirealms/customfishing/object/fishing/FishResult.java b/src/main/java/net/momirealms/customfishing/fishing/FishResult.java similarity index 87% rename from src/main/java/net/momirealms/customfishing/object/fishing/FishResult.java rename to src/main/java/net/momirealms/customfishing/fishing/FishResult.java index ccaf439f..c2d55265 100644 --- a/src/main/java/net/momirealms/customfishing/object/fishing/FishResult.java +++ b/src/main/java/net/momirealms/customfishing/fishing/FishResult.java @@ -15,12 +15,12 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.fishing; +package net.momirealms.customfishing.fishing; public enum FishResult { FAILURE, - CAUGHT_MOB, - CAUGHT_LOOT, - CAUGHT_VANILLA + CATCH_MOB, + CATCH_SPECIAL_ITEM, + CATCH_VANILLA_ITEM } diff --git a/src/main/java/net/momirealms/customfishing/object/fishing/FishingCondition.java b/src/main/java/net/momirealms/customfishing/fishing/FishingCondition.java similarity index 88% rename from src/main/java/net/momirealms/customfishing/object/fishing/FishingCondition.java rename to src/main/java/net/momirealms/customfishing/fishing/FishingCondition.java index 163464ce..9cfa26e5 100644 --- a/src/main/java/net/momirealms/customfishing/object/fishing/FishingCondition.java +++ b/src/main/java/net/momirealms/customfishing/fishing/FishingCondition.java @@ -15,11 +15,11 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.fishing; +package net.momirealms.customfishing.fishing; import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.requirements.CustomPapi; import net.momirealms.customfishing.integration.papi.PlaceholderManager; -import net.momirealms.customfishing.object.requirements.CustomPapi; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -34,7 +34,7 @@ public class FishingCondition{ public FishingCondition(Location location, Player player) { this.location = location; this.player = player; - PlaceholderManager placeholderManager = CustomFishing.plugin.getIntegrationManager().getPlaceholderManager(); + PlaceholderManager placeholderManager = CustomFishing.getInstance().getIntegrationManager().getPlaceholderManager(); this.papiMap = new HashMap<>(); for (String papi : CustomPapi.allPapi) { this.papiMap.put(papi, placeholderManager.parse(player, papi)); diff --git a/src/main/java/net/momirealms/customfishing/object/fishing/LavaEffect.java b/src/main/java/net/momirealms/customfishing/fishing/LavaEffect.java similarity index 97% rename from src/main/java/net/momirealms/customfishing/object/fishing/LavaEffect.java rename to src/main/java/net/momirealms/customfishing/fishing/LavaEffect.java index b235caec..a6f4de3b 100644 --- a/src/main/java/net/momirealms/customfishing/object/fishing/LavaEffect.java +++ b/src/main/java/net/momirealms/customfishing/fishing/LavaEffect.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.fishing; +package net.momirealms.customfishing.fishing; import org.bukkit.Location; import org.bukkit.Particle; diff --git a/src/main/java/net/momirealms/customfishing/fishing/MiniGameConfig.java b/src/main/java/net/momirealms/customfishing/fishing/MiniGameConfig.java new file mode 100644 index 00000000..ac5d98c7 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/fishing/MiniGameConfig.java @@ -0,0 +1,30 @@ +package net.momirealms.customfishing.fishing; + +import net.momirealms.customfishing.fishing.bar.FishingBar; + +import java.util.Random; + +public class MiniGameConfig { + + private final int time; + private final FishingBar[] bars; + private final int[] difficulties; + + public MiniGameConfig(int time, FishingBar[] bars, int[] difficulties) { + this.time = time; + this.bars = bars; + this.difficulties = difficulties; + } + + public FishingBar getRandomBar() { + return bars[new Random().nextInt(bars.length)]; + } + + public int getRandomDifficulty() { + return difficulties[new Random().nextInt(difficulties.length)]; + } + + public int getTime() { + return this.time; + } +} diff --git a/src/main/java/net/momirealms/customfishing/object/fishing/VanillaLoot.java b/src/main/java/net/momirealms/customfishing/fishing/VanillaLoot.java similarity index 95% rename from src/main/java/net/momirealms/customfishing/object/fishing/VanillaLoot.java rename to src/main/java/net/momirealms/customfishing/fishing/VanillaLoot.java index 9af20c53..89ead047 100644 --- a/src/main/java/net/momirealms/customfishing/object/fishing/VanillaLoot.java +++ b/src/main/java/net/momirealms/customfishing/fishing/VanillaLoot.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.fishing; +package net.momirealms.customfishing.fishing; import org.bukkit.inventory.ItemStack; diff --git a/src/main/java/net/momirealms/customfishing/fishing/bar/FishingBar.java b/src/main/java/net/momirealms/customfishing/fishing/bar/FishingBar.java new file mode 100644 index 00000000..bdc038e0 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/fishing/bar/FishingBar.java @@ -0,0 +1,30 @@ +package net.momirealms.customfishing.fishing.bar; + +import org.bukkit.configuration.ConfigurationSection; + +import java.util.Random; + +public abstract class FishingBar { + + protected String[] titles; + protected String font; + protected String barImage; + + public FishingBar(ConfigurationSection section) { + this.titles = section.getStringList("title").size() == 0 ? new String[]{section.getString("title")} : section.getStringList("title").toArray(new String[0]); + this.font = section.getString("subtitle.font", "customfishing:bar"); + this.barImage = section.getString("subtitle.bar","뀃"); + } + + public String getRandomTitle() { + return titles[new Random().nextInt(titles.length)]; + } + + public String getBarImage() { + return barImage; + } + + public String getFont() { + return font; + } +} diff --git a/src/main/java/net/momirealms/customfishing/fishing/bar/ModeOneBar.java b/src/main/java/net/momirealms/customfishing/fishing/bar/ModeOneBar.java new file mode 100644 index 00000000..965cf207 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/fishing/bar/ModeOneBar.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) <2022> + * + * 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 + * 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 net.momirealms.customfishing.fishing.bar; + +import org.bukkit.configuration.ConfigurationSection; + +import java.util.Objects; +import java.util.Set; + +public class ModeOneBar extends FishingBar { + + private final int widthPerSection; + private final double[] successRate; + private final int totalWidth; + private final int pointerWidth; + + private final String pointerImage; + private final int pointerOffset; + + public ModeOneBar(ConfigurationSection section) { + super(section); + Set chances = Objects.requireNonNull(section.getConfigurationSection("success-rate-sections")).getKeys(false); + this.widthPerSection = section.getInt("arguments.width-per-section", 16); + this.successRate = new double[chances.size()]; + for(int i = 0; i < chances.size(); i++) + successRate[i] = section.getDouble("success-rate-sections." + (i + 1)); + this.totalWidth = chances.size() * widthPerSection - 1; + this.pointerImage = section.getString("subtitle.pointer","뀄"); + this.pointerOffset = section.getInt("arguments.pointer-offset"); + this.pointerWidth = section.getInt("arguments.pointer-width"); + } + + public int getWidthPerSection() { + return widthPerSection; + } + + public double[] getSuccessRate() { + return successRate; + } + + public int getTotalWidth() { + return totalWidth; + } + + + + public String getPointerImage() { + return pointerImage; + } + + public int getPointerWidth() { + return pointerWidth; + } + + public int getPointerOffset() { + return pointerOffset; + } +} diff --git a/src/main/java/net/momirealms/customfishing/fishing/bar/ModeTwoBar.java b/src/main/java/net/momirealms/customfishing/fishing/bar/ModeTwoBar.java new file mode 100644 index 00000000..38b67b3f --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/fishing/bar/ModeTwoBar.java @@ -0,0 +1,67 @@ +package net.momirealms.customfishing.fishing.bar; + +import org.bukkit.configuration.ConfigurationSection; + +import java.util.Random; + +public class ModeTwoBar extends FishingBar { + + private final int[] time_requirements; + private final String judgement_area_image; + private final String fish_image; + private final int bar_effective_width; + private final int judgement_area_offset; + private final int judgement_area_width; + private final int fish_icon_width; + private final String[] progress; + private double punishment; + + public ModeTwoBar(ConfigurationSection section) { + super(section); + this.time_requirements = section.getIntegerList("hold-time-requirements").stream().mapToInt(Integer::intValue).toArray(); + this.judgement_area_image = section.getString("subtitle.judgment-area"); + this.fish_image = section.getString("subtitle.fish"); + this.bar_effective_width = section.getInt("arguments.bar-effective-area-width"); + this.judgement_area_offset = section.getInt("arguments.judgment-area-offset"); + this.judgement_area_width = section.getInt("arguments.judgment-area-width"); + this.fish_icon_width = section.getInt("arguments.fish-icon-width"); + this.punishment = section.getDouble("arguments.punishment"); + this.progress = section.getStringList("progress").toArray(new String[0]); + } + + public int getRandomTimeRequirement() { + return time_requirements[new Random().nextInt(time_requirements.length)] * 20; + } + + public String getJudgement_area_image() { + return judgement_area_image; + } + + public String getFish_image() { + return fish_image; + } + + public int getBar_effective_width() { + return bar_effective_width; + } + + public int getJudgement_area_offset() { + return judgement_area_offset; + } + + public int getJudgement_area_width() { + return judgement_area_width; + } + + public int getFish_icon_width() { + return fish_icon_width; + } + + public String[] getProgress() { + return progress; + } + + public double getPunishment() { + return punishment; + } +} diff --git a/src/main/java/net/momirealms/customfishing/competition/Competition.java b/src/main/java/net/momirealms/customfishing/fishing/competition/Competition.java similarity index 88% rename from src/main/java/net/momirealms/customfishing/competition/Competition.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/Competition.java index c593972f..0e06ae10 100644 --- a/src/main/java/net/momirealms/customfishing/competition/Competition.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/Competition.java @@ -15,13 +15,13 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition; +package net.momirealms.customfishing.fishing.competition; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.competition.bossbar.BossBarManager; -import net.momirealms.customfishing.competition.ranking.LocalRankingImpl; -import net.momirealms.customfishing.competition.ranking.RankingInterface; -import net.momirealms.customfishing.competition.ranking.RedisRankingImpl; +import net.momirealms.customfishing.fishing.competition.bossbar.BossBarManager; +import net.momirealms.customfishing.fishing.competition.ranking.LocalRankingImpl; +import net.momirealms.customfishing.fishing.competition.ranking.RankingInterface; +import net.momirealms.customfishing.fishing.competition.ranking.RedisRankingImpl; import net.momirealms.customfishing.integration.papi.PlaceholderManager; import net.momirealms.customfishing.manager.ConfigManager; import net.momirealms.customfishing.manager.MessageManager; @@ -54,32 +54,26 @@ public class Competition { public void begin(boolean forceStart) { this.goal = competitionConfig.getGoal(); - if (this.goal == CompetitionGoal.RANDOM) { - this.goal = getRandomGoal(); - } + if (this.goal == CompetitionGoal.RANDOM) this.goal = getRandomGoal(); this.remainingTime = this.competitionConfig.getDuration(); this.startTime = Instant.now().getEpochSecond(); Collection playerCollections = Bukkit.getOnlinePlayers(); if (playerCollections.size() >= competitionConfig.getMinPlayers() || forceStart) { - if (ConfigManager.useRedis){ - ranking = new RedisRankingImpl(); - } else { - ranking = new LocalRankingImpl(); - } + if (ConfigManager.useRedis) this.ranking = new RedisRankingImpl(); + else this.ranking = new LocalRankingImpl(); + startTimer(); - for (String startMsg : competitionConfig.getStartMessage()) { - for (Player player : playerCollections) { + for (String startMsg : competitionConfig.getStartMessage()) + for (Player player : playerCollections) AdventureUtil.playerMessage(player, startMsg); - } - } - for (String startCmd : competitionConfig.getStartCommand()) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), startCmd); - } - if (competitionConfig.isEnableBossBar()) { - bossBarManager = new BossBarManager(); - bossBarManager.load(); + + for (String startCmd : competitionConfig.getStartCommand()) Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), startCmd); + + if (competitionConfig.isBossBarEnabled()) { + this.bossBarManager = new BossBarManager(); + this.bossBarManager.load(); } } else { @@ -98,14 +92,14 @@ public class Competition { end(); } } - }.runTaskTimer(CustomFishing.plugin, 0, 20); + }.runTaskTimer(CustomFishing.getInstance(), 0, 20); } public void cancel() { if (this.bossBarManager != null) { bossBarManager.unload(); } - ranking.clear(); + this.ranking.clear(); this.timerTask.cancel(); currentCompetition = null; } @@ -118,8 +112,7 @@ public class Competition { givePrize(); List newMessage = new ArrayList<>(); - PlaceholderManager placeholderManager = CustomFishing.plugin.getIntegrationManager().getPlaceholderManager(); - + PlaceholderManager placeholderManager = CustomFishing.getInstance().getIntegrationManager().getPlaceholderManager(); for (String endMsg : competitionConfig.getEndMessage()) { List placeholders = new ArrayList<>(placeholderManager.detectPlaceholders(endMsg)); for (String placeholder : placeholders) { @@ -148,7 +141,7 @@ public class Competition { currentCompetition = null; - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.plugin, ()-> { + Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.getInstance(), ()-> { ranking.clear(); }, 600); } @@ -190,13 +183,10 @@ public class Competition { } private boolean decreaseTime() { - long tVac; long current = Instant.now().getEpochSecond(); int duration = competitionConfig.getDuration(); - progress = (float) remainingTime / duration; - remainingTime = duration - (current - startTime); if ((tVac = (current - startTime) + 1) != duration - remainingTime) { for (long i = duration - remainingTime; i < tVac; i++) { diff --git a/src/main/java/net/momirealms/customfishing/competition/CompetitionConfig.java b/src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionConfig.java similarity index 95% rename from src/main/java/net/momirealms/customfishing/competition/CompetitionConfig.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionConfig.java index 94061cdb..2cabb962 100644 --- a/src/main/java/net/momirealms/customfishing/competition/CompetitionConfig.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionConfig.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition; +package net.momirealms.customfishing.fishing.competition; -import net.momirealms.customfishing.competition.bossbar.BossBarConfig; +import net.momirealms.customfishing.fishing.competition.bossbar.BossBarConfig; import net.momirealms.customfishing.object.action.ActionInterface; import java.util.Calendar; @@ -90,7 +90,7 @@ public class CompetitionConfig { return bossBarConfig; } - public boolean isEnableBossBar() { + public boolean isBossBarEnabled() { return enableBossBar; } diff --git a/src/main/java/net/momirealms/customfishing/competition/CompetitionGoal.java b/src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionGoal.java similarity index 93% rename from src/main/java/net/momirealms/customfishing/competition/CompetitionGoal.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionGoal.java index 25ba1199..1aab76e6 100644 --- a/src/main/java/net/momirealms/customfishing/competition/CompetitionGoal.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionGoal.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition; +package net.momirealms.customfishing.fishing.competition; public enum CompetitionGoal { diff --git a/src/main/java/net/momirealms/customfishing/competition/CompetitionPlayer.java b/src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionPlayer.java similarity index 97% rename from src/main/java/net/momirealms/customfishing/competition/CompetitionPlayer.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionPlayer.java index 7b3fe43a..0c07d99d 100644 --- a/src/main/java/net/momirealms/customfishing/competition/CompetitionPlayer.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionPlayer.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition; +package net.momirealms.customfishing.fishing.competition; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/net/momirealms/customfishing/competition/CompetitionSchedule.java b/src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionSchedule.java similarity index 87% rename from src/main/java/net/momirealms/customfishing/competition/CompetitionSchedule.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionSchedule.java index f1d6e94b..d26ce486 100644 --- a/src/main/java/net/momirealms/customfishing/competition/CompetitionSchedule.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/CompetitionSchedule.java @@ -15,10 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition; +package net.momirealms.customfishing.fishing.competition; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.manager.CompetitionManager; import net.momirealms.customfishing.object.Function; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; @@ -42,7 +41,7 @@ public class CompetitionSchedule extends Function { private int doubleCheckTime; public static boolean startCompetition(String competitionName) { - CompetitionConfig competitionConfig = CompetitionManager.competitionsC.get(competitionName); + CompetitionConfig competitionConfig = CustomFishing.getInstance().getCompetitionManager().getCompetitionsC().get(competitionName); if (competitionConfig == null) return false; if (Competition.currentCompetition != null) { Competition.currentCompetition.end(); @@ -76,13 +75,13 @@ public class CompetitionSchedule extends Function { this.checkTimeTask = new BukkitRunnable() { public void run() { if (isANewMinute()) { - CompetitionConfig competitionConfig = CompetitionManager.competitionsT.get(getCurrentTime()); + CompetitionConfig competitionConfig = CustomFishing.getInstance().getCompetitionManager().getCompetitionsT().get(getCurrentTime()); if (competitionConfig != null && competitionConfig.canStart()) { startCompetition(competitionConfig); } } } - }.runTaskTimer(CustomFishing.plugin, 60 - LocalTime.now().getSecond(), 100); + }.runTaskTimer(CustomFishing.getInstance(), 60 - LocalTime.now().getSecond(), 100); } public void stopCheck() { diff --git a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarConfig.java b/src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarConfig.java similarity index 95% rename from src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarConfig.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarConfig.java index 44f674be..ed513a83 100644 --- a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarConfig.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarConfig.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition.bossbar; +package net.momirealms.customfishing.fishing.competition.bossbar; import org.bukkit.boss.BarColor; diff --git a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarManager.java b/src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarManager.java similarity index 85% rename from src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarManager.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarManager.java index c53cac17..8808b54b 100644 --- a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarManager.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarManager.java @@ -15,11 +15,11 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition.bossbar; +package net.momirealms.customfishing.fishing.competition.bossbar; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.competition.Competition; -import net.momirealms.customfishing.listener.SimpleListener; +import net.momirealms.customfishing.fishing.competition.Competition; +import net.momirealms.customfishing.listener.JoinQuitListener; import net.momirealms.customfishing.manager.MessageManager; import net.momirealms.customfishing.object.Function; import net.momirealms.customfishing.util.AdventureUtil; @@ -32,20 +32,20 @@ import java.util.HashMap; public class BossBarManager extends Function { public static HashMap cache = new HashMap<>(); - private final SimpleListener simpleListener; + private final JoinQuitListener joinQuitListener; public BossBarManager() { - this.simpleListener = new SimpleListener(this); + this.joinQuitListener = new JoinQuitListener(this); } @Override public void load() { - Bukkit.getPluginManager().registerEvents(this.simpleListener, CustomFishing.plugin); + Bukkit.getPluginManager().registerEvents(this.joinQuitListener, CustomFishing.getInstance()); } @Override public void unload() { - if (this.simpleListener != null) HandlerList.unregisterAll(this.simpleListener); + if (this.joinQuitListener != null) HandlerList.unregisterAll(this.joinQuitListener); for (BossBarSender bossBarSender : cache.values()) { bossBarSender.hide(); } diff --git a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarOverlay.java b/src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarOverlay.java similarity index 92% rename from src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarOverlay.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarOverlay.java index 70d862a0..941d83c8 100644 --- a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarOverlay.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarOverlay.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition.bossbar; +package net.momirealms.customfishing.fishing.competition.bossbar; public enum BossBarOverlay { NOTCHED_6, diff --git a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarSender.java b/src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarSender.java similarity index 89% rename from src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarSender.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarSender.java index 81311118..247238a4 100644 --- a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarSender.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/bossbar/BossBarSender.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition.bossbar; +package net.momirealms.customfishing.fishing.competition.bossbar; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.InternalStructure; @@ -25,8 +25,8 @@ import com.comphenix.protocol.wrappers.WrappedChatComponent; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.competition.Competition; -import net.momirealms.customfishing.object.TextCache; +import net.momirealms.customfishing.fishing.competition.Competition; +import net.momirealms.customfishing.object.DynamicText; import net.momirealms.customfishing.util.AdventureUtil; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; @@ -46,8 +46,8 @@ public class BossBarSender { private int timer_2; private int counter; private final int size; - private final TextCache[] texts; - private TextCache text; + private final DynamicText[] texts; + private DynamicText text; private BukkitTask bukkitTask; private final UUID uuid; private boolean force; @@ -62,9 +62,9 @@ public class BossBarSender { public BossBarSender(Player player, BossBarConfig config){ String[] str = config.getText(); this.size = str.length; - texts = new TextCache[str.length]; + texts = new DynamicText[str.length]; for (int i = 0; i < str.length; i++) { - texts[i] = new TextCache(player, str[i]); + texts[i] = new DynamicText(player, str[i]); } text = texts[0]; this.player = player; @@ -76,7 +76,7 @@ public class BossBarSender { public void show() { this.isShown = true; - CustomFishing.protocolManager.sendServerPacket(player, getPacket()); + CustomFishing.getProtocolManager().sendServerPacket(player, getPacket()); this.bukkitTask = new BukkitRunnable() { @Override @@ -99,12 +99,12 @@ public class BossBarSender { timer_1 = 0; if (text.update() || force) { force = false; - CustomFishing.protocolManager.sendServerPacket(player, getUpdatePacket()); - CustomFishing.protocolManager.sendServerPacket(player, getProgressPacket()); + CustomFishing.getProtocolManager().sendServerPacket(player, getUpdatePacket()); + CustomFishing.getProtocolManager().sendServerPacket(player, getProgressPacket()); } } } - }.runTaskTimerAsynchronously(CustomFishing.plugin,0,1); + }.runTaskTimerAsynchronously(CustomFishing.getInstance(),0,1); } private PacketContainer getUpdatePacket() { @@ -171,7 +171,7 @@ public class BossBarSender { Field remove = bar.getDeclaredField("f"); remove.setAccessible(true); packet.getModifier().write(1, remove.get(null)); - CustomFishing.protocolManager.sendServerPacket(player, packet); + CustomFishing.getProtocolManager().sendServerPacket(player, packet); } catch (ClassNotFoundException e){ AdventureUtil.consoleMessage("[CustomFishing] Failed to remove bossbar for " + player.getName()); } catch (NoSuchFieldException | IllegalAccessException e) { diff --git a/src/main/java/net/momirealms/customfishing/competition/ranking/LocalRankingImpl.java b/src/main/java/net/momirealms/customfishing/fishing/competition/ranking/LocalRankingImpl.java similarity index 96% rename from src/main/java/net/momirealms/customfishing/competition/ranking/LocalRankingImpl.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/ranking/LocalRankingImpl.java index 9d22cb34..c48ca828 100644 --- a/src/main/java/net/momirealms/customfishing/competition/ranking/LocalRankingImpl.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/ranking/LocalRankingImpl.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition.ranking; +package net.momirealms.customfishing.fishing.competition.ranking; -import net.momirealms.customfishing.competition.CompetitionPlayer; +import net.momirealms.customfishing.fishing.competition.CompetitionPlayer; import java.util.*; diff --git a/src/main/java/net/momirealms/customfishing/competition/ranking/RankingInterface.java b/src/main/java/net/momirealms/customfishing/fishing/competition/ranking/RankingInterface.java similarity index 89% rename from src/main/java/net/momirealms/customfishing/competition/ranking/RankingInterface.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/ranking/RankingInterface.java index 6b15cfcb..38a215f8 100644 --- a/src/main/java/net/momirealms/customfishing/competition/ranking/RankingInterface.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/ranking/RankingInterface.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition.ranking; +package net.momirealms.customfishing.fishing.competition.ranking; -import net.momirealms.customfishing.competition.CompetitionPlayer; +import net.momirealms.customfishing.fishing.competition.CompetitionPlayer; import org.jetbrains.annotations.Nullable; import java.util.Iterator; diff --git a/src/main/java/net/momirealms/customfishing/competition/ranking/RedisRankingImpl.java b/src/main/java/net/momirealms/customfishing/fishing/competition/ranking/RedisRankingImpl.java similarity index 96% rename from src/main/java/net/momirealms/customfishing/competition/ranking/RedisRankingImpl.java rename to src/main/java/net/momirealms/customfishing/fishing/competition/ranking/RedisRankingImpl.java index b989fdeb..968d6839 100644 --- a/src/main/java/net/momirealms/customfishing/competition/ranking/RedisRankingImpl.java +++ b/src/main/java/net/momirealms/customfishing/fishing/competition/ranking/RedisRankingImpl.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition.ranking; +package net.momirealms.customfishing.fishing.competition.ranking; -import net.momirealms.customfishing.competition.CompetitionPlayer; +import net.momirealms.customfishing.fishing.competition.CompetitionPlayer; import net.momirealms.customfishing.util.JedisUtil; import redis.clients.jedis.Jedis; import redis.clients.jedis.resps.Tuple; diff --git a/src/main/java/net/momirealms/customfishing/object/loot/DroppedItem.java b/src/main/java/net/momirealms/customfishing/fishing/loot/DroppedItem.java similarity index 78% rename from src/main/java/net/momirealms/customfishing/object/loot/DroppedItem.java rename to src/main/java/net/momirealms/customfishing/fishing/loot/DroppedItem.java index 17353971..33af0ee7 100644 --- a/src/main/java/net/momirealms/customfishing/object/loot/DroppedItem.java +++ b/src/main/java/net/momirealms/customfishing/fishing/loot/DroppedItem.java @@ -15,33 +15,31 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.loot; +package net.momirealms.customfishing.fishing.loot; -import net.momirealms.customfishing.object.fishing.Difficulty; +import net.momirealms.customfishing.fishing.MiniGameConfig; +import net.momirealms.customfishing.object.LeveledEnchantment; import org.jetbrains.annotations.Nullable; -public class DroppedItem extends Loot{ +public class DroppedItem extends Loot { - private boolean randomDurability; + private final boolean randomDurability; private LeveledEnchantment[] randomEnchants; private final String material; private String[] size; private float basicPrice; private float sizeBonus; - public DroppedItem(String key, Difficulty[] difficulty, int time, int weight, String material) { - super(key, difficulty, time, weight); + public DroppedItem(String key, String nick, String material, MiniGameConfig[] fishingGames, int weight, boolean showInFinder, double score, boolean randomDurability) { + super(key, nick, fishingGames, weight, showInFinder, score); this.material = material; + this.randomDurability = randomDurability; } public boolean isRandomDurability() { return randomDurability; } - public void setRandomDurability(boolean randomDurability) { - this.randomDurability = randomDurability; - } - @Nullable public LeveledEnchantment[] getRandomEnchants() { return randomEnchants; diff --git a/src/main/java/net/momirealms/customfishing/object/loot/Item.java b/src/main/java/net/momirealms/customfishing/fishing/loot/Item.java similarity index 60% rename from src/main/java/net/momirealms/customfishing/object/loot/Item.java rename to src/main/java/net/momirealms/customfishing/fishing/loot/Item.java index 58b62c27..1de02140 100644 --- a/src/main/java/net/momirealms/customfishing/object/loot/Item.java +++ b/src/main/java/net/momirealms/customfishing/fishing/loot/Item.java @@ -15,18 +15,23 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.loot; +package net.momirealms.customfishing.fishing.loot; +import net.momirealms.customfishing.object.LeveledEnchantment; import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemFlag; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Objects; public class Item { private final String key; + private int amount; private final Material material; private String name; private List lore; @@ -42,6 +47,40 @@ public class Item { this.key = key; } + public Item(ConfigurationSection section, String key) { + this.key = key; + this.material = Material.valueOf(section.getString("material", "cod").toUpperCase()); + this.amount = section.getInt("amount", 1); + this.setUnbreakable(section.getBoolean("unbreakable", false)); + if (section.contains("display.lore")) this.setLore(section.getStringList("display.lore")); + if (section.contains("display.name")) this.setName(section.getString("display.name")); + if (section.contains("custom-model-data")) this.setCustomModelData(section.getInt("custom-model-data")); + if (section.contains("enchantments")) { + List enchantmentList = new ArrayList<>(); + Objects.requireNonNull(section.getConfigurationSection("enchantments")).getKeys(false).forEach(enchant -> { + LeveledEnchantment leveledEnchantment = new LeveledEnchantment( + NamespacedKey.fromString(enchant), + section.getInt("enchantments." + enchant) + ); + enchantmentList.add(leveledEnchantment); + }); + this.setEnchantment(enchantmentList); + } + if (section.contains("item_flags")) { + ArrayList itemFlags = new ArrayList<>(); + section.getStringList("item_flags").forEach(flag -> itemFlags.add(ItemFlag.valueOf(flag))); + this.setItemFlags(itemFlags); + } + if (section.contains("nbt")) { + ConfigurationSection nbtSection = section.getConfigurationSection(".nbt"); + if (nbtSection == null) return; + this.setNbt(nbtSection.getValues(false)); + } + if (section.contains("head64")) { + this.setHead64(section.getString("head64")); + } + } + public Material getMaterial() { return material; } @@ -114,6 +153,10 @@ public class Item { return key; } + public int getAmount() { + return amount; + } + public Item cloneWithPrice(double price){ Item newItem = new Item(this.material, this.key); if (this.lore != null){ diff --git a/src/main/java/net/momirealms/customfishing/object/loot/Loot.java b/src/main/java/net/momirealms/customfishing/fishing/loot/Loot.java similarity index 65% rename from src/main/java/net/momirealms/customfishing/object/loot/Loot.java rename to src/main/java/net/momirealms/customfishing/fishing/loot/Loot.java index cb7dff6e..6802802b 100644 --- a/src/main/java/net/momirealms/customfishing/object/loot/Loot.java +++ b/src/main/java/net/momirealms/customfishing/fishing/loot/Loot.java @@ -15,57 +15,50 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.loot; +package net.momirealms.customfishing.fishing.loot; +import net.momirealms.customfishing.fishing.MiniGameConfig; +import net.momirealms.customfishing.fishing.requirements.RequirementInterface; import net.momirealms.customfishing.object.action.ActionInterface; -import net.momirealms.customfishing.object.fishing.Difficulty; -import net.momirealms.customfishing.object.fishing.Layout; -import net.momirealms.customfishing.object.requirements.RequirementInterface; public class Loot { - public static Loot EMPTY = new Loot("empty", new Difficulty[]{new Difficulty(1, 1)}, 5000, 10); + public static Loot EMPTY = new Loot("null", "null", new MiniGameConfig[0], 0, false, 0d); - protected String key; - protected String nick; - protected Difficulty[] difficulty; + protected final String key; + protected final String nick; protected String group; - protected boolean showInFinder; - protected Layout[] layout; + protected final boolean showInFinder; protected ActionInterface[] successActions; protected ActionInterface[] failureActions; protected ActionInterface[] hookActions; - protected int weight; - protected int time; + protected ActionInterface[] consumeActions; protected RequirementInterface[] requirements; - protected double score; + protected final MiniGameConfig[] fishingGames; + protected final int weight; + protected final double score; - public Loot(String key, Difficulty[] difficulty, int time, int weight) { + public Loot(String key, String nick, MiniGameConfig[] fishingGames, int weight, boolean showInFinder, double score) { this.key = key; - this.difficulty = difficulty; - this.time = time; + this.nick = nick; this.weight = weight; + this.showInFinder = showInFinder; + this.score = score; + this.fishingGames = fishingGames; + } + + public MiniGameConfig[] getFishingGames() { + return fishingGames; } public String getKey() { return key; } + public String getNick() { return nick; } - public void setNick(String nick) { - this.nick = nick; - } - - public Difficulty[] getDifficulty() { - return difficulty; - } - - public void setDifficulty(Difficulty[] difficulty) { - this.difficulty = difficulty; - } - public String getGroup() { return group; } @@ -78,18 +71,6 @@ public class Loot { return showInFinder; } - public void setShowInFinder(boolean showInFinder) { - this.showInFinder = showInFinder; - } - - public Layout[] getLayout() { - return layout; - } - - public void setLayout(Layout[] layout) { - this.layout = layout; - } - public ActionInterface[] getSuccessActions() { return successActions; } @@ -102,6 +83,14 @@ public class Loot { return failureActions; } + public ActionInterface[] getConsumeActions() { + return consumeActions; + } + + public void setConsumeActions(ActionInterface[] consumeActions) { + this.consumeActions = consumeActions; + } + public void setFailureActions(ActionInterface[] failureActions) { this.failureActions = failureActions; } @@ -118,12 +107,8 @@ public class Loot { return weight; } - public int getTime() { - return time; - } - - public void setTime(int time) { - this.time = time; + public double getScore() { + return score; } public RequirementInterface[] getRequirements() { @@ -133,12 +118,4 @@ public class Loot { public void setRequirements(RequirementInterface[] requirements) { this.requirements = requirements; } - - public double getScore() { - return score; - } - - public void setScore(double score) { - this.score = score; - } } diff --git a/src/main/java/net/momirealms/customfishing/object/loot/Mob.java b/src/main/java/net/momirealms/customfishing/fishing/loot/Mob.java similarity index 72% rename from src/main/java/net/momirealms/customfishing/object/loot/Mob.java rename to src/main/java/net/momirealms/customfishing/fishing/loot/Mob.java index 104d285f..725ccb82 100644 --- a/src/main/java/net/momirealms/customfishing/object/loot/Mob.java +++ b/src/main/java/net/momirealms/customfishing/fishing/loot/Mob.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.loot; +package net.momirealms.customfishing.fishing.loot; -import net.momirealms.customfishing.object.fishing.Difficulty; +import net.momirealms.customfishing.fishing.MiniGameConfig; import org.jetbrains.annotations.NotNull; public class Mob extends Loot{ @@ -26,11 +26,11 @@ public class Mob extends Loot{ private final int mobLevel; private final MobVector mobVector; - public Mob(String key, Difficulty[] difficulty, int time, int weight, String mobID, int level, MobVector vector) { - super(key, difficulty, time, weight); + public Mob(String key, String nick, MiniGameConfig[] fishingGames, int weight, boolean showInFinder, double score, String mobID, int mobLevel, MobVector mobVector) { + super(key, nick, fishingGames, weight, showInFinder, score); this.mobID = mobID; - this.mobLevel = level; - this.mobVector = vector; + this.mobLevel = mobLevel; + this.mobVector = mobVector; } public String getMobID() { diff --git a/src/main/java/net/momirealms/customfishing/object/loot/MobVector.java b/src/main/java/net/momirealms/customfishing/fishing/loot/MobVector.java similarity index 94% rename from src/main/java/net/momirealms/customfishing/object/loot/MobVector.java rename to src/main/java/net/momirealms/customfishing/fishing/loot/MobVector.java index 8686d06c..e2af7b4d 100644 --- a/src/main/java/net/momirealms/customfishing/object/loot/MobVector.java +++ b/src/main/java/net/momirealms/customfishing/fishing/loot/MobVector.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.loot; +package net.momirealms.customfishing.fishing.loot; public record MobVector(double horizontal, double vertical) { diff --git a/src/main/java/net/momirealms/customfishing/fishing/mode/FishingGame.java b/src/main/java/net/momirealms/customfishing/fishing/mode/FishingGame.java new file mode 100644 index 00000000..bbd65ead --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/fishing/mode/FishingGame.java @@ -0,0 +1,69 @@ +package net.momirealms.customfishing.fishing.mode; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.bar.FishingBar; +import net.momirealms.customfishing.manager.FishingManager; +import net.momirealms.customfishing.manager.MessageManager; +import net.momirealms.customfishing.manager.OffsetManager; +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; + +public abstract class FishingGame extends BukkitRunnable { + + protected OffsetManager offsetManager; + protected long deadline; + protected FishingManager fishingManager; + protected CustomFishing plugin; + protected Player player; + protected int difficulty; + protected String title; + + public FishingGame(CustomFishing plugin, FishingManager fishingManager, long deadline, Player player, int difficulty, FishingBar fishingBar) { + this.offsetManager = plugin.getOffsetManager(); + this.fishingManager = fishingManager; + this.player = player; + this.deadline = deadline; + this.difficulty = difficulty; + this.title = fishingBar.getRandomTitle(); + } + + @Override + public void run() { + + } + + public void showBar() { + + } + + public boolean isSuccess() { + return false; + } + + protected boolean timeOut() { + if (System.currentTimeMillis() > deadline) { + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.escape); + cancel(); + fishingManager.removeFishingPlayer(player); + fishingManager.removeBobber(player); + fishingManager.fail(player, null, true); + return true; + } + return false; + } + + protected boolean switchItem() { + PlayerInventory playerInventory = player.getInventory(); + if (playerInventory.getItemInMainHand().getType() != Material.FISHING_ROD && playerInventory.getItemInOffHand().getType() != Material.FISHING_ROD) { + cancel(); + fishingManager.removeFishingPlayer(player); + player.removePotionEffect(PotionEffectType.SLOW); + return true; + } + return false; + } +} diff --git a/src/main/java/net/momirealms/customfishing/fishing/mode/ModeOneGame.java b/src/main/java/net/momirealms/customfishing/fishing/mode/ModeOneGame.java new file mode 100644 index 00000000..e91da4ea --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/fishing/mode/ModeOneGame.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) <2022> + * + * 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 + * 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 net.momirealms.customfishing.fishing.mode; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.bar.ModeOneBar; +import net.momirealms.customfishing.manager.FishingManager; +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.entity.Player; + +public class ModeOneGame extends FishingGame { + + private int progress; + private boolean face; + private final ModeOneBar modeOneBar; + + public ModeOneGame(CustomFishing plugin, FishingManager fishingManager, long deadline, Player player, int difficulty, ModeOneBar modeOneBar) { + super(plugin, fishingManager, deadline, player, difficulty, modeOneBar); + this.face = true; + this.modeOneBar = modeOneBar; + } + + @Override + public void run() { + if (timeOut() || switchItem()) return; + if (face) progress += difficulty; + else progress -= difficulty; + if (progress > modeOneBar.getTotalWidth()) { + face = !face; + progress = 2 * modeOneBar.getTotalWidth() - progress; + } + else if (progress < 0) { + face = !face; + progress = -progress; + } + showBar(); + } + + @Override + public void showBar() { + String bar = + "" + modeOneBar.getBarImage() + + "" + offsetManager.getOffsetChars(modeOneBar.getPointerOffset() + progress) + "" + + modeOneBar.getPointerImage() + + "" + offsetManager.getOffsetChars(modeOneBar.getTotalWidth() - progress - modeOneBar.getPointerWidth()) + ""; + + AdventureUtil.playerTitle(player, title, bar,0,500,0); + } + + @Override + public boolean isSuccess() { + int last = progress / modeOneBar.getWidthPerSection(); + return (Math.random() < modeOneBar.getSuccessRate()[last]); + } +} diff --git a/src/main/java/net/momirealms/customfishing/fishing/mode/ModeTwoGame.java b/src/main/java/net/momirealms/customfishing/fishing/mode/ModeTwoGame.java new file mode 100644 index 00000000..1132fbba --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/fishing/mode/ModeTwoGame.java @@ -0,0 +1,139 @@ +package net.momirealms.customfishing.fishing.mode; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.bar.ModeTwoBar; +import net.momirealms.customfishing.manager.FishingManager; +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.entity.FishHook; +import org.bukkit.entity.Player; + +public class ModeTwoGame extends FishingGame { + + private boolean success; + private double hold_time; + private final ModeTwoBar modeTwoBar; + private double judgement_position; + private double fish_position; + private double judgement_velocity; + private double fish_velocity; + private int timer; + private final int time_requirement; + + public ModeTwoGame(CustomFishing plugin, FishingManager fishingManager, long deadline, Player player, int difficulty, ModeTwoBar modeTwoBar) { + super(plugin, fishingManager, deadline, player, difficulty, modeTwoBar); + this.success = false; + this.judgement_position = (double) modeTwoBar.getBar_effective_width() / 2; + this.fish_position = 0; + this.timer = 0; + this.modeTwoBar = modeTwoBar; + this.time_requirement = modeTwoBar.getRandomTimeRequirement(); + } + + @Override + public void run() { + if (timeOut() || switchItem()) return; + if (player.isSneaking()) addV(); + else reduceV(); + if (timer < 20) { + timer++; + } + else { + timer = 0; + if (Math.random() > ((double) 1 / (difficulty + 1))) { + burst(); + } + } + judgement_position += judgement_velocity; + fish_position += fish_velocity; + fraction(); + calibrate(); + + if (fish_position >= judgement_position && fish_position + modeTwoBar.getFish_icon_width() <= judgement_position + modeTwoBar.getJudgement_area_width()) { + hold_time++; + } + else { + hold_time -= modeTwoBar.getPunishment(); + } + if (hold_time >= time_requirement) { + cancel(); + success = true; + FishHook fishHook = fishingManager.getBobber(player); + if (fishHook != null) { + fishingManager.proceedReelIn(fishHook.getLocation(), player, this); + fishingManager.removeBobber(player); + } + fishingManager.removeFishingPlayer(player); + return; + } + showBar(); + } + + @Override + public void showBar() { + String bar = "" + modeTwoBar.getBarImage() + + "" + offsetManager.getOffsetChars((int) (modeTwoBar.getJudgement_area_offset() + judgement_position)) + "" + + modeTwoBar.getJudgement_area_image() + + "" + offsetManager.getOffsetChars((int) (modeTwoBar.getBar_effective_width() - judgement_position - modeTwoBar.getJudgement_area_width() + 1)) + "" + + "" + offsetManager.getOffsetChars((int) (-modeTwoBar.getBar_effective_width() - 2 + fish_position)) + "" + + modeTwoBar.getFish_image() + + "" + offsetManager.getOffsetChars((int) (modeTwoBar.getBar_effective_width() - fish_position - modeTwoBar.getFish_icon_width() + 1)) + "" + + ""; + if (hold_time > time_requirement) hold_time = time_requirement; + AdventureUtil.playerTitle(player, + title.replace("{progress}", modeTwoBar.getProgress()[(int) ((hold_time / time_requirement) * modeTwoBar.getProgress().length)]) + , bar,0,500,0 + ); + } + + private void burst() { + if (Math.random() < (judgement_position / modeTwoBar.getBar_effective_width())) { + judgement_velocity = -2 - Math.random() * difficulty; + } + else { + judgement_velocity = 2 + Math.random() * difficulty; + } + } + + private void fraction() { + if (judgement_velocity > 0) { + judgement_velocity -= 0.15; + if (judgement_velocity < 0) judgement_velocity = 0; + } + else { + judgement_velocity += 0.15; + if (judgement_velocity > 0) judgement_velocity = 0; + } + } + + private void reduceV() { + fish_velocity -= 0.3; + } + + private void addV() { + fish_velocity += 0.45; + } + + private void calibrate() { + if (fish_position < 0) { + fish_position = 0; + fish_velocity = 0; + } + if (fish_position + modeTwoBar.getFish_icon_width() > modeTwoBar.getBar_effective_width()) { + fish_position = modeTwoBar.getBar_effective_width() - modeTwoBar.getFish_icon_width(); + fish_velocity = 0; + } + if (judgement_position < 0) { + judgement_position = 0; + judgement_velocity = 0; + } + if (judgement_position + modeTwoBar.getJudgement_area_width() > modeTwoBar.getBar_effective_width()) { + judgement_position = modeTwoBar.getBar_effective_width() - modeTwoBar.getJudgement_area_width(); + judgement_velocity = 0; + } + } + + @Override + public boolean isSuccess() { + return success; + } +} diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/BiomeImpl.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/BiomeImpl.java similarity index 86% rename from src/main/java/net/momirealms/customfishing/object/requirements/BiomeImpl.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/BiomeImpl.java index e2f82863..88d67771 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/BiomeImpl.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/BiomeImpl.java @@ -15,11 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements; +package net.momirealms.customfishing.fishing.requirements; import net.momirealms.biomeapi.BiomeAPI; -import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.object.fishing.FishingCondition; +import net.momirealms.customfishing.fishing.FishingCondition; import java.util.List; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/CustomPapi.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/CustomPapi.java similarity index 96% rename from src/main/java/net/momirealms/customfishing/object/requirements/CustomPapi.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/CustomPapi.java index 2a831690..ed892468 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/CustomPapi.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/CustomPapi.java @@ -15,10 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements; +package net.momirealms.customfishing.fishing.requirements; -import net.momirealms.customfishing.object.fishing.FishingCondition; -import net.momirealms.customfishing.object.requirements.papi.*; +import net.momirealms.customfishing.fishing.FishingCondition; +import net.momirealms.customfishing.fishing.requirements.papi.*; import org.bukkit.configuration.MemorySection; import java.util.ArrayList; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/PermissionImpl.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/PermissionImpl.java similarity index 88% rename from src/main/java/net/momirealms/customfishing/object/requirements/PermissionImpl.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/PermissionImpl.java index 5da0d39e..eb794579 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/PermissionImpl.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/PermissionImpl.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements; +package net.momirealms.customfishing.fishing.requirements; -import net.momirealms.customfishing.object.fishing.FishingCondition; +import net.momirealms.customfishing.fishing.FishingCondition; public record PermissionImpl(String permission) implements RequirementInterface { diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/RequirementInterface.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/RequirementInterface.java similarity index 86% rename from src/main/java/net/momirealms/customfishing/object/requirements/RequirementInterface.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/RequirementInterface.java index e3ffe51b..208789c8 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/RequirementInterface.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/RequirementInterface.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements; +package net.momirealms.customfishing.fishing.requirements; -import net.momirealms.customfishing.object.fishing.FishingCondition; +import net.momirealms.customfishing.fishing.FishingCondition; public interface RequirementInterface { boolean isConditionMet(FishingCondition fishingCondition); diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/SeasonImpl.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/SeasonImpl.java similarity index 84% rename from src/main/java/net/momirealms/customfishing/object/requirements/SeasonImpl.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/SeasonImpl.java index b336b80d..04b857e5 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/SeasonImpl.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/SeasonImpl.java @@ -15,11 +15,11 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements; +package net.momirealms.customfishing.fishing.requirements; import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.FishingCondition; import net.momirealms.customfishing.integration.SeasonInterface; -import net.momirealms.customfishing.object.fishing.FishingCondition; import java.util.List; @@ -27,7 +27,7 @@ public record SeasonImpl(List seasons) implements RequirementInterface { @Override public boolean isConditionMet(FishingCondition fishingCondition) { - SeasonInterface seasonInterface = CustomFishing.plugin.getIntegrationManager().getSeasonInterface(); + SeasonInterface seasonInterface = CustomFishing.getInstance().getIntegrationManager().getSeasonInterface(); if (seasonInterface == null) return true; String currentSeason = seasonInterface.getSeason(fishingCondition.getLocation().getWorld()); for (String season : seasons) { diff --git a/src/main/java/net/momirealms/customfishing/fishing/requirements/SkillLevelImpl.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/SkillLevelImpl.java new file mode 100644 index 00000000..bfce89d5 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/SkillLevelImpl.java @@ -0,0 +1,12 @@ +package net.momirealms.customfishing.fishing.requirements; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.FishingCondition; + +public record SkillLevelImpl(int level) implements RequirementInterface { + + @Override + public boolean isConditionMet(FishingCondition fishingCondition) { + return CustomFishing.getInstance().getIntegrationManager().getSkillInterface().getLevel(fishingCondition.getPlayer()) >= level; + } +} diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/TimeImpl.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/TimeImpl.java similarity index 90% rename from src/main/java/net/momirealms/customfishing/object/requirements/TimeImpl.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/TimeImpl.java index 276b6205..31e34561 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/TimeImpl.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/TimeImpl.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements; +package net.momirealms.customfishing.fishing.requirements; -import net.momirealms.customfishing.object.fishing.FishingCondition; +import net.momirealms.customfishing.fishing.FishingCondition; import org.apache.commons.lang.StringUtils; import java.util.List; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/WeatherImpl.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/WeatherImpl.java similarity index 91% rename from src/main/java/net/momirealms/customfishing/object/requirements/WeatherImpl.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/WeatherImpl.java index f458442c..bb2def86 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/WeatherImpl.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/WeatherImpl.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements; +package net.momirealms.customfishing.fishing.requirements; -import net.momirealms.customfishing.object.fishing.FishingCondition; +import net.momirealms.customfishing.fishing.FishingCondition; import org.bukkit.World; import java.util.List; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/WorldImpl.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/WorldImpl.java similarity index 89% rename from src/main/java/net/momirealms/customfishing/object/requirements/WorldImpl.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/WorldImpl.java index 4019bbe9..698f1553 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/WorldImpl.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/WorldImpl.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements; +package net.momirealms.customfishing.fishing.requirements; -import net.momirealms.customfishing.object.fishing.FishingCondition; +import net.momirealms.customfishing.fishing.FishingCondition; import java.util.List; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/YPosImpl.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/YPosImpl.java similarity index 90% rename from src/main/java/net/momirealms/customfishing/object/requirements/YPosImpl.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/YPosImpl.java index 06578fa0..168cbecd 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/YPosImpl.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/YPosImpl.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements; +package net.momirealms.customfishing.fishing.requirements; -import net.momirealms.customfishing.object.fishing.FishingCondition; +import net.momirealms.customfishing.fishing.FishingCondition; import org.apache.commons.lang.StringUtils; import java.util.List; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionAnd.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/ExpressionAnd.java similarity index 94% rename from src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionAnd.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/papi/ExpressionAnd.java index bec9d051..b3df5bae 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionAnd.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/ExpressionAnd.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements.papi; +package net.momirealms.customfishing.fishing.requirements.papi; import org.bukkit.entity.Player; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionOr.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/ExpressionOr.java similarity index 94% rename from src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionOr.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/papi/ExpressionOr.java index 9f7cf67b..dd43d52a 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionOr.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/ExpressionOr.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements.papi; +package net.momirealms.customfishing.fishing.requirements.papi; import org.bukkit.entity.Player; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiEquals.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiEquals.java similarity index 94% rename from src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiEquals.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiEquals.java index f46d41f2..605e5736 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiEquals.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiEquals.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements.papi; +package net.momirealms.customfishing.fishing.requirements.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiGreater.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiGreater.java similarity index 94% rename from src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiGreater.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiGreater.java index 6349ed12..e5e16a25 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiGreater.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiGreater.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements.papi; +package net.momirealms.customfishing.fishing.requirements.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLarger.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiNoLarger.java similarity index 94% rename from src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLarger.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiNoLarger.java index 9b064cb4..5791e460 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLarger.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiNoLarger.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements.papi; +package net.momirealms.customfishing.fishing.requirements.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLess.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiNoLess.java similarity index 94% rename from src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLess.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiNoLess.java index e8ffa6fd..973a8611 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLess.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiNoLess.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements.papi; +package net.momirealms.customfishing.fishing.requirements.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNotEquals.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiNotEquals.java similarity index 94% rename from src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNotEquals.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiNotEquals.java index dab15150..37a7e85c 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNotEquals.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiNotEquals.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements.papi; +package net.momirealms.customfishing.fishing.requirements.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiRequirement.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiRequirement.java similarity index 93% rename from src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiRequirement.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiRequirement.java index db82f721..2d5a5441 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiRequirement.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiRequirement.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements.papi; +package net.momirealms.customfishing.fishing.requirements.papi; import org.bukkit.entity.Player; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiSmaller.java b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiSmaller.java similarity index 94% rename from src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiSmaller.java rename to src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiSmaller.java index a6602d94..3dc21789 100644 --- a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiSmaller.java +++ b/src/main/java/net/momirealms/customfishing/fishing/requirements/papi/PapiSmaller.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.requirements.papi; +package net.momirealms.customfishing.fishing.requirements.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; diff --git a/src/main/java/net/momirealms/customfishing/object/totem/ActivatedTotem.java b/src/main/java/net/momirealms/customfishing/fishing/totem/ActivatedTotem.java similarity index 83% rename from src/main/java/net/momirealms/customfishing/object/totem/ActivatedTotem.java rename to src/main/java/net/momirealms/customfishing/fishing/totem/ActivatedTotem.java index 5113d329..0df2d472 100644 --- a/src/main/java/net/momirealms/customfishing/object/totem/ActivatedTotem.java +++ b/src/main/java/net/momirealms/customfishing/fishing/totem/ActivatedTotem.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.totem; +package net.momirealms.customfishing.fishing.totem; import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.manager.FishingManager; @@ -54,7 +54,7 @@ public class ActivatedTotem extends BukkitRunnable { this.hasHolo = totem.getHoloText() != null; this.nearbyPlayerSet = Collections.synchronizedSet(new HashSet<>()); this.particleTimerTask = new TotemParticle(location, totem.getRadius(), totem.getParticle()); - this.particleTimerTask.runTaskTimerAsynchronously(CustomFishing.plugin, 0, 4); + this.particleTimerTask.runTaskTimerAsynchronously(CustomFishing.getInstance(), 0, 4); this.direction = direction; } @@ -74,7 +74,7 @@ public class ActivatedTotem extends BukkitRunnable { if (nearbyPlayers.remove(player)) { if (hasHolo) { for (int i = 0; i < entityID.length; i++) { - CustomFishing.protocolManager.sendServerPacket(player, ArmorStandUtil.getMetaPacket(entityID[i], + CustomFishing.getProtocolManager().sendServerPacket(player, ArmorStandUtil.getMetaPacket(entityID[i], totem.getHoloText()[entityID.length - 1 - i].replace("{time}", String.valueOf(totem.getDuration() - timer)) .replace("{max_time}", String.valueOf(totem.getDuration())) )); @@ -85,7 +85,7 @@ public class ActivatedTotem extends BukkitRunnable { else { if (hasHolo) { for (int j : entityID) { - CustomFishing.protocolManager.sendServerPacket(player, ArmorStandUtil.getDestroyPacket(j)); + CustomFishing.getProtocolManager().sendServerPacket(player, ArmorStandUtil.getDestroyPacket(j)); } } nearbyPlayerSet.remove(player); @@ -95,8 +95,8 @@ public class ActivatedTotem extends BukkitRunnable { for (Player newComer : nearbyPlayers) { if (hasHolo) { for (int i = 0; i < entityID.length; i++) { - CustomFishing.protocolManager.sendServerPacket(newComer, ArmorStandUtil.getSpawnPacket(entityID[i], location.clone().add(0.5, totem.getHoloOffset() + i * 0.4, 0.5))); - CustomFishing.protocolManager.sendServerPacket(newComer, ArmorStandUtil.getMetaPacket(entityID[i], + CustomFishing.getProtocolManager().sendServerPacket(newComer, ArmorStandUtil.getSpawnPacket(entityID[i], location.clone().add(0.5, totem.getHoloOffset() + i * 0.4, 0.5))); + CustomFishing.getProtocolManager().sendServerPacket(newComer, ArmorStandUtil.getMetaPacket(entityID[i], totem.getHoloText()[entityID.length - 1 - i].replace("{time}", String.valueOf(totem.getDuration() - timer)) .replace("{max_time}", String.valueOf(totem.getDuration())) )); @@ -119,11 +119,11 @@ public class ActivatedTotem extends BukkitRunnable { this.particleTimerTask.cancel(); cancel(); fishingManager.removeTotem(location); - CustomFishing.plugin.getTotemManager().clearBreakDetectCache(totem.getFinalModel(), location, direction); + CustomFishing.getInstance().getTotemManager().clearBreakDetectCache(totem.getFinalModel(), location, direction); if (hasHolo) { for (Player player : nearbyPlayerSet) { for (int j : entityID) { - CustomFishing.protocolManager.sendServerPacket(player, ArmorStandUtil.getDestroyPacket(j)); + CustomFishing.getProtocolManager().sendServerPacket(player, ArmorStandUtil.getDestroyPacket(j)); } } } diff --git a/src/main/java/net/momirealms/customfishing/object/totem/CorePos.java b/src/main/java/net/momirealms/customfishing/fishing/totem/CorePos.java similarity index 95% rename from src/main/java/net/momirealms/customfishing/object/totem/CorePos.java rename to src/main/java/net/momirealms/customfishing/fishing/totem/CorePos.java index 8466fc2c..b6ddccb4 100644 --- a/src/main/java/net/momirealms/customfishing/object/totem/CorePos.java +++ b/src/main/java/net/momirealms/customfishing/fishing/totem/CorePos.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.totem; +package net.momirealms.customfishing.fishing.totem; public class CorePos { diff --git a/src/main/java/net/momirealms/customfishing/object/totem/FinalModel.java b/src/main/java/net/momirealms/customfishing/fishing/totem/FinalModel.java similarity index 97% rename from src/main/java/net/momirealms/customfishing/object/totem/FinalModel.java rename to src/main/java/net/momirealms/customfishing/fishing/totem/FinalModel.java index dc9a3514..3329f738 100644 --- a/src/main/java/net/momirealms/customfishing/object/totem/FinalModel.java +++ b/src/main/java/net/momirealms/customfishing/fishing/totem/FinalModel.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.totem; +package net.momirealms.customfishing.fishing.totem; public class FinalModel { diff --git a/src/main/java/net/momirealms/customfishing/object/totem/OriginalModel.java b/src/main/java/net/momirealms/customfishing/fishing/totem/OriginalModel.java similarity index 97% rename from src/main/java/net/momirealms/customfishing/object/totem/OriginalModel.java rename to src/main/java/net/momirealms/customfishing/fishing/totem/OriginalModel.java index aa793a79..15a3b0a6 100644 --- a/src/main/java/net/momirealms/customfishing/object/totem/OriginalModel.java +++ b/src/main/java/net/momirealms/customfishing/fishing/totem/OriginalModel.java @@ -16,7 +16,7 @@ */ -package net.momirealms.customfishing.object.totem; +package net.momirealms.customfishing.fishing.totem; import java.util.Arrays; diff --git a/src/main/java/net/momirealms/customfishing/object/totem/Totem.java b/src/main/java/net/momirealms/customfishing/fishing/totem/Totem.java similarity index 89% rename from src/main/java/net/momirealms/customfishing/object/totem/Totem.java rename to src/main/java/net/momirealms/customfishing/fishing/totem/Totem.java index 494e548b..44f3ebe7 100644 --- a/src/main/java/net/momirealms/customfishing/object/totem/Totem.java +++ b/src/main/java/net/momirealms/customfishing/fishing/totem/Totem.java @@ -15,11 +15,11 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.totem; +package net.momirealms.customfishing.fishing.totem; +import net.momirealms.customfishing.fishing.Effect; +import net.momirealms.customfishing.fishing.requirements.RequirementInterface; import net.momirealms.customfishing.object.action.ActionInterface; -import net.momirealms.customfishing.object.fishing.Bonus; -import net.momirealms.customfishing.object.requirements.RequirementInterface; import org.bukkit.Particle; import org.bukkit.potion.PotionEffect; @@ -31,20 +31,20 @@ public class Totem { private final int radius; private final Particle particle; private final int duration; - private final Bonus bonus; + private final Effect effect; private ActionInterface[] activatorActions; private ActionInterface[] nearbyActions; private double holoOffset; private String[] holoText; private PotionEffect[] potionEffects; - public Totem(OriginalModel originalModel, FinalModel finalModel, int radius, int duration, Particle particle, Bonus bonus) { + public Totem(OriginalModel originalModel, FinalModel finalModel, int radius, int duration, Particle particle, Effect effect) { this.originalModel = originalModel; this.finalModel = finalModel; this.radius = radius; this.duration = duration; this.particle = particle; - this.bonus = bonus; + this.effect = effect; } public RequirementInterface[] getRequirements() { @@ -80,8 +80,8 @@ public class Totem { return duration; } - public Bonus getBonus() { - return bonus; + public Effect getBonus() { + return effect; } public ActionInterface[] getActivatorActions() { diff --git a/src/main/java/net/momirealms/customfishing/object/totem/TotemConfig.java b/src/main/java/net/momirealms/customfishing/fishing/totem/TotemConfig.java similarity index 89% rename from src/main/java/net/momirealms/customfishing/object/totem/TotemConfig.java rename to src/main/java/net/momirealms/customfishing/fishing/totem/TotemConfig.java index 813c09a4..f2e71e80 100644 --- a/src/main/java/net/momirealms/customfishing/object/totem/TotemConfig.java +++ b/src/main/java/net/momirealms/customfishing/fishing/totem/TotemConfig.java @@ -15,11 +15,11 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.totem; +package net.momirealms.customfishing.fishing.totem; +import net.momirealms.customfishing.fishing.Effect; +import net.momirealms.customfishing.fishing.requirements.RequirementInterface; import net.momirealms.customfishing.object.action.ActionInterface; -import net.momirealms.customfishing.object.fishing.Bonus; -import net.momirealms.customfishing.object.requirements.RequirementInterface; import org.bukkit.Particle; import org.bukkit.potion.PotionEffect; @@ -31,20 +31,20 @@ public class TotemConfig { private final int radius; private final Particle particle; private final int duration; - private final Bonus bonus; + private final Effect effect; private ActionInterface[] activatorActions; private ActionInterface[] nearbyActions; private double holoOffset; private String[] holoText; private PotionEffect[] potionEffects; - public TotemConfig(OriginalModel originalModel, FinalModel finalModel, int radius, int duration, Particle particle, Bonus bonus) { + public TotemConfig(OriginalModel originalModel, FinalModel finalModel, int radius, int duration, Particle particle, Effect effect) { this.originalModel = originalModel; this.finalModel = finalModel; this.radius = radius; this.duration = duration; this.particle = particle; - this.bonus = bonus; + this.effect = effect; } public RequirementInterface[] getRequirements() { @@ -80,8 +80,8 @@ public class TotemConfig { return duration; } - public Bonus getBonus() { - return bonus; + public Effect getBonus() { + return effect; } public ActionInterface[] getActivatorActions() { diff --git a/src/main/java/net/momirealms/customfishing/object/totem/TotemParticle.java b/src/main/java/net/momirealms/customfishing/fishing/totem/TotemParticle.java similarity index 97% rename from src/main/java/net/momirealms/customfishing/object/totem/TotemParticle.java rename to src/main/java/net/momirealms/customfishing/fishing/totem/TotemParticle.java index 22464ab3..b1af04bd 100644 --- a/src/main/java/net/momirealms/customfishing/object/totem/TotemParticle.java +++ b/src/main/java/net/momirealms/customfishing/fishing/totem/TotemParticle.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.totem; +package net.momirealms.customfishing.fishing.totem; import org.bukkit.Location; import org.bukkit.Particle; diff --git a/src/main/java/net/momirealms/customfishing/helper/LibraryLoader.java b/src/main/java/net/momirealms/customfishing/helper/LibraryLoader.java index 23f2c81b..20c211e5 100644 --- a/src/main/java/net/momirealms/customfishing/helper/LibraryLoader.java +++ b/src/main/java/net/momirealms/customfishing/helper/LibraryLoader.java @@ -45,7 +45,7 @@ import java.util.Objects; public final class LibraryLoader { @SuppressWarnings("Guava") - private static final Supplier URL_INJECTOR = Suppliers.memoize(() -> URLClassLoaderAccess.create((URLClassLoader) CustomFishing.plugin.getClass().getClassLoader())); + private static final Supplier URL_INJECTOR = Suppliers.memoize(() -> URLClassLoaderAccess.create((URLClassLoader) CustomFishing.getInstance().getClass().getClassLoader())); /** * Resolves all {@link MavenLibrary} annotations on the given object. @@ -109,7 +109,7 @@ public final class LibraryLoader { } private static File getLibFolder(Dependency dependency) { - File pluginDataFolder = CustomFishing.plugin.getDataFolder(); + File pluginDataFolder = CustomFishing.getInstance().getDataFolder(); File serverDir = pluginDataFolder.getParentFile().getParentFile(); File helperDir = new File(serverDir, "libraries"); diff --git a/src/main/java/net/momirealms/customfishing/helper/Log.java b/src/main/java/net/momirealms/customfishing/helper/Log.java index 30ad817a..81d1efde 100644 --- a/src/main/java/net/momirealms/customfishing/helper/Log.java +++ b/src/main/java/net/momirealms/customfishing/helper/Log.java @@ -37,23 +37,23 @@ import java.util.logging.Level; public final class Log { public static void info(@NotNull String s) { - CustomFishing.plugin.getLogger().info(s); + CustomFishing.getInstance().getLogger().info(s); } public static void warn(@NotNull String s) { - CustomFishing.plugin.getLogger().warning(s); + CustomFishing.getInstance().getLogger().warning(s); } public static void severe(@NotNull String s) { - CustomFishing.plugin.getLogger().severe(s); + CustomFishing.getInstance().getLogger().severe(s); } public static void warn(@NotNull String s, Throwable t) { - CustomFishing.plugin.getLogger().log(Level.WARNING, s, t); + CustomFishing.getInstance().getLogger().log(Level.WARNING, s, t); } public static void severe(@NotNull String s, Throwable t) { - CustomFishing.plugin.getLogger().log(Level.SEVERE, s, t); + CustomFishing.getInstance().getLogger().log(Level.SEVERE, s, t); } private Log() { diff --git a/src/main/java/net/momirealms/customfishing/helper/VersionHelper.java b/src/main/java/net/momirealms/customfishing/helper/VersionHelper.java index a2d23802..135d58ab 100644 --- a/src/main/java/net/momirealms/customfishing/helper/VersionHelper.java +++ b/src/main/java/net/momirealms/customfishing/helper/VersionHelper.java @@ -1,15 +1,26 @@ package net.momirealms.customfishing.helper; -import org.bukkit.Bukkit; +import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion; +import de.tr7zw.changeme.nbtapi.utils.VersionChecker; +import net.momirealms.customfishing.CustomFishing; + +import java.lang.reflect.Field; public class VersionHelper { private boolean isNewerThan1_19_R2; private String version; + private final CustomFishing plugin; + + public VersionHelper(CustomFishing plugin) { + this.plugin = plugin; + isVersionNewerThan1_19_R2(); + disableUseLessInfo(); + } public boolean isVersionNewerThan1_19_R2() { if (version == null) { - version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + version = plugin.getServer().getClass().getPackage().getName().split("\\.")[3]; String[] split = version.split("_"); int main_ver = Integer.parseInt(split[1]); if (main_ver >= 20) isNewerThan1_19_R2 = true; @@ -18,4 +29,37 @@ public class VersionHelper { } return isNewerThan1_19_R2; } + + private void disableUseLessInfo() { + MinecraftVersion.disableBStats(); + MinecraftVersion.disableUpdateCheck(); + VersionChecker.hideOk = true; + try { + Field field = MinecraftVersion.class.getDeclaredField("version"); + field.setAccessible(true); + MinecraftVersion minecraftVersion; + try { + minecraftVersion = MinecraftVersion.valueOf(version.replace("v", "MC")); + } catch (IllegalArgumentException ex) { + minecraftVersion = MinecraftVersion.UNKNOWN; + } + field.set(MinecraftVersion.class, minecraftVersion); + } catch (NoSuchFieldException | IllegalAccessException e) { + throw new RuntimeException(e); + } + boolean hasGsonSupport; + try { + Class.forName("com.google.gson.Gson"); + hasGsonSupport = true; + } catch (Exception ex) { + hasGsonSupport = false; + } + try { + Field field= MinecraftVersion.class.getDeclaredField("hasGsonSupport"); + field.setAccessible(true); + field.set(Boolean.class, hasGsonSupport); + } catch (NoSuchFieldException | IllegalAccessException e) { + throw new RuntimeException(e); + } + } } diff --git a/src/main/java/net/momirealms/customfishing/integration/AntiGriefInterface.java b/src/main/java/net/momirealms/customfishing/integration/AntiGriefInterface.java deleted file mode 100644 index cda2bd28..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/AntiGriefInterface.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration; - -import net.momirealms.customfishing.CustomFishing; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public interface AntiGriefInterface { - - boolean canBreak(Location location, Player player); - - boolean canPlace(Location location, Player player); - - static boolean testBreak(Player player, Location location) { - for (AntiGriefInterface antiGrief : CustomFishing.plugin.getIntegrationManager().getAntiGriefs()) { - if(!antiGrief.canBreak(location, player)) { - return false; - } - } - return true; - } - - static boolean testPlace(Player player, Location location) { - for (AntiGriefInterface antiGrief : CustomFishing.plugin.getIntegrationManager().getAntiGriefs()) { - if(!antiGrief.canPlace(location, player)) { - return false; - } - } - return true; - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/MobInterface.java b/src/main/java/net/momirealms/customfishing/integration/MobInterface.java index 9675623f..8a89e5d6 100644 --- a/src/main/java/net/momirealms/customfishing/integration/MobInterface.java +++ b/src/main/java/net/momirealms/customfishing/integration/MobInterface.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.integration; -import net.momirealms.customfishing.object.loot.Mob; +import net.momirealms.customfishing.fishing.loot.Mob; import org.bukkit.Location; public interface MobInterface { diff --git a/src/main/java/net/momirealms/customfishing/integration/VaultHook.java b/src/main/java/net/momirealms/customfishing/integration/VaultHook.java index 93160759..cd3a3113 100644 --- a/src/main/java/net/momirealms/customfishing/integration/VaultHook.java +++ b/src/main/java/net/momirealms/customfishing/integration/VaultHook.java @@ -26,7 +26,7 @@ public class VaultHook { private Economy economy; public boolean initialize() { - RegisteredServiceProvider rsp = CustomFishing.plugin.getServer().getServicesManager().getRegistration(Economy.class); + RegisteredServiceProvider rsp = CustomFishing.getInstance().getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) { return false; } diff --git a/src/main/java/net/momirealms/customfishing/integration/antigrief/BentoBoxHook.java b/src/main/java/net/momirealms/customfishing/integration/antigrief/BentoBoxHook.java deleted file mode 100644 index c28e21b1..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/antigrief/BentoBoxHook.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration.antigrief; - -import net.momirealms.customfishing.integration.AntiGriefInterface; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import world.bentobox.bentobox.BentoBox; -import world.bentobox.bentobox.api.user.User; -import world.bentobox.bentobox.database.objects.Island; -import world.bentobox.bentobox.lists.Flags; - -import java.util.Optional; - -public class BentoBoxHook implements AntiGriefInterface { - - @Override - public boolean canBreak(Location location, Player player) { - User user = User.getInstance(player); - Optional islandOptional = BentoBox.getInstance().getIslands().getIslandAt(location); - return islandOptional.map(island -> island.isAllowed(user, Flags.BREAK_BLOCKS)).orElse(true); - } - - @Override - public boolean canPlace(Location location, Player player) { - User user = User.getInstance(player); - Optional islandOptional = BentoBox.getInstance().getIslands().getIslandAt(location); - return islandOptional.map(island -> island.isAllowed(user, Flags.PLACE_BLOCKS)).orElse(true); - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/antigrief/CrashClaimHook.java b/src/main/java/net/momirealms/customfishing/integration/antigrief/CrashClaimHook.java deleted file mode 100644 index 1e960aeb..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/antigrief/CrashClaimHook.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration.antigrief; - -import net.crashcraft.crashclaim.api.CrashClaimAPI; -import net.crashcraft.crashclaim.permissions.PermissionRoute; -import net.momirealms.customfishing.integration.AntiGriefInterface; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class CrashClaimHook implements AntiGriefInterface { - - @Override - public boolean canBreak(Location location, Player player) { - CrashClaimAPI crashClaimAPI = net.crashcraft.crashclaim.CrashClaim.getPlugin().getApi(); - return crashClaimAPI.getPermissionHelper().hasPermission(player.getUniqueId(), location, PermissionRoute.BUILD); - } - - @Override - public boolean canPlace(Location location, Player player) { - CrashClaimAPI crashClaimAPI = net.crashcraft.crashclaim.CrashClaim.getPlugin().getApi(); - return crashClaimAPI.getPermissionHelper().hasPermission(player.getUniqueId(), location, PermissionRoute.BUILD); - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/antigrief/GriefDefenderHook.java b/src/main/java/net/momirealms/customfishing/integration/antigrief/GriefDefenderHook.java deleted file mode 100644 index b7d32b38..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/antigrief/GriefDefenderHook.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration.antigrief; - -import net.momirealms.customfishing.integration.AntiGriefInterface; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class GriefDefenderHook implements AntiGriefInterface { - - @Override - public boolean canBreak(Location location, Player player) { - return com.griefdefender.api.GriefDefender.getCore().getUser(player.getUniqueId()).canBreak(location); - } - - @Override - public boolean canPlace(Location location, Player player) { - return com.griefdefender.api.GriefDefender.getCore().getUser(player.getUniqueId()).canPlace(player.getInventory().getItemInMainHand(), location); - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/antigrief/GriefPreventionHook.java b/src/main/java/net/momirealms/customfishing/integration/antigrief/GriefPreventionHook.java deleted file mode 100644 index 1125f675..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/antigrief/GriefPreventionHook.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration.antigrief; - -import net.momirealms.customfishing.integration.AntiGriefInterface; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class GriefPreventionHook implements AntiGriefInterface { - - @Override - public boolean canBreak(Location location, Player player) { - return me.ryanhamshire.GriefPrevention.GriefPrevention.instance.allowBreak(player, location.getBlock(), location) == null; - } - - @Override - public boolean canPlace(Location location, Player player) { - return me.ryanhamshire.GriefPrevention.GriefPrevention.instance.allowBuild(player, location) == null; - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/antigrief/KingdomsXHook.java b/src/main/java/net/momirealms/customfishing/integration/antigrief/KingdomsXHook.java deleted file mode 100644 index 02e6b0fd..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/antigrief/KingdomsXHook.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration.antigrief; - -import net.momirealms.customfishing.integration.AntiGriefInterface; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.kingdoms.constants.group.Kingdom; -import org.kingdoms.constants.land.Land; -import org.kingdoms.constants.player.KingdomPlayer; - -public class KingdomsXHook implements AntiGriefInterface { - - @Override - public boolean canBreak(Location location, Player player) { - return kingdomsCheck(location, player); - } - - @Override - public boolean canPlace(Location location, Player player) { - return kingdomsCheck(location, player); - } - - private boolean kingdomsCheck(Location location, Player player) { - Land land = Land.getLand(location); - if (land == null) return true; - if (land.isClaimed()) { - KingdomPlayer kp = KingdomPlayer.getKingdomPlayer(player); - Kingdom cropKingdom = land.getKingdom(); - if (kp.getKingdom() != null) { - Kingdom kingdom = kp.getKingdom(); - return kingdom != cropKingdom; - } - else return false; - } - else return true; - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/antigrief/LandsHook.java b/src/main/java/net/momirealms/customfishing/integration/antigrief/LandsHook.java deleted file mode 100644 index f33e8afe..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/antigrief/LandsHook.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration.antigrief; - -import me.angeschossen.lands.api.LandsIntegration; -import me.angeschossen.lands.api.flags.types.RoleFlag; -import me.angeschossen.lands.api.land.LandWorld; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customfishing.integration.AntiGriefInterface; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class LandsHook implements AntiGriefInterface { - - private final LandsIntegration api; - - public LandsHook() { - api = LandsIntegration.of(CustomCrops.plugin);; - } - - @Override - public boolean canBreak(Location location, Player player) { - LandWorld world = api.getWorld(location.getWorld()); - if (world != null) { - return world.hasRoleFlag(player.getUniqueId(), location, RoleFlag.of("BLOCK_BREAK")); - } - return true; - } - - @Override - public boolean canPlace(Location location, Player player) { - LandWorld world = api.getWorld(location.getWorld()); - if (world != null) { - return world.hasRoleFlag(player.getUniqueId(), location, RoleFlag.of("BLOCK_PLACE")); - } - return true; - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/antigrief/PlotSquaredHook.java b/src/main/java/net/momirealms/customfishing/integration/antigrief/PlotSquaredHook.java deleted file mode 100644 index 914b0746..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/antigrief/PlotSquaredHook.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration.antigrief; - -import com.plotsquared.core.location.Location; -import net.momirealms.customfishing.integration.AntiGriefInterface; -import org.bukkit.entity.Player; - -public class PlotSquaredHook implements AntiGriefInterface { - - @Override - public boolean canBreak(org.bukkit.Location location, Player player) { - return isAllowed(location, player); - } - - @Override - public boolean canPlace(org.bukkit.Location location, Player player) { - return isAllowed(location, player); - } - - private boolean isAllowed(org.bukkit.Location location, Player player) { - Location plotLoc = Location.at(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (plotLoc.isPlotRoad()) return false; - if (plotLoc.getPlotArea() != null) return plotLoc.getPlotArea().getPlot(plotLoc).isAdded(player.getUniqueId()); - else return true; - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/antigrief/ResidenceHook.java b/src/main/java/net/momirealms/customfishing/integration/antigrief/ResidenceHook.java deleted file mode 100644 index bcefdfd8..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/antigrief/ResidenceHook.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration.antigrief; - -import com.bekvon.bukkit.residence.containers.Flags; -import com.bekvon.bukkit.residence.protection.ClaimedResidence; -import com.bekvon.bukkit.residence.protection.ResidencePermissions; -import net.momirealms.customfishing.integration.AntiGriefInterface; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class ResidenceHook implements AntiGriefInterface { - - @Override - public boolean canBreak(Location location, Player player) { - ClaimedResidence res = com.bekvon.bukkit.residence.Residence.getInstance().getResidenceManager().getByLoc(location); - if(res!=null){ - ResidencePermissions perms = res.getPermissions(); - return perms.playerHas(player, Flags.destroy, true); - } - return true; - } - - @Override - public boolean canPlace(Location location, Player player) { - ClaimedResidence res = com.bekvon.bukkit.residence.Residence.getInstance().getResidenceManager().getByLoc(location); - if(res!=null){ - ResidencePermissions perms = res.getPermissions(); - return perms.playerHas(player, Flags.build, true); - } - return true; - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/antigrief/TownyHook.java b/src/main/java/net/momirealms/customfishing/integration/antigrief/TownyHook.java deleted file mode 100644 index 754b034b..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/antigrief/TownyHook.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration.antigrief; - -import com.palmergames.bukkit.towny.object.TownyPermission; -import com.palmergames.bukkit.towny.utils.PlayerCacheUtil; -import net.momirealms.customfishing.integration.AntiGriefInterface; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class TownyHook implements AntiGriefInterface { - - @Override - public boolean canBreak(Location location, Player player) { - return TownyPermission(player, location, TownyPermission.ActionType.DESTROY); - } - - @Override - public boolean canPlace(Location location, Player player) { - return TownyPermission(player, location, TownyPermission.ActionType.BUILD); - } - - private boolean TownyPermission(Player player, Location location, TownyPermission.ActionType actionType){ - return PlayerCacheUtil.getCachePermission(player, location, location.getBlock().getType(), actionType); - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/antigrief/WorldGuardHook.java b/src/main/java/net/momirealms/customfishing/integration/antigrief/WorldGuardHook.java deleted file mode 100644 index 4ee48e4e..00000000 --- a/src/main/java/net/momirealms/customfishing/integration/antigrief/WorldGuardHook.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.integration.antigrief; - -import com.sk89q.worldedit.bukkit.BukkitAdapter; -import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.world.World; -import com.sk89q.worldguard.LocalPlayer; -import com.sk89q.worldguard.bukkit.WorldGuardPlugin; -import com.sk89q.worldguard.internal.platform.WorldGuardPlatform; -import com.sk89q.worldguard.protection.flags.Flags; -import com.sk89q.worldguard.protection.managers.RegionManager; -import com.sk89q.worldguard.protection.regions.RegionContainer; -import com.sk89q.worldguard.protection.regions.RegionQuery; -import net.momirealms.customfishing.integration.AntiGriefInterface; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class WorldGuardHook implements AntiGriefInterface { - - @Override - public boolean canPlace(Location location, Player player) { - if (player.isOp()) return true; - LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player); - World world = BukkitAdapter.adapt(location.getWorld()); - WorldGuardPlatform platform = com.sk89q.worldguard.WorldGuard.getInstance().getPlatform(); - if (hasRegion(world, BukkitAdapter.asBlockVector(location))){ - RegionQuery query = platform.getRegionContainer().createQuery(); - return query.testBuild(BukkitAdapter.adapt(location), localPlayer, Flags.BUILD); - } - else return true; - } - - @Override - public boolean canBreak(Location location, Player player) { - if (player.isOp()) return true; - LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player); - World world = BukkitAdapter.adapt(location.getWorld()); - WorldGuardPlatform platform = com.sk89q.worldguard.WorldGuard.getInstance().getPlatform(); - if (hasRegion(world, BukkitAdapter.asBlockVector(location))){ - RegionQuery query = platform.getRegionContainer().createQuery(); - return query.testBuild(BukkitAdapter.adapt(location), localPlayer, Flags.BLOCK_BREAK); - } - else return true; - } - - private boolean hasRegion(World world, BlockVector3 vector){ - RegionContainer container = com.sk89q.worldguard.WorldGuard.getInstance().getPlatform().getRegionContainer(); - RegionManager regionManager = container.get(world); - if (regionManager == null) return true; - return regionManager.getApplicableRegions(vector).size() > 0; - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/integration/block/ItemsAdderBlockImpl.java b/src/main/java/net/momirealms/customfishing/integration/block/ItemsAdderBlockImpl.java index 14c8983a..0e6e6628 100644 --- a/src/main/java/net/momirealms/customfishing/integration/block/ItemsAdderBlockImpl.java +++ b/src/main/java/net/momirealms/customfishing/integration/block/ItemsAdderBlockImpl.java @@ -18,8 +18,8 @@ package net.momirealms.customfishing.integration.block; import dev.lone.itemsadder.api.CustomBlock; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.integration.BlockInterface; -import net.momirealms.customfishing.manager.TotemManager; import net.momirealms.customfishing.util.AdventureUtil; import org.bukkit.Location; import org.bukkit.Material; @@ -40,9 +40,9 @@ public class ItemsAdderBlockImpl implements BlockInterface { @Override public void placeBlock(String id, Location location) { - String blockID = TotemManager.INVERTED.get(id); + String blockID = CustomFishing.getInstance().getTotemManager().getInvertedBlock(id); if (blockID == null) { - AdventureUtil.consoleMessage(id + " does not exist in totem-blocks.yml"); + AdventureUtil.consoleMessage(id + " does not exist in default.yml"); return; } if (BlockInterface.isVanillaItem(blockID)) { @@ -64,6 +64,6 @@ public class ItemsAdderBlockImpl implements BlockInterface { else { id = customBlock.getNamespacedID(); } - return TotemManager.BLOCKS.get(id); + return CustomFishing.getInstance().getTotemManager().getBlockID(id); } } \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/integration/block/OraxenBlockImpl.java b/src/main/java/net/momirealms/customfishing/integration/block/OraxenBlockImpl.java index f73bd9e5..2155694b 100644 --- a/src/main/java/net/momirealms/customfishing/integration/block/OraxenBlockImpl.java +++ b/src/main/java/net/momirealms/customfishing/integration/block/OraxenBlockImpl.java @@ -20,8 +20,8 @@ package net.momirealms.customfishing.integration.block; import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanic; import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanicFactory; import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanicListener; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.integration.BlockInterface; -import net.momirealms.customfishing.manager.TotemManager; import net.momirealms.customfishing.util.AdventureUtil; import org.bukkit.Location; import org.bukkit.Material; @@ -37,9 +37,9 @@ public class OraxenBlockImpl implements BlockInterface { @Override public void placeBlock(String id, Location location) { - String blockID = TotemManager.INVERTED.get(id); + String blockID = CustomFishing.getInstance().getTotemManager().getInvertedBlock(id); if (blockID == null) { - AdventureUtil.consoleMessage(id + " does not exist in totem-blocks.yml"); + AdventureUtil.consoleMessage(id + " does not exist in default.yml"); return; } if (BlockInterface.isVanillaItem(blockID)) { @@ -66,6 +66,6 @@ public class OraxenBlockImpl implements BlockInterface { else { id = mechanic.getItemID(); } - return TotemManager.BLOCKS.get(id); + return CustomFishing.getInstance().getTotemManager().getBlockID(id); } } diff --git a/src/main/java/net/momirealms/customfishing/integration/block/VanillaBlockImpl.java b/src/main/java/net/momirealms/customfishing/integration/block/VanillaBlockImpl.java index ca26b8ab..fa16959b 100644 --- a/src/main/java/net/momirealms/customfishing/integration/block/VanillaBlockImpl.java +++ b/src/main/java/net/momirealms/customfishing/integration/block/VanillaBlockImpl.java @@ -17,8 +17,8 @@ package net.momirealms.customfishing.integration.block; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.integration.BlockInterface; -import net.momirealms.customfishing.manager.TotemManager; import net.momirealms.customfishing.util.AdventureUtil; import org.bukkit.Location; import org.bukkit.Material; @@ -33,9 +33,9 @@ public class VanillaBlockImpl implements BlockInterface { @Override public void placeBlock(String id, Location location) { - String blockID = TotemManager.INVERTED.get(id); + String blockID = CustomFishing.getInstance().getTotemManager().getInvertedBlock(id); if (blockID == null) { - AdventureUtil.consoleMessage(id + " does not exist in totem-blocks.yml"); + AdventureUtil.consoleMessage(id + " does not exist in default.yml"); return; } BlockInterface.placeVanillaBlock(blockID, location); @@ -44,7 +44,7 @@ public class VanillaBlockImpl implements BlockInterface { @Nullable @Override public String getID(Block block) { - return TotemManager.BLOCKS.get(block.getType().name()); + return CustomFishing.getInstance().getTotemManager().getBlockID(block.getType().name()); } @Override diff --git a/src/main/java/net/momirealms/customfishing/integration/item/CustomFishingItemImpl.java b/src/main/java/net/momirealms/customfishing/integration/item/CustomFishingItemImpl.java index c5b30f1f..206be8a4 100644 --- a/src/main/java/net/momirealms/customfishing/integration/item/CustomFishingItemImpl.java +++ b/src/main/java/net/momirealms/customfishing/integration/item/CustomFishingItemImpl.java @@ -17,8 +17,8 @@ package net.momirealms.customfishing.integration.item; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.integration.ItemInterface; -import net.momirealms.customfishing.manager.LootManager; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -27,11 +27,17 @@ import org.jetbrains.annotations.Nullable; public class CustomFishingItemImpl implements ItemInterface { + private final CustomFishing plugin; + + public CustomFishingItemImpl(CustomFishing plugin) { + this.plugin = plugin; + } + @Override @Nullable public ItemStack build(String material) { if (material.contains(":")) return null; - return LootManager.build(material); + return plugin.getLootManager().build(material); } @Override diff --git a/src/main/java/net/momirealms/customfishing/integration/item/EcoItemRegister.java b/src/main/java/net/momirealms/customfishing/integration/item/EcoItemRegister.java index 732fe73d..1b392d81 100644 --- a/src/main/java/net/momirealms/customfishing/integration/item/EcoItemRegister.java +++ b/src/main/java/net/momirealms/customfishing/integration/item/EcoItemRegister.java @@ -21,7 +21,6 @@ import com.willfp.eco.core.items.CustomItem; import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTItem; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.manager.BonusManager; import org.bukkit.NamespacedKey; import org.bukkit.inventory.ItemStack; @@ -31,9 +30,9 @@ public class EcoItemRegister { public static void registerItems() { // Rods - for (Map.Entry entry : BonusManager.RODITEMS.entrySet()) { + for (Map.Entry entry : CustomFishing.getInstance().getEffectManager().getRodItems().entrySet()) { new CustomItem( - new NamespacedKey(CustomFishing.plugin, "rod_" + entry.getKey()), + new NamespacedKey(CustomFishing.getInstance(), "rod_" + entry.getKey()), itemStack -> { try { NBTItem nbtItem = new NBTItem(itemStack); @@ -49,9 +48,9 @@ public class EcoItemRegister { ).register(); } // Baits - for (Map.Entry entry : BonusManager.BAITITEMS.entrySet()) { + for (Map.Entry entry : CustomFishing.getInstance().getEffectManager().getBaitItems().entrySet()) { new CustomItem( - new NamespacedKey(CustomFishing.plugin, "bait_" + entry.getKey()), + new NamespacedKey(CustomFishing.getInstance(), "bait_" + entry.getKey()), itemStack -> { try { NBTItem nbtItem = new NBTItem(itemStack); @@ -67,9 +66,9 @@ public class EcoItemRegister { ).register(); } // Utils - for (Map.Entry entry : BonusManager.UTILITEMS.entrySet()) { + for (Map.Entry entry : CustomFishing.getInstance().getEffectManager().getUtilItems().entrySet()) { new CustomItem( - new NamespacedKey(CustomFishing.plugin, "util_" + entry.getKey()), + new NamespacedKey(CustomFishing.getInstance(), "util_" + entry.getKey()), itemStack -> { try { NBTItem nbtItem = new NBTItem(itemStack); diff --git a/src/main/java/net/momirealms/customfishing/integration/mob/MythicMobsMobImpl.java b/src/main/java/net/momirealms/customfishing/integration/mob/MythicMobsMobImpl.java index c6bf633b..b6cf49f5 100644 --- a/src/main/java/net/momirealms/customfishing/integration/mob/MythicMobsMobImpl.java +++ b/src/main/java/net/momirealms/customfishing/integration/mob/MythicMobsMobImpl.java @@ -24,9 +24,9 @@ import io.lumine.mythic.api.mobs.MythicMob; import io.lumine.mythic.bukkit.MythicBukkit; import io.lumine.mythic.bukkit.utils.serialize.Position; import io.lumine.mythic.core.mobs.ActiveMob; +import net.momirealms.customfishing.fishing.loot.Mob; +import net.momirealms.customfishing.fishing.loot.MobVector; import net.momirealms.customfishing.integration.MobInterface; -import net.momirealms.customfishing.object.loot.Mob; -import net.momirealms.customfishing.object.loot.MobVector; import org.bukkit.Location; import org.bukkit.util.Vector; diff --git a/src/main/java/net/momirealms/customfishing/integration/papi/CompetitionPapi.java b/src/main/java/net/momirealms/customfishing/integration/papi/CompetitionPapi.java index bb01be80..c8df6354 100644 --- a/src/main/java/net/momirealms/customfishing/integration/papi/CompetitionPapi.java +++ b/src/main/java/net/momirealms/customfishing/integration/papi/CompetitionPapi.java @@ -18,8 +18,8 @@ package net.momirealms.customfishing.integration.papi; import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import net.momirealms.customfishing.competition.Competition; -import net.momirealms.customfishing.competition.ranking.RankingInterface; +import net.momirealms.customfishing.fishing.competition.Competition; +import net.momirealms.customfishing.fishing.competition.ranking.RankingInterface; import net.momirealms.customfishing.manager.MessageManager; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/net/momirealms/customfishing/integration/papi/PlaceholderManager.java b/src/main/java/net/momirealms/customfishing/integration/papi/PlaceholderManager.java index 57e821c5..742e8e74 100644 --- a/src/main/java/net/momirealms/customfishing/integration/papi/PlaceholderManager.java +++ b/src/main/java/net/momirealms/customfishing/integration/papi/PlaceholderManager.java @@ -38,7 +38,6 @@ public class PlaceholderManager extends Function { hasPlaceholderAPI = true; this.competitionPapi = new CompetitionPapi(); } - load(); } public String parse(Player player, String text) { diff --git a/src/main/java/net/momirealms/customfishing/integration/quest/BattlePassCFQuest.java b/src/main/java/net/momirealms/customfishing/integration/quest/BattlePassCFQuest.java index 540bea3a..d4211bce 100644 --- a/src/main/java/net/momirealms/customfishing/integration/quest/BattlePassCFQuest.java +++ b/src/main/java/net/momirealms/customfishing/integration/quest/BattlePassCFQuest.java @@ -21,7 +21,7 @@ import io.github.battlepass.BattlePlugin; import io.github.battlepass.quests.quests.external.executor.ExternalQuestExecutor; import io.github.battlepass.registry.quest.QuestRegistry; import net.momirealms.customfishing.api.event.FishResultEvent; -import net.momirealms.customfishing.object.fishing.FishResult; +import net.momirealms.customfishing.fishing.FishResult; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -41,7 +41,7 @@ public class BattlePassCFQuest extends ExternalQuestExecutor implements Listener public void onFishCaught(FishResultEvent event) { if (event.isCancelled()) return; Player player = event.getPlayer(); - if (event.getResult() == FishResult.CAUGHT_LOOT || event.getResult() == FishResult.CAUGHT_VANILLA || event.getResult() == FishResult.CAUGHT_MOB) { + if (event.getResult() == FishResult.CATCH_SPECIAL_ITEM || event.getResult() == FishResult.CATCH_VANILLA_ITEM || event.getResult() == FishResult.CATCH_MOB) { this.execute("fish", player, (var1x) -> var1x.root(event.getLoot_id())); } } diff --git a/src/main/java/net/momirealms/customfishing/integration/quest/ClueScrollCFQuest.java b/src/main/java/net/momirealms/customfishing/integration/quest/ClueScrollCFQuest.java index 3d8f4db4..b4eeba77 100644 --- a/src/main/java/net/momirealms/customfishing/integration/quest/ClueScrollCFQuest.java +++ b/src/main/java/net/momirealms/customfishing/integration/quest/ClueScrollCFQuest.java @@ -21,7 +21,7 @@ import com.electro2560.dev.cluescrolls.api.ClueScrollsAPI; import com.electro2560.dev.cluescrolls.api.CustomClue; import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.api.event.FishResultEvent; -import net.momirealms.customfishing.object.fishing.FishResult; +import net.momirealms.customfishing.fishing.FishResult; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -32,19 +32,19 @@ public class ClueScrollCFQuest implements Listener { private final CustomClue commonClue; public ClueScrollCFQuest() { - commonClue = ClueScrollsAPI.getInstance().registerCustomClue(CustomFishing.plugin, "fish"); - fishClue = ClueScrollsAPI.getInstance().registerCustomClue(CustomFishing.plugin, "catch_fish"); - mobClue = ClueScrollsAPI.getInstance().registerCustomClue(CustomFishing.plugin, "catch_mob"); + commonClue = ClueScrollsAPI.getInstance().registerCustomClue(CustomFishing.getInstance(), "fish"); + fishClue = ClueScrollsAPI.getInstance().registerCustomClue(CustomFishing.getInstance(), "catch_fish"); + mobClue = ClueScrollsAPI.getInstance().registerCustomClue(CustomFishing.getInstance(), "catch_mob"); } @EventHandler public void onFish(FishResultEvent event) { if (event.isCancelled()) return; - if (event.getResult() == FishResult.CAUGHT_LOOT || event.getResult() == FishResult.CAUGHT_VANILLA) { + if (event.getResult() == FishResult.CATCH_SPECIAL_ITEM || event.getResult() == FishResult.CATCH_VANILLA_ITEM) { fishClue.handle(event.getPlayer(), 1); commonClue.handle(event.getPlayer(), 1); } - if (event.getResult() == FishResult.CAUGHT_MOB) { + if (event.getResult() == FishResult.CATCH_MOB) { mobClue.handle(event.getPlayer(), 1); commonClue.handle(event.getPlayer(), 1); } diff --git a/src/main/java/net/momirealms/customfishing/integration/quest/NewBetonQuestCFQuest.java b/src/main/java/net/momirealms/customfishing/integration/quest/NewBetonQuestCFQuest.java index f03e448e..a69e1520 100644 --- a/src/main/java/net/momirealms/customfishing/integration/quest/NewBetonQuestCFQuest.java +++ b/src/main/java/net/momirealms/customfishing/integration/quest/NewBetonQuestCFQuest.java @@ -18,7 +18,7 @@ package net.momirealms.customfishing.integration.quest; import net.momirealms.customfishing.api.event.FishResultEvent; -import net.momirealms.customfishing.object.fishing.FishResult; +import net.momirealms.customfishing.fishing.FishResult; import net.momirealms.customfishing.util.AdventureUtil; import org.betonquest.betonquest.BetonQuest; import org.betonquest.betonquest.Instruction; diff --git a/src/main/java/net/momirealms/customfishing/integration/quest/OldBetonQuestCFQuest.java b/src/main/java/net/momirealms/customfishing/integration/quest/OldBetonQuestCFQuest.java index 8cf0873e..d8884788 100644 --- a/src/main/java/net/momirealms/customfishing/integration/quest/OldBetonQuestCFQuest.java +++ b/src/main/java/net/momirealms/customfishing/integration/quest/OldBetonQuestCFQuest.java @@ -18,7 +18,7 @@ package net.momirealms.customfishing.integration.quest; import net.momirealms.customfishing.api.event.FishResultEvent; -import net.momirealms.customfishing.object.fishing.FishResult; +import net.momirealms.customfishing.fishing.FishResult; import net.momirealms.customfishing.util.AdventureUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -135,7 +135,7 @@ public class OldBetonQuestCFQuest extends Objective implements Listener { this.amount = Integer.parseInt(instruction); } catch (NumberFormatException e) { - AdventureUtil.consoleMessage("<>"); + AdventureUtil.consoleMessage("[CustomFishing] NumberFormatException"); this.amount = 1; } } diff --git a/src/main/java/net/momirealms/customfishing/integration/skill/MMOCoreImpl.java b/src/main/java/net/momirealms/customfishing/integration/skill/MMOCoreImpl.java index 3e7dfaf4..a5f11d80 100644 --- a/src/main/java/net/momirealms/customfishing/integration/skill/MMOCoreImpl.java +++ b/src/main/java/net/momirealms/customfishing/integration/skill/MMOCoreImpl.java @@ -36,7 +36,9 @@ public class MMOCoreImpl implements SkillInterface { @Override public void addXp(Player player, double amount) { - profession.giveExperience(playerDataManager.get(player), amount, null ,EXPSource.OTHER); + if (profession != null) { + profession.giveExperience(playerDataManager.get(player), amount, null ,EXPSource.OTHER); + } } @Override diff --git a/src/main/java/net/momirealms/customfishing/object/fishing/Difficulty.java b/src/main/java/net/momirealms/customfishing/listener/ConsumeItemListener.java similarity index 55% rename from src/main/java/net/momirealms/customfishing/object/fishing/Difficulty.java rename to src/main/java/net/momirealms/customfishing/listener/ConsumeItemListener.java index fbe84b46..dc33f33d 100644 --- a/src/main/java/net/momirealms/customfishing/object/fishing/Difficulty.java +++ b/src/main/java/net/momirealms/customfishing/listener/ConsumeItemListener.java @@ -15,17 +15,24 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.fishing; +package net.momirealms.customfishing.listener; -public record Difficulty(int timer, int speed) { +import net.momirealms.customfishing.object.Function; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerItemConsumeEvent; - @Override - public int timer() { - return timer; +public class ConsumeItemListener implements Listener { + + private final Function function; + + public ConsumeItemListener(Function function) { + this.function = function; } - @Override - public int speed() { - return speed; + @EventHandler + public void onConsumeItem(PlayerItemConsumeEvent event) { + if (event.isCancelled()) return; + function.onConsumeItem(event); } } diff --git a/src/main/java/net/momirealms/customfishing/listener/SimpleListener.java b/src/main/java/net/momirealms/customfishing/listener/JoinQuitListener.java similarity index 94% rename from src/main/java/net/momirealms/customfishing/listener/SimpleListener.java rename to src/main/java/net/momirealms/customfishing/listener/JoinQuitListener.java index 7c9817dd..948faeb3 100644 --- a/src/main/java/net/momirealms/customfishing/listener/SimpleListener.java +++ b/src/main/java/net/momirealms/customfishing/listener/JoinQuitListener.java @@ -23,7 +23,7 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; -public record SimpleListener(Function function) implements Listener { +public record JoinQuitListener(Function function) implements Listener { @EventHandler public void onJoin(PlayerJoinEvent event) { diff --git a/src/main/java/net/momirealms/customfishing/listener/PlayerFishListener.java b/src/main/java/net/momirealms/customfishing/listener/PlayerFishListener.java index fac23d30..0fdf929a 100644 --- a/src/main/java/net/momirealms/customfishing/listener/PlayerFishListener.java +++ b/src/main/java/net/momirealms/customfishing/listener/PlayerFishListener.java @@ -65,7 +65,7 @@ public record PlayerFishListener( public void selectState(PlayerFishEvent event) { if (event.isCancelled()) return; - if (!ConfigManager.getWorldsList().contains(event.getHook().getLocation().getWorld())) return; + if (!ConfigManager.getWorldsList().contains(event.getHook().getLocation().getWorld().getName())) return; switch (event.getState()) { case FISHING -> manager.onFishing(event); case REEL_IN -> manager.onReelIn(event); diff --git a/src/main/java/net/momirealms/customfishing/listener/WindowPacketListener.java b/src/main/java/net/momirealms/customfishing/listener/WindowPacketListener.java index 1fab0c59..a8469a8a 100644 --- a/src/main/java/net/momirealms/customfishing/listener/WindowPacketListener.java +++ b/src/main/java/net/momirealms/customfishing/listener/WindowPacketListener.java @@ -28,7 +28,7 @@ public class WindowPacketListener extends PacketAdapter { private final Function function; public WindowPacketListener(Function function) { - super(CustomFishing.plugin, PacketType.Play.Server.OPEN_WINDOW); + super(CustomFishing.getInstance(), PacketType.Play.Server.OPEN_WINDOW); this.function = function; } diff --git a/src/main/java/net/momirealms/customfishing/manager/BagDataManager.java b/src/main/java/net/momirealms/customfishing/manager/BagDataManager.java index 6a0f93ce..2e41cc99 100644 --- a/src/main/java/net/momirealms/customfishing/manager/BagDataManager.java +++ b/src/main/java/net/momirealms/customfishing/manager/BagDataManager.java @@ -20,13 +20,14 @@ package net.momirealms.customfishing.manager; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.reflect.StructureModifier; import com.comphenix.protocol.wrappers.WrappedChatComponent; +import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTItem; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.data.PlayerBagData; import net.momirealms.customfishing.listener.InventoryListener; -import net.momirealms.customfishing.listener.SimpleListener; +import net.momirealms.customfishing.listener.JoinQuitListener; import net.momirealms.customfishing.listener.WindowPacketListener; import net.momirealms.customfishing.object.Function; import net.momirealms.customfishing.util.AdventureUtil; @@ -47,68 +48,74 @@ import java.util.concurrent.ConcurrentHashMap; public class BagDataManager extends Function { - public static ConcurrentHashMap dataCache; - public static HashSet tempCache; + private final ConcurrentHashMap dataMap; + private final HashSet tempData; private final InventoryListener inventoryListener; private final WindowPacketListener windowPacketListener; - private final SimpleListener simpleListener; + private final JoinQuitListener joinQuitListener; private final BukkitTask timerSave; + private final CustomFishing plugin; - public BagDataManager() { - dataCache = new ConcurrentHashMap<>(); - tempCache = new HashSet<>(); + public BagDataManager(CustomFishing plugin) { + this.plugin = plugin; + this.dataMap = new ConcurrentHashMap<>(); + this.tempData = new HashSet<>(); this.inventoryListener = new InventoryListener(this); this.windowPacketListener = new WindowPacketListener(this); - this.simpleListener = new SimpleListener(this); + this.joinQuitListener = new JoinQuitListener(this); - this.timerSave = Bukkit.getScheduler().runTaskTimerAsynchronously(CustomFishing.plugin, () -> { - DataManager dataManager = CustomFishing.plugin.getDataManager(); - for (PlayerBagData playerBagData : dataCache.values()) { + this.timerSave = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, () -> { + DataManager dataManager = plugin.getDataManager(); + for (PlayerBagData playerBagData : dataMap.values()) { dataManager.getDataStorageInterface().saveBagData(playerBagData); } - AdventureUtil.consoleMessage("[CustomFishing] Fishing bag data saving for " + dataCache.size() + " online players..."); + AdventureUtil.consoleMessage("[CustomFishing] Fishing bag data saving for " + dataMap.size() + " online players..."); }, 12000, 12000); } @Override public void load() { if (!ConfigManager.enableFishingBag) return; - Bukkit.getPluginManager().registerEvents(inventoryListener, CustomFishing.plugin); - Bukkit.getPluginManager().registerEvents(simpleListener, CustomFishing.plugin); - CustomFishing.protocolManager.addPacketListener(windowPacketListener); + Bukkit.getPluginManager().registerEvents(inventoryListener, plugin); + Bukkit.getPluginManager().registerEvents(joinQuitListener, plugin); + CustomFishing.getProtocolManager().addPacketListener(windowPacketListener); } @Override public void unload() { HandlerList.unregisterAll(inventoryListener); - HandlerList.unregisterAll(simpleListener); - CustomFishing.protocolManager.removePacketListener(windowPacketListener); + HandlerList.unregisterAll(joinQuitListener); + CustomFishing.getProtocolManager().removePacketListener(windowPacketListener); } public void disable() { - for (PlayerBagData playerBagData : dataCache.values()) { - DataManager dataManager = CustomFishing.plugin.getDataManager(); + unload(); + for (PlayerBagData playerBagData : dataMap.values()) { + DataManager dataManager = CustomFishing.getInstance().getDataManager(); dataManager.getDataStorageInterface().saveBagData(playerBagData); } - dataCache.clear(); - tempCache.clear(); + dataMap.clear(); + tempData.clear(); timerSave.cancel(); } + public PlayerBagData getPlayerBagData(UUID uuid) { + return dataMap.get(uuid); + } + public void openFishingBag(Player viewer, OfflinePlayer ownerOffline) { Player owner = ownerOffline.getPlayer(); if (owner == null) { - Inventory inventory = CustomFishing.plugin.getDataManager().getDataStorageInterface().loadBagData(ownerOffline); + Inventory inventory = plugin.getDataManager().getDataStorageInterface().loadBagData(ownerOffline); PlayerBagData playerBagData = new PlayerBagData(ownerOffline, inventory); - tempCache.add(playerBagData); + tempData.add(playerBagData); viewer.openInventory(inventory); } else { - PlayerBagData playerBagData = dataCache.get(owner.getUniqueId()); + PlayerBagData playerBagData = dataMap.get(owner.getUniqueId()); if (playerBagData == null) { AdventureUtil.consoleMessage("[CustomFishing] Bag data is not loaded for player " + owner.getName()); - return; } else { tryOpen(owner, viewer, playerBagData); @@ -118,27 +125,27 @@ public class BagDataManager extends Function { @Override public void onQuit(Player player) { - PlayerBagData playerBagData = dataCache.remove(player.getUniqueId()); + PlayerBagData playerBagData = dataMap.remove(player.getUniqueId()); if (playerBagData != null) { - Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.plugin, () -> { - CustomFishing.plugin.getDataManager().getDataStorageInterface().saveBagData(playerBagData); + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + plugin.getDataManager().getDataStorageInterface().saveBagData(playerBagData); }); } } @Override public void onJoin(Player player) { - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.plugin, () -> { + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { readData(player); }, 20); } public void readData(Player player) { if (player == null || !player.isOnline()) return; - Inventory inventory = CustomFishing.plugin.getDataManager().getDataStorageInterface().loadBagData(player); + Inventory inventory = plugin.getDataManager().getDataStorageInterface().loadBagData(player); if (inventory != null) { PlayerBagData playerBagData = new PlayerBagData(player, inventory); - dataCache.put(player.getUniqueId(), playerBagData); + dataMap.put(player.getUniqueId(), playerBagData); } } @@ -165,13 +172,23 @@ public class BagDataManager extends Function { @Override public void onClickInventory(InventoryClickEvent event) { final Player player = (Player) event.getWhoClicked(); - PlayerBagData playerBagData = dataCache.get(player.getUniqueId()); + PlayerBagData playerBagData = dataMap.get(player.getUniqueId()); if (playerBagData == null) return; if (playerBagData.getInventory() == event.getInventory()) { ItemStack currentItem = event.getCurrentItem(); if (currentItem == null || currentItem.getType() == Material.AIR) return; NBTItem nbtItem = new NBTItem(currentItem); - if (!nbtItem.hasKey("CustomFishing") && !ConfigManager.bagWhiteListItems.contains(currentItem.getType())) { + if (!nbtItem.hasTag("CustomFishing") && !ConfigManager.bagWhiteListItems.contains(currentItem.getType())) { + event.setCancelled(true); + return; + } + NBTCompound nbtCompound = nbtItem.getCompound("CustomFishing"); + if (nbtCompound == null) { + event.setCancelled(true); + return; + } + String type = nbtCompound.getString("type"); + if (!ConfigManager.canStoreLoot && type.equals("loot")) { event.setCancelled(true); } } @@ -181,23 +198,23 @@ public class BagDataManager extends Function { public void onCloseInventory(InventoryCloseEvent event) { final Player player = (Player) event.getPlayer(); Inventory inventory = event.getInventory(); - PlayerBagData playerBagData = dataCache.get(player.getUniqueId()); + PlayerBagData playerBagData = dataMap.get(player.getUniqueId()); if (playerBagData != null) { if (inventory == playerBagData.getInventory()) { for (ItemStack itemStack : event.getInventory().getContents()) { if (itemStack == null || itemStack.getType() == Material.AIR) continue; NBTItem nbtItem = new NBTItem(itemStack); - if (nbtItem.hasKey("CustomFishing") || ConfigManager.bagWhiteListItems.contains(itemStack.getType())) continue; + if (nbtItem.hasTag("CustomFishing") || ConfigManager.bagWhiteListItems.contains(itemStack.getType())) continue; player.getInventory().addItem(itemStack.clone()); itemStack.setAmount(0); } return; } - for (PlayerBagData temp : tempCache) { + for (PlayerBagData temp : tempData) { if (temp.getInventory() == inventory) { - tempCache.remove(temp); - Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.plugin, () -> { - CustomFishing.plugin.getDataManager().getDataStorageInterface().saveBagData(temp); + tempData.remove(temp); + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + plugin.getDataManager().getDataStorageInterface().saveBagData(temp); }); } } diff --git a/src/main/java/net/momirealms/customfishing/manager/BarMechanicManager.java b/src/main/java/net/momirealms/customfishing/manager/BarMechanicManager.java new file mode 100644 index 00000000..ba6bd670 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/BarMechanicManager.java @@ -0,0 +1,127 @@ +/* + * Copyright (C) <2022> + * + * 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 + * 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 net.momirealms.customfishing.manager; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.MiniGameConfig; +import net.momirealms.customfishing.fishing.bar.FishingBar; +import net.momirealms.customfishing.fishing.bar.ModeOneBar; +import net.momirealms.customfishing.fishing.bar.ModeTwoBar; +import net.momirealms.customfishing.object.Function; +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.util.*; + +public class BarMechanicManager extends Function { + + private final CustomFishing plugin; + private final HashMap bars; + private final HashMap miniGames; + + public BarMechanicManager(CustomFishing plugin) { + this.plugin = plugin; + this.bars = new HashMap<>(); + this.miniGames = new HashMap<>(); + } + + @Override + public void load() { + loadBars(); + loadGames(); + } + + @Override + public void unload() { + bars.clear(); + miniGames.clear(); + } + + private void loadGames() { + File game_file = new File(plugin.getDataFolder() + File.separator + "minigames"); + if (!game_file.exists()) { + if (!game_file.mkdir()) return; + plugin.saveResource("minigames" + File.separator + "default.yml", false); + } + File[] files = game_file.listFiles(); + if (files == null) return; + for (File file : files) { + if (!file.getName().endsWith(".yml")) continue; + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + for (String key : config.getKeys(false)) { + ConfigurationSection section = config.getConfigurationSection(key); + if (section == null) continue; + List fishingBarList = new ArrayList<>(); + for (String bar : section.getStringList("bars")) { + if (bars.containsKey(bar)) { + fishingBarList.add(bars.get(bar)); + } + else { + AdventureUtil.consoleMessage("[CustomFishing] Bar " + bar + " doesn't exist"); + } + } + MiniGameConfig miniGameConfig = new MiniGameConfig( + section.getInt("time", 10), + fishingBarList.toArray(new FishingBar[0]), + section.getIntegerList("difficulty").stream().mapToInt(Integer::intValue).toArray() + ); + miniGames.put(key, miniGameConfig); + } + } + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + miniGames.size() + " game(s)"); + } + + private void loadBars() { + File bar_file = new File(plugin.getDataFolder() + File.separator + "bars"); + if (!bar_file.exists()) { + if (!bar_file.mkdir()) return; + plugin.saveResource("bars" + File.separator + "default.yml", false); + } + File[] files = bar_file.listFiles(); + if (files == null) return; + for (File file : files) { + if (!file.getName().endsWith(".yml")) continue; + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + for (String key : config.getKeys(false)) { + ConfigurationSection section = config.getConfigurationSection(key); + if (section == null) continue; + int type = section.getInt("game-type"); + if (type == 1) { + ModeOneBar modeOneBar = new ModeOneBar(section); + bars.put(key, modeOneBar); + } + else if (type == 2) { + ModeTwoBar modeTwoBar = new ModeTwoBar(section); + bars.put(key, modeTwoBar); + } + } + } + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + bars.size() + " bar(s)"); + } + + public MiniGameConfig getGameConfig(String game) { + return miniGames.get(game); + } + + public MiniGameConfig getRandomGame() { + Collection miniGameConfigs = miniGames.values(); + return (MiniGameConfig) miniGameConfigs.toArray()[new Random().nextInt(miniGameConfigs.size())]; + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/BonusManager.java b/src/main/java/net/momirealms/customfishing/manager/BonusManager.java deleted file mode 100644 index 966d3241..00000000 --- a/src/main/java/net/momirealms/customfishing/manager/BonusManager.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.manager; - -import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.object.Function; -import net.momirealms.customfishing.object.fishing.Bonus; -import net.momirealms.customfishing.object.loot.Item; -import net.momirealms.customfishing.object.loot.LeveledEnchantment; -import net.momirealms.customfishing.util.AdventureUtil; -import net.momirealms.customfishing.util.ConfigUtil; -import net.momirealms.customfishing.util.ItemStackUtil; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; - -import java.io.File; -import java.util.*; - -public class BonusManager extends Function { - - public static HashMap BAITITEMS; - public static HashMap BAIT; - public static HashMap RODITEMS; - public static HashMap ROD; - public static HashMap ENCHANTS = new HashMap<>(); - public static HashMap UTILITEMS; - - @Override - public void load() { - BAIT = new HashMap<>(); - BAITITEMS = new HashMap<>(); - ROD = new HashMap<>(); - RODITEMS = new HashMap<>(); - ENCHANTS = new HashMap<>(); - loadRod(); - loadBait(); - loadEnchant(); - loadUtil(); - } - - @Override - public void unload() { - if (BAIT != null) BAIT.clear(); - if (BAITITEMS != null) BAITITEMS.clear(); - if (ROD != null) ROD.clear(); - if (RODITEMS != null) RODITEMS.clear(); - if (ENCHANTS != null) ENCHANTS.clear(); - } - - private void loadUtil() { - UTILITEMS = new HashMap<>(); - File util_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "utils"); - if (!util_file.exists()) { - if (!util_file.mkdir()) return; - CustomFishing.plugin.saveResource("utils" + File.separator + "fishfinder.yml", false); - CustomFishing.plugin.saveResource("utils" + File.separator + "totem_items.yml", false); - CustomFishing.plugin.saveResource("utils" + File.separator + "splash_items.yml", false); - } - File[] files = util_file.listFiles(); - if (files == null) return; - for (File file : files) { - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - Set keys = config.getKeys(false); - for (String key : keys) { - Item item = new Item(Material.valueOf(config.getString(key + ".material", "PAPER").toUpperCase()), key); - setItemProperties(config, key, item); - UTILITEMS.put(key, ItemStackUtil.addIdentifier(ItemStackUtil.getFromItem(item), "util", key)); - } - } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + UTILITEMS.size() + " utils"); - } - - private void loadEnchant() { - ENCHANTS = new HashMap<>(); - YamlConfiguration config = ConfigUtil.getConfig("enchant-bonus.yml"); - Set keys = config.getKeys(false); - for (String key : keys) { - config.getConfigurationSection(key).getKeys(false).forEach(level -> { - Bonus bonus = new Bonus(); - config.getConfigurationSection(key + "." + level).getKeys(false).forEach(modifier -> { - switch (modifier) { - case "weight-add" -> { - HashMap pm = new HashMap<>(); - config.getConfigurationSection(key + "." + level + ".weight-add").getValues(false).forEach((group, value) -> { - pm.put(group, (Integer) value); - }); - bonus.setWeightAS(pm); - } - case "weight-multiply" -> { - HashMap mq = new HashMap<>(); - config.getConfigurationSection(key + "." + level + ".weight-multiply").getValues(false).forEach((group, value) -> { - mq.put(group, Double.parseDouble(String.valueOf(value))-1); - }); - bonus.setWeightMD(mq); - } - case "time" -> bonus.setTime(config.getDouble(key + "." + level + ".time")); - case "difficulty" -> bonus.setDifficulty(config.getInt(key + "." + level + ".difficulty")); - case "double-loot" -> bonus.setDoubleLoot(config.getDouble(key + "." + level + ".double-loot")); - case "score" -> bonus.setScore(config.getDouble(key + "." + level + ".score")); - case "lava-fishing" -> bonus.setCanLavaFishing(config.getBoolean(key + "." + level + ".lava-fishing")); - } - }); - ENCHANTS.put(key + ":" + level, bonus); - }); - } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + keys.size() + " enchantments"); - } - - private void loadBait() { - BAITITEMS = new HashMap<>(); - BAIT = new HashMap<>(); - File bait_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "baits"); - if (!bait_file.exists()) { - if (!bait_file.mkdir()) return; - CustomFishing.plugin.saveResource("baits" + File.separator + "default.yml", false); - } - File[] files = bait_file.listFiles(); - if (files == null) return; - for (File file : files) { - if (!file.getName().endsWith(".yml")) continue; - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - Set keys = config.getKeys(false); - for (String key : keys) { - Item item = new Item(Material.valueOf(config.getString(key + ".material", "PAPER").toUpperCase()), key); - setItemProperties(config, key, item); - BAITITEMS.put(key, ItemStackUtil.addIdentifier(ItemStackUtil.getFromItem(item), "bait", key)); - if (config.contains(key + ".modifier")) { - BAIT.put(key, getBonus(config, key)); - } - } - } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + BAITITEMS.size() + " baits"); - } - - public static Bonus getBonus(YamlConfiguration config, String key) { - Bonus bonus = new Bonus(); - config.getConfigurationSection(key + ".modifier").getKeys(false).forEach(modifier -> { - switch (modifier) { - case "weight-add" -> { - HashMap as = new HashMap<>(); - config.getConfigurationSection(key + ".modifier.weight-add").getValues(false).forEach((group, value) -> { - as.put(group, (Integer) value); - }); - bonus.setWeightAS(as); - } - case "weight-multiply" -> { - HashMap md = new HashMap<>(); - config.getConfigurationSection(key + ".modifier.weight-multiply").getValues(false).forEach((group, value) -> { - md.put(group, Double.parseDouble(String.valueOf(value))-1); - }); - bonus.setWeightMD(md); - } - case "time" -> bonus.setTime(config.getDouble(key + ".modifier.time")); - case "difficulty" -> bonus.setDifficulty(config.getInt(key + ".modifier.difficulty")); - case "double-loot" -> bonus.setDoubleLoot(config.getDouble(key + ".modifier.double-loot")); - case "score" -> bonus.setScore(config.getDouble(key + ".modifier.score") - 1); - case "lava-fishing" -> bonus.setCanLavaFishing(config.getBoolean(key + ".modifier.lava-fishing", false)); - } - }); - return bonus; - } - - private void loadRod() { - ROD = new HashMap<>(); - RODITEMS = new HashMap<>(); - File rod_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "rods"); - if (!rod_file.exists()) { - if (!rod_file.mkdir()) return; - CustomFishing.plugin.saveResource("rods" + File.separator + "default.yml", false); - } - File[] files = rod_file.listFiles(); - if (files == null) return; - for (File file : files) { - if (!file.getName().endsWith(".yml")) continue; - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - Set keys = config.getKeys(false); - for (String key : keys) { - Item item = new Item(Material.FISHING_ROD, key); - setItemProperties(config, key, item); - RODITEMS.put(key, ItemStackUtil.addIdentifier(ItemStackUtil.getFromItem(item), "rod", key)); - if (config.contains(key + ".modifier")) { - ROD.put(key, getBonus(config, key)); - } - } - } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + RODITEMS.size() + " rods"); - } - - public static void setItemProperties(ConfigurationSection config, String key, Item item) { - item.setUnbreakable(config.getBoolean(key + ".unbreakable", false)); - if (config.contains(key + ".display.lore")) item.setLore(config.getStringList(key + ".display.lore")); - if (config.contains(key + ".display.name")) item.setName(config.getString(key + ".display.name")); - if (config.contains(key + ".custom-model-data")) item.setCustomModelData(config.getInt(key + ".custom-model-data")); - if (config.contains(key + ".enchantments")) { - List enchantmentList = new ArrayList<>(); - config.getConfigurationSection(key + ".enchantments").getKeys(false).forEach(enchant -> { - LeveledEnchantment leveledEnchantment = new LeveledEnchantment( - NamespacedKey.fromString(enchant), - config.getInt(key + ".enchantments." + enchant) - ); - enchantmentList.add(leveledEnchantment); - }); - item.setEnchantment(enchantmentList); - } - if (config.contains(key + ".item_flags")) { - ArrayList itemFlags = new ArrayList<>(); - config.getStringList(key + ".item_flags").forEach(flag -> itemFlags.add(ItemFlag.valueOf(flag))); - item.setItemFlags(itemFlags); - } - if (config.contains(key + ".nbt")) { - Map nbt = config.getConfigurationSection(key + ".nbt").getValues(false); - item.setNbt(nbt); - } - if (config.contains(key + ".head64")) { - item.setHead64(config.getString(key + ".head64")); - } - } -} diff --git a/src/main/java/net/momirealms/customfishing/manager/CompetitionManager.java b/src/main/java/net/momirealms/customfishing/manager/CompetitionManager.java index 37e3c7d2..2604f928 100644 --- a/src/main/java/net/momirealms/customfishing/manager/CompetitionManager.java +++ b/src/main/java/net/momirealms/customfishing/manager/CompetitionManager.java @@ -17,11 +17,12 @@ package net.momirealms.customfishing.manager; -import net.momirealms.customfishing.competition.CompetitionConfig; -import net.momirealms.customfishing.competition.CompetitionGoal; -import net.momirealms.customfishing.competition.CompetitionSchedule; -import net.momirealms.customfishing.competition.bossbar.BossBarConfig; -import net.momirealms.customfishing.competition.bossbar.BossBarOverlay; +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.competition.CompetitionConfig; +import net.momirealms.customfishing.fishing.competition.CompetitionGoal; +import net.momirealms.customfishing.fishing.competition.CompetitionSchedule; +import net.momirealms.customfishing.fishing.competition.bossbar.BossBarConfig; +import net.momirealms.customfishing.fishing.competition.bossbar.BossBarOverlay; import net.momirealms.customfishing.object.Function; import net.momirealms.customfishing.object.action.ActionInterface; import net.momirealms.customfishing.object.action.CommandActionImpl; @@ -29,21 +30,30 @@ import net.momirealms.customfishing.object.action.MessageActionImpl; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ConfigUtil; import org.bukkit.boss.BarColor; +import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; +import java.io.File; import java.util.*; public class CompetitionManager extends Function { - public static HashMap competitionsT; - public static HashMap competitionsC; + private CustomFishing plugin; + // Competitions that can be triggered at a specified time + private final HashMap competitionsT; + // Competitions that can be triggered with a command + private final HashMap competitionsC; private CompetitionSchedule competitionSchedule; + public CompetitionManager(CustomFishing plugin) { + this.plugin = plugin; + this.competitionsC = new HashMap<>(); + this.competitionsT = new HashMap<>(); + } + @Override public void load() { if (ConfigManager.enableCompetition) { - competitionsC = new HashMap<>(); - competitionsT = new HashMap<>(); loadCompetitions(); this.competitionSchedule = new CompetitionSchedule(); this.competitionSchedule.load(); @@ -52,13 +62,39 @@ public class CompetitionManager extends Function { @Override public void unload() { - if (competitionsC != null) competitionsC.clear(); - if (competitionsT != null) competitionsT.clear(); - if (competitionSchedule != null) competitionSchedule.unload(); + this.competitionsC.clear(); + this.competitionsT.clear(); + if (this.competitionSchedule != null) { + this.competitionSchedule.unload(); + } } - public void loadCompetitions() { - YamlConfiguration config = ConfigUtil.getConfig("competition.yml"); + private void loadCompetitions() { + File competition_file = new File(plugin.getDataFolder() + File.separator + "competitions"); + if (!competition_file.exists()) { + if (!competition_file.mkdir()) return; + plugin.saveResource("competitions" + File.separator + "default.yml", false); + } + File[] files = competition_file.listFiles(); + if (files == null) return; + int amount = 0; + for (File file : files) { + if (!file.getName().endsWith(".yml")) continue; + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + Set keys = config.getKeys(false); + for (String key : keys) { + ConfigurationSection section = config.getConfigurationSection(key); + if (section == null) continue; + + + amount++; + } + } + + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + amount + " competition(s)"); + + + YamlConfiguration config = ConfigUtil.getConfig("competitions/default.yml"); Set keys = config.getKeys(false); keys.forEach(key -> { boolean enableBsb = config.getBoolean(key + ".bossbar.enable", false); @@ -105,7 +141,7 @@ public class CompetitionManager extends Function { case "Thursday" -> days.add(5); case "Friday" -> days.add(6); case "Saturday" -> days.add(7); - default -> AdventureUtil.consoleMessage("unknown weekday: " + weekDay); + default -> AdventureUtil.consoleMessage("[CustomFishing] Unknown weekday: " + weekDay); } } competitionConfig.setWeekday(days); @@ -123,4 +159,12 @@ public class CompetitionManager extends Function { competitionsC.put(key, competitionConfig); }); } + + public HashMap getCompetitionsT() { + return competitionsT; + } + + public HashMap getCompetitionsC() { + return competitionsC; + } } diff --git a/src/main/java/net/momirealms/customfishing/manager/ConfigManager.java b/src/main/java/net/momirealms/customfishing/manager/ConfigManager.java index 3ba9edbf..4fc231e2 100644 --- a/src/main/java/net/momirealms/customfishing/manager/ConfigManager.java +++ b/src/main/java/net/momirealms/customfishing/manager/ConfigManager.java @@ -30,8 +30,7 @@ import java.util.List; public class ConfigManager { - public static World[] worlds; - public static List worldList; + public static List worldList; public static boolean whiteOrBlack; public static String priority; public static String lang; @@ -49,6 +48,7 @@ public class ConfigManager { public static boolean preventPickUp; public static boolean enableFishingBag; public static boolean alwaysFishingBar; + public static boolean allRodsFishInLava; public static String[] successTitle; public static String[] successSubTitle; public static int successFadeIn; @@ -60,6 +60,7 @@ public class ConfigManager { public static int failureFadeStay; public static int failureFadeOut; public static boolean useRedis; + public static boolean canStoreLoot; public static int lavaMaxTime; public static int lavaMinTime; public static boolean enableWaterAnimation; @@ -70,33 +71,31 @@ public class ConfigManager { public static int lava_time; public static boolean addTagToFish; public static boolean logEarning; - public static boolean vaultHook; public static boolean disableBar; public static boolean instantBar; public static String fishingBagTitle; + public static HashSet bagWhiteListItems; public static void load() { ConfigUtil.update("config.yml"); YamlConfiguration config = ConfigUtil.getConfig("config.yml"); - lang = config.getString("lang","english"); + loadMechanics(config); + loadTitle(config); + loadFishingWorlds(config); + loadOtherSettings(config); + } - whiteOrBlack = config.getString("worlds.mode","whitelist").equals("whitelist"); - List worldsName = config.getStringList("worlds.list"); - worlds = new World[worldsName.size()]; - for (int i = 0; i < worldsName.size(); i++) { - if (Bukkit.getWorld(worldsName.get(i)) != null) { - worlds[i] = Bukkit.getWorld(worldsName.get(i)); - } - } - worldList = new ArrayList<>(); - for (World world : worlds) { - if (world == null) continue; - worldList.add(world); - } - worlds = worldList.toArray(new World[0]); + private static void loadOtherSettings(YamlConfiguration config) { + priority = config.getString("other-settings.event-priority", "NORMAL").toUpperCase(); + disableJobsXp = config.getBoolean("other-settings.disable-JobsReborn-fishing-exp", false); + preventPickUp = config.getBoolean("other-settings.prevent-other-players-pick-up-loot", false); + convertMMOItems = config.getBoolean("other-settings.convert-MMOItems-rods", false); + logEarning = config.getBoolean("other-settings.log-earnings", true); + } + private static void loadMechanics(YamlConfiguration config) { disableBar = config.getBoolean("mechanics.disable-bar-mechanic", false); instantBar = config.getBoolean("mechanics.instant-bar", false); alwaysFishingBar = config.getBoolean("mechanics.other-loots.fishing-bar", true); @@ -109,64 +108,73 @@ public class ConfigManager { needRodForLoot = config.getBoolean("mechanics.need-special-rod-for-loots", false); rodLoseDurability = config.getBoolean("mechanics.rod-lose-durability", true); enableCompetition = config.getBoolean("mechanics.fishing-competition.enable", true); + enableWaterAnimation = config.getBoolean("mechanics.splash-animation.water.enable", false); + enableLavaAnimation = config.getBoolean("mechanics.splash-animation.lava.enable", false); + allRodsFishInLava = config.getBoolean("mechanics.all-rods-fish-in-lava", false); + water_item = config.getString("mechanics.splash-animation.water.item"); + lava_item = config.getString("mechanics.splash-animation.lava.item"); + water_time = config.getInt("mechanics.splash-animation.water.time"); + lava_time = config.getInt("mechanics.splash-animation.lava.time"); + lavaMinTime = config.getInt("mechanics.lava-fishing.min-wait-time", 100); + lavaMaxTime = config.getInt("mechanics.lava-fishing.max-wait-time", 600) - lavaMinTime; + enableFishingBag = config.getBoolean("mechanics.fishing-bag.enable", true); + canStoreLoot = config.getBoolean("mechanics.fishing-bag.can-store-loot", false); + addTagToFish = config.getBoolean("mechanics.add-custom-fishing-tags-to-loots", true); + fishingBagTitle = config.getString("mechanics.fishing-bag.bag-title", "Fishing Bag"); + bagWhiteListItems = new HashSet<>(); + for (String material : config.getStringList("mechanics.fishing-bag.whitelist-items")) bagWhiteListItems.add(Material.valueOf(material.toUpperCase())); + redisSettings(config); + } - priority = config.getString("other-settings.event-priority", "NORMAL").toUpperCase(); - disableJobsXp = config.getBoolean("other-settings.disable-JobsReborn-fishing-exp", false); - preventPickUp = config.getBoolean("other-settings.prevent-other-players-pick-up-loot", false); - convertMMOItems = config.getBoolean("other-settings.convert-MMOItems-rods", false); - logEarning = config.getBoolean("other-settings.log-earnings", true); - vaultHook = config.getBoolean("integration.Vault", true); - + private static void loadTitle(YamlConfiguration config) { successTitle = config.getStringList("titles.success.title").toArray(new String[0]); successSubTitle = config.getStringList("titles.success.subtitle").toArray(new String[0]); successFadeIn = config.getInt("titles.success.fade.in", 10) * 50; successFadeStay = config.getInt("titles.success.fade.stay", 30) * 50; successFadeOut = config.getInt("titles.success.fade.out", 10) * 50; - failureTitle = config.getStringList("titles.failure.title").toArray(new String[0]); failureSubTitle = config.getStringList("titles.failure.subtitle").toArray(new String[0]); failureFadeIn = config.getInt("titles.failure.fade.in", 10) * 50; failureFadeStay = config.getInt("titles.failure.fade.stay", 30) * 50; failureFadeOut = config.getInt("titles.failure.fade.out", 10) * 50; - if (successTitle.length == 0) successTitle = new String[]{""}; if (successSubTitle.length == 0) successSubTitle = new String[]{""}; if (failureTitle.length == 0) failureTitle = new String[]{""}; if (failureSubTitle.length == 0) failureSubTitle = new String[]{""}; - - enableWaterAnimation = config.getBoolean("mechanics.splash-animation.water.enable", false); - enableLavaAnimation = config.getBoolean("mechanics.splash-animation.lava.enable", false); - water_item = config.getString("mechanics.splash-animation.water.item"); - lava_item = config.getString("mechanics.splash-animation.lava.item"); - water_time = config.getInt("mechanics.splash-animation.water.time"); - lava_time = config.getInt("mechanics.splash-animation.lava.time"); - - lavaMinTime = config.getInt("mechanics.lava-fishing.min-wait-time", 100); - lavaMaxTime = config.getInt("mechanics.lava-fishing.max-wait-time", 600) - lavaMinTime; - - enableFishingBag = config.getBoolean("mechanics.fishing-bag.enable", true); - addTagToFish = config.getBoolean("mechanics.fishing-bag.can-store-loot", false); - fishingBagTitle = config.getString("mechanics.fishing-bag.bag-title", "Fishing Bag"); - bagWhiteListItems = new HashSet<>(); - for (String material : config.getStringList("mechanics.fishing-bag.whitelist-items")) { - bagWhiteListItems.add(Material.valueOf(material.toUpperCase())); - } - - useRedis = false; - if (enableCompetition && config.getBoolean("mechanics.fishing-competition.redis", false)) { - YamlConfiguration configuration = ConfigUtil.getConfig("database.yml"); - JedisUtil.initializeRedis(configuration); - useRedis = true; - } } - public static List getWorldsList() { + + private static void loadFishingWorlds(YamlConfiguration config) { + whiteOrBlack = config.getString("worlds.mode","whitelist").equals("whitelist"); + worldList = config.getStringList("worlds.list"); + } + + public static List getWorldsList() { if (whiteOrBlack) { return worldList; } else { - List worldList = new ArrayList<>(Bukkit.getWorlds()); + List worldList = new ArrayList<>(); + for (World world : Bukkit.getWorlds()) { + worldList.add(world.getName()); + } worldList.removeAll(ConfigManager.worldList); return worldList; } } + + private static void redisSettings(YamlConfiguration config) { + if (enableCompetition && config.getBoolean("mechanics.fishing-competition.redis", false)) { + if (!JedisUtil.isPoolEnabled()) { + YamlConfiguration configuration = ConfigUtil.getConfig("database.yml"); + JedisUtil.initializeRedis(configuration); + } + useRedis = true; + } + else { + if (JedisUtil.isPoolEnabled()) { + JedisUtil.closePool(); + } + useRedis = false; + } + } } diff --git a/src/main/java/net/momirealms/customfishing/manager/DataManager.java b/src/main/java/net/momirealms/customfishing/manager/DataManager.java index 491c3164..9a603b4f 100644 --- a/src/main/java/net/momirealms/customfishing/manager/DataManager.java +++ b/src/main/java/net/momirealms/customfishing/manager/DataManager.java @@ -17,6 +17,7 @@ package net.momirealms.customfishing.manager; +import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.data.storage.DataStorageInterface; import net.momirealms.customfishing.data.storage.FileStorageImpl; import net.momirealms.customfishing.data.storage.MySQLStorageImpl; @@ -27,13 +28,15 @@ import org.bukkit.configuration.file.YamlConfiguration; public class DataManager extends Function { private final DataStorageInterface dataStorageInterface; + private CustomFishing plugin; - public DataManager() { + public DataManager(CustomFishing plugin) { + this.plugin = plugin; YamlConfiguration config = ConfigUtil.getConfig("database.yml"); if (config.getString("data-storage-method","YAML").equalsIgnoreCase("YAML")) { - this.dataStorageInterface = new FileStorageImpl(); + this.dataStorageInterface = new FileStorageImpl(plugin); } else { - this.dataStorageInterface = new MySQLStorageImpl(); + this.dataStorageInterface = new MySQLStorageImpl(plugin); } load(); } diff --git a/src/main/java/net/momirealms/customfishing/manager/EffectManager.java b/src/main/java/net/momirealms/customfishing/manager/EffectManager.java new file mode 100644 index 00000000..27851646 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/EffectManager.java @@ -0,0 +1,250 @@ +/* + * Copyright (C) <2022> + * + * 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 + * 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 net.momirealms.customfishing.manager; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.Effect; +import net.momirealms.customfishing.fishing.loot.Item; +import net.momirealms.customfishing.object.Function; +import net.momirealms.customfishing.util.AdventureUtil; +import net.momirealms.customfishing.util.ItemStackUtil; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.util.HashMap; +import java.util.Objects; +import java.util.Set; + +public class EffectManager extends Function { + + private final CustomFishing plugin; + private final HashMap baitItems; + private final HashMap baitEffects; + private final HashMap rodItems; + private final HashMap rodEffects; + private final HashMap enchantEffects; + private final HashMap utilItems; + + public EffectManager(CustomFishing plugin) { + this.plugin = plugin; + this.baitEffects = new HashMap<>(); + this.baitItems = new HashMap<>(); + this.rodEffects = new HashMap<>(); + this.rodItems = new HashMap<>(); + this.utilItems = new HashMap<>(); + this.enchantEffects = new HashMap<>(); + } + + @Override + public void load() { + loadRod(); + loadBait(); + loadEnchant(); + loadUtil(); + } + + @Override + public void unload() { + this.baitEffects.clear(); + this.baitItems.clear(); + this.rodEffects.clear(); + this.rodItems.clear(); + this.enchantEffects.clear(); + } + + private void loadUtil() { + File util_file = new File(plugin.getDataFolder() + File.separator + "utils"); + if (!util_file.exists()) { + if (!util_file.mkdir()) return; + plugin.saveResource("utils" + File.separator + "fish_finder.yml", false); + plugin.saveResource("utils" + File.separator + "totem_items.yml", false); + plugin.saveResource("utils" + File.separator + "splash_items.yml", false); + } + File[] files = util_file.listFiles(); + if (files == null) return; + for (File file : files) { + if (!file.getName().endsWith(".yml")) continue; + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + Set keys = config.getKeys(false); + for (String key : keys) { + ConfigurationSection itemSection = config.getConfigurationSection(key); + if (itemSection == null) continue; + Item item = new Item(itemSection, key); + utilItems.put(key, ItemStackUtil.addIdentifier(ItemStackUtil.getFromItem(item), "util", key)); + } + } + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + utilItems.size() + " util(s)"); + } + + private void loadEnchant() { + File enchant_file = new File(plugin.getDataFolder() + File.separator + "enchants"); + if (!enchant_file.exists()) { + if (!enchant_file.mkdir()) return; + plugin.saveResource("enchants" + File.separator + "default.yml", false); + } + File[] files = enchant_file.listFiles(); + if (files == null) return; + int amount = 0; + for (File file : files) { + if (!file.getName().endsWith(".yml")) continue; + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + for (String key : config.getKeys(false)) { + ConfigurationSection levelSection = config.getConfigurationSection(key); + if (levelSection == null) continue; + for (String level : levelSection.getKeys(false)) { + enchantEffects.put(key + ":" + level, getEffect(levelSection.getConfigurationSection(key))); + } + amount++; + } + } + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + amount + " enchantment(s)"); + } + + private void loadBait() { + File bait_file = new File(plugin.getDataFolder() + File.separator + "baits"); + if (!bait_file.exists()) { + if (!bait_file.mkdir()) return; + plugin.saveResource("baits" + File.separator + "default.yml", false); + } + File[] files = bait_file.listFiles(); + if (files == null) return; + for (File file : files) { + if (!file.getName().endsWith(".yml")) continue; + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + Set keys = config.getKeys(false); + for (String key : keys) { + ConfigurationSection baitSection = config.getConfigurationSection(key); + if (baitSection == null) continue; + Item item = new Item(baitSection, key); + baitItems.put(key, ItemStackUtil.addIdentifier(ItemStackUtil.getFromItem(item), "bait", key)); + if (config.contains(key + ".effect")) { + baitEffects.put(key, getEffect(config.getConfigurationSection(key + ".effect"))); + } + } + } + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + baitItems.size() + " bait(s)"); + } + + private void loadRod() { + File rod_file = new File(plugin.getDataFolder() + File.separator + "rods"); + if (!rod_file.exists()) { + if (!rod_file.mkdir()) return; + plugin.saveResource("rods" + File.separator + "default.yml", false); + } + File[] files = rod_file.listFiles(); + if (files == null) return; + for (File file : files) { + if (!file.getName().endsWith(".yml")) continue; + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + Set keys = config.getKeys(false); + for (String key : keys) { + ConfigurationSection rodSection = config.getConfigurationSection(key); + if (rodSection == null) continue; + Item item = new Item(rodSection, key); + rodItems.put(key, ItemStackUtil.addIdentifier(ItemStackUtil.getFromItem(item), "rod", key)); + if (config.contains(key + ".effect")) { + rodEffects.put(key, getEffect(config.getConfigurationSection(key + ".effect"))); + } + } + } + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + rodItems.size() + " rod(s)"); + } + + public static Effect getEffect(ConfigurationSection section) { + Effect effect = new Effect(); + if (section == null) return effect; + for (String modifier : section.getKeys(false)) { + switch (modifier) { + case "weight-add" -> { + HashMap as = new HashMap<>(); + Objects.requireNonNull(section.getConfigurationSection(modifier)).getValues(false).forEach((group, value) -> as.put(group, (Integer) value)); + effect.setWeightAS(as); + } + case "weight-multiply" -> { + HashMap md = new HashMap<>(); + Objects.requireNonNull(section.getConfigurationSection(modifier)).getValues(false).forEach((group, value) -> md.put(group, Double.parseDouble(String.valueOf(value))-1)); + effect.setWeightMD(md); + } + case "time" -> effect.setTimeModifier(section.getDouble(modifier)); + case "difficulty" -> effect.setDifficulty(section.getInt(modifier)); + case "double-loot" -> effect.setDoubleLootChance(section.getDouble(modifier)); + case "score" -> effect.setScoreMultiplier(section.getDouble(modifier) - 1); + case "size-multiply" -> effect.setSizeMultiplier(section.getDouble(modifier) - 1); + case "lava-fishing" -> effect.setCanLavaFishing(section.getBoolean(modifier, false)); + } + } + return effect; + } + + @Nullable + public ItemStack getBaitItem(String key) { + return baitItems.get(key); + } + + public HashMap getBaitItems() { + return baitItems; + } + + @Nullable + public Effect getBaitEffect(String key) { + return baitEffects.get(key); + } + + public HashMap getBaitEffects() { + return baitEffects; + } + + @Nullable + public ItemStack getRodItem(String key) { + return rodItems.get(key); + } + + public HashMap getRodItems() { + return rodItems; + } + + @Nullable + public Effect getRodEffect(String key) { + return rodEffects.get(key); + } + + public HashMap getRodEffects() { + return rodEffects; + } + + @Nullable + public Effect getEnchantEffect(String key) { + return enchantEffects.get(key); + } + + public HashMap getEnchantEffects() { + return enchantEffects; + } + + @Nullable + public ItemStack getUtilItem(String key) { + return utilItems.get(key); + } + + public HashMap getUtilItems() { + return utilItems; + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/FishingManager.java b/src/main/java/net/momirealms/customfishing/manager/FishingManager.java index 8ae80245..9d9d9d73 100644 --- a/src/main/java/net/momirealms/customfishing/manager/FishingManager.java +++ b/src/main/java/net/momirealms/customfishing/manager/FishingManager.java @@ -26,23 +26,28 @@ import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.api.event.*; -import net.momirealms.customfishing.competition.Competition; -import net.momirealms.customfishing.competition.CompetitionGoal; import net.momirealms.customfishing.data.PlayerBagData; -import net.momirealms.customfishing.integration.AntiGriefInterface; +import net.momirealms.customfishing.fishing.*; +import net.momirealms.customfishing.fishing.bar.FishingBar; +import net.momirealms.customfishing.fishing.bar.ModeOneBar; +import net.momirealms.customfishing.fishing.bar.ModeTwoBar; +import net.momirealms.customfishing.fishing.competition.Competition; +import net.momirealms.customfishing.fishing.competition.CompetitionGoal; +import net.momirealms.customfishing.fishing.loot.DroppedItem; +import net.momirealms.customfishing.fishing.loot.Loot; +import net.momirealms.customfishing.fishing.loot.Mob; +import net.momirealms.customfishing.fishing.mode.FishingGame; +import net.momirealms.customfishing.fishing.mode.ModeOneGame; +import net.momirealms.customfishing.fishing.mode.ModeTwoGame; +import net.momirealms.customfishing.fishing.requirements.RequirementInterface; +import net.momirealms.customfishing.fishing.totem.ActivatedTotem; +import net.momirealms.customfishing.fishing.totem.TotemConfig; import net.momirealms.customfishing.integration.MobInterface; import net.momirealms.customfishing.integration.item.McMMOTreasure; import net.momirealms.customfishing.listener.*; import net.momirealms.customfishing.object.Function; import net.momirealms.customfishing.object.SimpleLocation; import net.momirealms.customfishing.object.action.ActionInterface; -import net.momirealms.customfishing.object.fishing.*; -import net.momirealms.customfishing.object.loot.DroppedItem; -import net.momirealms.customfishing.object.loot.Loot; -import net.momirealms.customfishing.object.loot.Mob; -import net.momirealms.customfishing.object.requirements.RequirementInterface; -import net.momirealms.customfishing.object.totem.ActivatedTotem; -import net.momirealms.customfishing.object.totem.TotemConfig; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.FakeItemUtil; import net.momirealms.customfishing.util.ItemStackUtil; @@ -59,6 +64,7 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.player.PlayerFishEvent; import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; @@ -73,54 +79,62 @@ import java.util.concurrent.ConcurrentHashMap; public class FishingManager extends Function { + private final CustomFishing plugin; private final PlayerFishListener playerFishListener; private final InteractListener interactListener; + private final ConsumeItemListener consumeItemListener; private PickUpListener pickUpListener; private MMOItemsListener mmoItemsListener; private JobsRebornXPListener jobsRebornXPListener; - private BreakBlockListener breakBlockListener; + private final JoinQuitListener joinQuitListener; + private final BreakBlockListener breakBlockListener; private final HashMap coolDown; - private final HashMap hooksCache; + private final HashMap hooks; private final HashMap nextLoot; - private final HashMap nextBonus; + private final HashMap nextEffect; private final HashMap vanillaLoot; - private final ConcurrentHashMap fishingPlayerCache; - private final ConcurrentHashMap totemCache; - private final ConcurrentHashMap breakDetectCache; - private final ConcurrentHashMap bobberTaskCache; + private final ConcurrentHashMap fishingPlayerMap; + private final ConcurrentHashMap activeTotemMap; + private final ConcurrentHashMap breakDetectionMap; + private final ConcurrentHashMap hookCheckTaskMap; - public FishingManager() { + public FishingManager(CustomFishing plugin) { + this.plugin = plugin; this.playerFishListener = new PlayerFishListener(this); this.interactListener = new InteractListener(this); this.breakBlockListener = new BreakBlockListener(this); + this.consumeItemListener = new ConsumeItemListener(this); + this.joinQuitListener = new JoinQuitListener(this); this.coolDown = new HashMap<>(); - this.hooksCache = new HashMap<>(); + this.hooks = new HashMap<>(); this.nextLoot = new HashMap<>(); - this.nextBonus = new HashMap<>(); + this.nextEffect = new HashMap<>(); this.vanillaLoot = new HashMap<>(); - this.fishingPlayerCache = new ConcurrentHashMap<>(); - this.totemCache = new ConcurrentHashMap<>(); - this.bobberTaskCache = new ConcurrentHashMap<>(); - this.breakDetectCache = new ConcurrentHashMap<>(); + this.fishingPlayerMap = new ConcurrentHashMap<>(); + this.activeTotemMap = new ConcurrentHashMap<>(); + this.hookCheckTaskMap = new ConcurrentHashMap<>(); + this.breakDetectionMap = new ConcurrentHashMap<>(); load(); } @Override public void load() { - Bukkit.getPluginManager().registerEvents(this.playerFishListener, CustomFishing.plugin); - Bukkit.getPluginManager().registerEvents(this.interactListener, CustomFishing.plugin); - Bukkit.getPluginManager().registerEvents(this.breakBlockListener, CustomFishing.plugin); + Bukkit.getPluginManager().registerEvents(this.playerFishListener, plugin); + Bukkit.getPluginManager().registerEvents(this.interactListener, plugin); + Bukkit.getPluginManager().registerEvents(this.breakBlockListener, plugin); + Bukkit.getPluginManager().registerEvents(this.consumeItemListener, plugin); + Bukkit.getPluginManager().registerEvents(this.joinQuitListener, plugin); if (ConfigManager.preventPickUp) { this.pickUpListener = new PickUpListener(); - Bukkit.getPluginManager().registerEvents(this.pickUpListener, CustomFishing.plugin); + Bukkit.getPluginManager().registerEvents(this.pickUpListener, plugin); } if (ConfigManager.convertMMOItems) { this.mmoItemsListener = new MMOItemsListener(this); - Bukkit.getPluginManager().registerEvents(this.mmoItemsListener, CustomFishing.plugin); + Bukkit.getPluginManager().registerEvents(this.mmoItemsListener, plugin); } if (ConfigManager.disableJobsXp) { this.jobsRebornXPListener = new JobsRebornXPListener(); - Bukkit.getPluginManager().registerEvents(this.jobsRebornXPListener, CustomFishing.plugin); + Bukkit.getPluginManager().registerEvents(this.jobsRebornXPListener, plugin); } } @@ -129,10 +143,12 @@ public class FishingManager extends Function { HandlerList.unregisterAll(this.playerFishListener); HandlerList.unregisterAll(this.interactListener); HandlerList.unregisterAll(this.breakBlockListener); + HandlerList.unregisterAll(this.consumeItemListener); + HandlerList.unregisterAll(this.joinQuitListener); if (this.pickUpListener != null) HandlerList.unregisterAll(this.pickUpListener); if (this.mmoItemsListener != null) HandlerList.unregisterAll(this.mmoItemsListener); if (this.jobsRebornXPListener != null) HandlerList.unregisterAll(this.jobsRebornXPListener); - for (BobberCheckTask bobberCheckTask : bobberTaskCache.values()) { + for (BobberCheckTask bobberCheckTask : hookCheckTaskMap.values()) { bobberCheckTask.stop(); } } @@ -142,10 +158,10 @@ public class FishingManager extends Function { final Player player = event.getPlayer(); final FishHook fishHook = event.getHook(); - hooksCache.put(player, fishHook); + hooks.put(player, fishHook); if (isCoolDown(player, 500)) return; - Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.plugin, () -> { + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { PlayerInventory inventory = player.getInventory(); @@ -155,36 +171,36 @@ public class FishingManager extends Function { int lureLevel = 0; ItemStack baitItem = null; - Bonus initialBonus = new Bonus(); - initialBonus.setDifficulty(0); - initialBonus.setDoubleLoot(0); - initialBonus.setTime(1); - initialBonus.setScore(0); - initialBonus.setWeightMD(new HashMap<>()); - initialBonus.setWeightAS(new HashMap<>()); + Effect initialEffect = new Effect(); + initialEffect.setDifficulty(0); + initialEffect.setDoubleLootChance(0); + initialEffect.setTimeModifier(1); + initialEffect.setScoreMultiplier(0); + initialEffect.setWeightMD(new HashMap<>()); + initialEffect.setWeightAS(new HashMap<>()); ItemStack mainHandItem = inventory.getItemInMainHand(); Material mainHandItemType = mainHandItem.getType(); if (mainHandItemType != Material.AIR) { if (mainHandItemType == Material.FISHING_ROD) { noRod = false; - enchantBonus(initialBonus, mainHandItem); + enchantBonus(initialEffect, mainHandItem); lureLevel = mainHandItem.getEnchantmentLevel(Enchantment.LURE); } NBTItem mainHandNBTItem = new NBTItem(mainHandItem); NBTCompound nbtCompound = mainHandNBTItem.getCompound("CustomFishing"); if (nbtCompound != null) { if (nbtCompound.getString("type").equals("rod")) { - Bonus rodBonus = BonusManager.ROD.get(nbtCompound.getString("id")); - if (rodBonus != null){ - initialBonus.addBonus(rodBonus); + Effect rodEffect = plugin.getEffectManager().getRodEffect(nbtCompound.getString("id")); + if (rodEffect != null){ + initialEffect.addEffect(rodEffect); noSpecialRod = false; } } else if (nbtCompound.getString("type").equals("bait")) { - Bonus baitBonus = BonusManager.BAIT.get(nbtCompound.getString("id")); - if (baitBonus != null) { - initialBonus.addBonus(baitBonus); + Effect baitEffect = plugin.getEffectManager().getBaitEffect(nbtCompound.getString("id")); + if (baitEffect != null) { + initialEffect.addEffect(baitEffect); baitItem = mainHandItem.clone(); mainHandItem.setAmount(mainHandItem.getAmount() - 1); noBait = false; @@ -197,40 +213,40 @@ public class FishingManager extends Function { Material offHandItemType = offHandItem.getType(); if (offHandItemType != Material.AIR){ if (noRod && offHandItemType == Material.FISHING_ROD) { - enchantBonus(initialBonus, offHandItem); + enchantBonus(initialEffect, offHandItem); lureLevel = offHandItem.getEnchantmentLevel(Enchantment.LURE); } NBTItem offHandNBTItem = new NBTItem(offHandItem); NBTCompound nbtCompound = offHandNBTItem.getCompound("CustomFishing"); if (nbtCompound != null) { if (noBait && nbtCompound.getString("type").equals("bait")) { - Bonus baitBonus = BonusManager.BAIT.get(nbtCompound.getString("id")); - if (baitBonus != null){ - initialBonus.addBonus(baitBonus); + Effect baitEffect = plugin.getEffectManager().getBaitEffect(nbtCompound.getString("id")); + if (baitEffect != null){ + initialEffect.addEffect(baitEffect); offHandItem.setAmount(offHandItem.getAmount() - 1); baitItem = offHandItem.clone(); noBait = false; } } else if (noSpecialRod && nbtCompound.getString("type").equals("rod")) { - Bonus rodBonus = BonusManager.ROD.get(nbtCompound.getString("id")); - if (rodBonus != null) { - initialBonus.addBonus(rodBonus); + Effect rodEffect = plugin.getEffectManager().getRodEffect(nbtCompound.getString("id")); + if (rodEffect != null) { + initialEffect.addEffect(rodEffect); noSpecialRod = false; } } } } - for (ActivatedTotem activatedTotem : totemCache.values()) { + for (ActivatedTotem activatedTotem : activeTotemMap.values()) { if (activatedTotem.getNearbyPlayerSet().contains(player)) { - initialBonus.addBonus(activatedTotem.getTotem().getBonus()); + initialEffect.addEffect(activatedTotem.getTotem().getBonus()); break; } } if (ConfigManager.enableFishingBag && noBait) { - PlayerBagData playerBagData = BagDataManager.dataCache.get(player.getUniqueId()); + PlayerBagData playerBagData = plugin.getBagDataManager().getPlayerBagData(player.getUniqueId()); if (playerBagData != null) { Inventory baitInv = playerBagData.getInventory(); for (int i = 0; i < baitInv.getSize(); i++) { @@ -240,9 +256,9 @@ public class FishingManager extends Function { NBTCompound cfCompound = nbtItem.getCompound("CustomFishing"); if (cfCompound == null) continue; if (!cfCompound.getString("type").equals("bait")) continue; - Bonus baitBonus = BonusManager.BAIT.get(cfCompound.getString("id")); - if (baitBonus != null) { - initialBonus.addBonus(baitBonus); + Effect baitEffect = plugin.getEffectManager().getBaitEffect(cfCompound.getString("id")); + if (baitEffect != null) { + initialEffect.addEffect(baitEffect); baitItem = itemStack.clone(); itemStack.setAmount(itemStack.getAmount() - 1); break; @@ -251,47 +267,47 @@ public class FishingManager extends Function { } } - RodCastEvent rodCastEvent = new RodCastEvent(player, initialBonus); + RodCastEvent rodCastEvent = new RodCastEvent(player, initialEffect); if (rodCastEvent.isCancelled()) { event.setCancelled(true); return; } - fishHook.setMaxWaitTime((int) (fishHook.getMaxWaitTime() * initialBonus.getTime())); - fishHook.setMinWaitTime((int) (fishHook.getMinWaitTime() * initialBonus.getTime())); + fishHook.setMaxWaitTime((int) (fishHook.getMaxWaitTime() * initialEffect.getTimeModifier())); + fishHook.setMinWaitTime((int) (fishHook.getMinWaitTime() * initialEffect.getTimeModifier())); - nextBonus.put(player, initialBonus); + nextEffect.put(player, initialEffect); if (ConfigManager.needRodToFish && noSpecialRod) { nextLoot.put(player, Loot.EMPTY); return; } - initialBonus.setHasSpecialRod(!noSpecialRod); + initialEffect.setHasSpecialRod(!noSpecialRod); int entityID = 0; if (baitItem != null) { baitItem.setAmount(1); - entityID = new Random().nextInt(100000000); - CustomFishing.protocolManager.sendServerPacket(player, FakeItemUtil.getSpawnPacket(entityID, fishHook.getLocation())); - CustomFishing.protocolManager.sendServerPacket(player, FakeItemUtil.getMetaPacket(entityID, baitItem)); + entityID = new Random().nextInt(Integer.MAX_VALUE); + CustomFishing.getProtocolManager().sendServerPacket(player, FakeItemUtil.getSpawnPacket(entityID, fishHook.getLocation())); + CustomFishing.getProtocolManager().sendServerPacket(player, FakeItemUtil.getMetaPacket(entityID, baitItem)); } - BobberCheckTask bobberCheckTask = new BobberCheckTask(player, initialBonus, fishHook, this, lureLevel, entityID); - bobberCheckTask.runTaskTimer(CustomFishing.plugin, 1, 1); - bobberTaskCache.put(player, bobberCheckTask); + BobberCheckTask bobberCheckTask = new BobberCheckTask(plugin, player, initialEffect, fishHook, this, lureLevel, entityID); + bobberCheckTask.runTaskTimer(plugin, 1, 1); + hookCheckTaskMap.put(player, bobberCheckTask); }); } - public void getNextLoot(Player player, Bonus initialBonus, List possibleLoots) { + public void getNextLoot(Player player, Effect initialEffect, List possibleLoots) { List availableLoots = new ArrayList<>(); if (possibleLoots.size() == 0){ nextLoot.put(player, null); return; } - HashMap as = initialBonus.getWeightAS(); - HashMap md = initialBonus.getWeightMD(); + HashMap as = initialEffect.getWeightAS(); + HashMap md = initialEffect.getWeightMD(); double[] weights = new double[possibleLoots.size()]; int index = 0; @@ -346,8 +362,8 @@ public class FishingManager extends Function { return; } - FishingPlayer fishingPlayer = fishingPlayerCache.remove(player); - if (fishingPlayer == null) { + FishingGame fishingGame = fishingPlayerMap.remove(player); + if (fishingGame == null) { Loot loot = nextLoot.get(player); if (loot == Loot.EMPTY) return; @@ -390,7 +406,7 @@ public class FishingManager extends Function { else { item.remove(); event.setExpToDrop(0); - proceedReelIn(event, player, fishingPlayer); + proceedReelIn(event.getHook().getLocation(), player, fishingGame); } } @@ -404,78 +420,65 @@ public class FishingManager extends Function { final Player player = event.getPlayer(); Loot loot = nextLoot.remove(player); VanillaLoot vanilla = vanillaLoot.remove(player); - Bonus bonus = nextBonus.remove(player); + Effect effect = nextEffect.remove(player); if (vanilla != null) { - dropVanillaLoot(player, vanilla, item.getLocation(), bonus.getDoubleLoot() > Math.random()); - return; - } - if (loot instanceof Mob mob) { - summonMob(player, loot, item.getLocation(), mob, bonus.getScoreBonus()); - return; - } - if (loot instanceof DroppedItem droppedItem){ + dropVanillaLoot(player, vanilla, item.getLocation(), effect.getDoubleLootChance() > Math.random()); + } else if (loot instanceof Mob mob) { + summonMob(player, loot, item.getLocation(), mob, effect.getScoreMultiplier()); + } else if (loot instanceof DroppedItem droppedItem){ if (ConfigManager.enableMcMMOLoot && Math.random() < ConfigManager.mcMMOLootChance){ - if (dropMcMMOLoot(player, item.getLocation(), bonus.getDoubleLoot() > Math.random())){ + if (dropMcMMOLoot(player, item.getLocation(), effect.getDoubleLootChance() > Math.random())){ return; } } - dropCustomFishingLoot(player, item.getLocation(), droppedItem, bonus.getDoubleLoot() > Math.random(), bonus.getScoreBonus()); + dropCustomFishingLoot(player, item.getLocation(), droppedItem, effect.getDoubleLootChance() > Math.random(), effect.getScoreMultiplier(), effect.getSizeMultiplier()); } } private void noBarLavaReelIn(PlayerFishEvent event) { final Player player = event.getPlayer(); - BobberCheckTask bobberCheckTask = bobberTaskCache.remove(player); + BobberCheckTask bobberCheckTask = hookCheckTaskMap.remove(player); if (bobberCheckTask != null && bobberCheckTask.isHooked()) { Loot loot = nextLoot.remove(player); VanillaLoot vanilla = vanillaLoot.remove(player); - Bonus bonus = nextBonus.remove(player); + Effect effect = nextEffect.remove(player); if (vanilla != null) { - dropVanillaLoot(player, vanilla, event.getHook().getLocation(), bonus.getDoubleLoot() > Math.random()); - return; - } - if (loot instanceof Mob mob) { - summonMob(player, loot, event.getHook().getLocation(), mob, bonus.getScoreBonus()); - return; - } - if (loot instanceof DroppedItem droppedItem) { + dropVanillaLoot(player, vanilla, event.getHook().getLocation(), effect.getDoubleLootChance() > Math.random()); + } else if (loot instanceof Mob mob) { + summonMob(player, loot, event.getHook().getLocation(), mob, effect.getScoreMultiplier()); + } else if (loot instanceof DroppedItem droppedItem) { if (ConfigManager.enableMcMMOLoot && Math.random() < ConfigManager.mcMMOLootChance) { - if (dropMcMMOLoot(player, event.getHook().getLocation(), bonus.getDoubleLoot() > Math.random())){ + if (dropMcMMOLoot(player, event.getHook().getLocation(), effect.getDoubleLootChance() > Math.random())){ return; } } - dropCustomFishingLoot(player, event.getHook().getLocation(), droppedItem, bonus.getDoubleLoot() > Math.random(), bonus.getScoreBonus()); + dropCustomFishingLoot(player, event.getHook().getLocation(), droppedItem, effect.getDoubleLootChance() > Math.random(), effect.getScoreMultiplier(), effect.getSizeMultiplier()); } } } - private void proceedReelIn(PlayerFishEvent event, Player player, FishingPlayer fishingPlayer) { - fishingPlayer.cancel(); + public void proceedReelIn(Location hookLoc, Player player, FishingGame fishingGame) { + fishingGame.cancel(); Loot loot = nextLoot.remove(player); VanillaLoot vanilla = vanillaLoot.remove(player); - nextBonus.remove(player); + Effect effect = nextEffect.remove(player); player.removePotionEffect(PotionEffectType.SLOW); - if (fishingPlayer.isSuccess()) { + if (fishingGame.isSuccess()) { if (ConfigManager.rodLoseDurability) loseDurability(player); - Location location = event.getHook().getLocation(); - if (location.getBlock().getType() == Material.LAVA) { - location.add(0,0.3,0); + if (hookLoc.getBlock().getType() == Material.LAVA) { + hookLoc.add(0,0.3,0); } if (vanilla != null) { - dropVanillaLoot(player, vanilla, location, fishingPlayer.isDouble()); - return; - } - if (loot instanceof Mob mob) { - summonMob(player, loot, location, mob, fishingPlayer.getScoreMultiplier()); - return; - } - if (loot instanceof DroppedItem droppedItem){ + dropVanillaLoot(player, vanilla, hookLoc, effect.getDoubleLootChance() > Math.random()); + } else if (loot instanceof Mob mob) { + summonMob(player, loot, hookLoc, mob, effect.getScoreMultiplier()); + } else if (loot instanceof DroppedItem droppedItem){ if (ConfigManager.enableMcMMOLoot && Math.random() < ConfigManager.mcMMOLootChance){ - if (dropMcMMOLoot(player, location, fishingPlayer.isDouble())){ + if (dropMcMMOLoot(player, hookLoc, effect.getDoubleLootChance() > Math.random())){ return; } } - dropCustomFishingLoot(player, location, droppedItem, fishingPlayer.isDouble(), fishingPlayer.getScoreMultiplier()); + dropCustomFishingLoot(player, hookLoc, droppedItem, effect.getDoubleLootChance() > Math.random(), effect.getScoreMultiplier(), effect.getSizeMultiplier()); } } else { @@ -491,14 +494,14 @@ public class FishingManager extends Function { return; } //in fishing - FishingPlayer fishingPlayer = fishingPlayerCache.remove(player); - if (fishingPlayer != null) { - proceedReelIn(event, player, fishingPlayer); - bobberTaskCache.remove(player); + FishingGame fishingGame = fishingPlayerMap.remove(player); + if (fishingGame != null) { + proceedReelIn(event.getHook().getLocation(), player, fishingGame); + hookCheckTaskMap.remove(player); return; } //not in fishing - BobberCheckTask bobberCheckTask = bobberTaskCache.get(player); + BobberCheckTask bobberCheckTask = hookCheckTaskMap.get(player); if (bobberCheckTask != null && bobberCheckTask.isHooked()) { Loot loot = nextLoot.get(player); if (loot == Loot.EMPTY) return; @@ -507,9 +510,9 @@ public class FishingManager extends Function { } } - private void dropCustomFishingLoot(Player player, Location location, DroppedItem droppedItem, boolean isDouble, double scoreMultiplier) { - ItemStack drop = getCustomFishingLootItemStack(droppedItem, player); - FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_LOOT, isDouble, drop, droppedItem.getKey()); + private void dropCustomFishingLoot(Player player, Location location, DroppedItem droppedItem, boolean isDouble, double scoreMultiplier, double sizeMultiplier) { + ItemStack drop = getCustomFishingLootItemStack(droppedItem, player, sizeMultiplier); + FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CATCH_SPECIAL_ITEM, isDouble, drop, droppedItem.getKey()); Bukkit.getPluginManager().callEvent(fishResultEvent); if (fishResultEvent.isCancelled()) { return; @@ -534,9 +537,11 @@ public class FishingManager extends Function { } public ItemStack getCustomFishingLootItemStack(DroppedItem droppedItem, Player player) { - String key = droppedItem.getMaterial(); - ItemStack drop = CustomFishing.plugin.getIntegrationManager().build(key); + return getCustomFishingLootItemStack(droppedItem, player, 1); + } + public ItemStack getCustomFishingLootItemStack(DroppedItem droppedItem, Player player, double sizeMultiplier) { + ItemStack drop = plugin.getIntegrationManager().build(droppedItem.getMaterial()); if (drop.getType() != Material.AIR) { if (droppedItem.getRandomEnchants() != null) ItemStackUtil.addRandomEnchants(drop, droppedItem.getRandomEnchants()); @@ -544,6 +549,8 @@ public class FishingManager extends Function { ItemStackUtil.addRandomDamage(drop); if (ConfigManager.preventPickUp) ItemStackUtil.addOwner(drop, player.getName()); + if (ConfigManager.addTagToFish) + ItemStackUtil.addIdentifier(drop, "loot", droppedItem.getKey()); if (drop.getType() == Material.PLAYER_HEAD) { NBTItem nbtItem = new NBTItem(drop); NBTCompound nbtCompound = nbtItem.getCompound("SkullOwner"); @@ -552,8 +559,7 @@ public class FishingManager extends Function { drop.setItemMeta(nbtItem.getItem().getItemMeta()); } } - ItemStackUtil.addExtraMeta(drop, droppedItem); - if (ConfigManager.addTagToFish) ItemStackUtil.addIdentifier(drop, "loot", droppedItem.getKey()); + ItemStackUtil.addExtraMeta(drop, droppedItem, sizeMultiplier); } return drop; } @@ -562,7 +568,7 @@ public class FishingManager extends Function { ItemStack itemStack = McMMOTreasure.getTreasure(player); if (itemStack == null) return false; - FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_VANILLA, isDouble, itemStack, "mcmmo"); + FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CATCH_VANILLA_ITEM, isDouble, itemStack, "mcmmo"); Bukkit.getPluginManager().callEvent(fishResultEvent); if (fishResultEvent.isCancelled()) { return true; @@ -592,7 +598,6 @@ public class FishingManager extends Function { } private void dropVanillaLoot(Player player, VanillaLoot vanillaLoot, Location location, boolean isDouble) { - ItemStack itemStack; itemStack = vanillaLoot.getItemStack(); @@ -603,7 +608,7 @@ public class FishingManager extends Function { } } - FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_VANILLA, isDouble, itemStack, "vanilla"); + FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CATCH_VANILLA_ITEM, isDouble, itemStack, "vanilla"); Bukkit.getPluginManager().callEvent(fishResultEvent); if (fishResultEvent.isCancelled()) { return; @@ -621,10 +626,10 @@ public class FishingManager extends Function { } private void summonMob(Player player, Loot loot, Location location, Mob mob, double scoreMultiplier) { - MobInterface mobInterface = CustomFishing.plugin.getIntegrationManager().getMobInterface(); + MobInterface mobInterface = plugin.getIntegrationManager().getMobInterface(); if (mobInterface == null) return; - FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_MOB, false, null, loot.getKey()); + FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CATCH_MOB, false, null, loot.getKey()); if (fishResultEvent.isCancelled()) { return; } @@ -634,9 +639,8 @@ public class FishingManager extends Function { if (Competition.currentCompetition.getGoal() == CompetitionGoal.MAX_SIZE || Competition.currentCompetition.getGoal() == CompetitionGoal.TOTAL_SIZE) { score = 0; } - else { - score = (float) loot.getScore(); - } + else score = (float) loot.getScore(); + Competition.currentCompetition.refreshData(player, (float) (score * scoreMultiplier), false); Competition.currentCompetition.tryAddBossBarToPlayer(player); } @@ -689,67 +693,70 @@ public class FishingManager extends Function { Component titleComponent = getTitleComponent(itemStack, title); String subTitle = ConfigManager.successSubTitle[new Random().nextInt(ConfigManager.successSubTitle.length)]; Component subtitleComponent = getTitleComponent(itemStack, subTitle); - AdventureUtil.playerTitle( - player, - titleComponent, - subtitleComponent, - ConfigManager.successFadeIn, - ConfigManager.successFadeStay, - ConfigManager.successFadeOut - ); + Bukkit.getScheduler().runTaskLater(plugin, () -> { + AdventureUtil.playerTitle( + player, + titleComponent, + subtitleComponent, + ConfigManager.successFadeIn, + ConfigManager.successFadeStay, + ConfigManager.successFadeOut + ); + }, 8); } private void loseDurability(Player player) { if (player.getGameMode() == GameMode.CREATIVE) return; - Bukkit.getScheduler().runTaskLater(CustomFishing.plugin, () -> { + Bukkit.getScheduler().runTaskLater(plugin, () -> { PlayerInventory inventory = player.getInventory(); ItemStack mainHand = inventory.getItemInMainHand(); if (mainHand.getType() == Material.FISHING_ROD){ - CustomFishing.plugin.getIntegrationManager().loseCustomDurability(mainHand, player); + plugin.getIntegrationManager().loseCustomDurability(mainHand, player); } else { ItemStack offHand = inventory.getItemInOffHand(); if (offHand.getType() == Material.FISHING_ROD){ - CustomFishing.plugin.getIntegrationManager().loseCustomDurability(offHand, player); + plugin.getIntegrationManager().loseCustomDurability(offHand, player); } } }, 1); } - private void fail(Player player, Loot loot, boolean isVanilla) { - + public void fail(Player player, Loot loot, boolean isVanilla) { FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.FAILURE, false, null, "null"); Bukkit.getServer().getPluginManager().callEvent(fishResultEvent); if (fishResultEvent.isCancelled()) { return; } - if (!isVanilla && loot != null){ + if (!isVanilla && loot != null) { for (ActionInterface action : loot.getFailureActions()) action.doOn(player, null); } - AdventureUtil.playerTitle( - player, - ConfigManager.failureTitle[new Random().nextInt(ConfigManager.failureTitle.length)], - ConfigManager.failureSubTitle[new Random().nextInt(ConfigManager.failureSubTitle.length)], - ConfigManager.failureFadeIn, - ConfigManager.failureFadeStay, - ConfigManager.failureFadeOut - ); + Bukkit.getScheduler().runTaskLater(plugin, () -> { + AdventureUtil.playerTitle( + player, + ConfigManager.failureTitle[new Random().nextInt(ConfigManager.failureTitle.length)], + ConfigManager.failureSubTitle[new Random().nextInt(ConfigManager.failureSubTitle.length)], + ConfigManager.failureFadeIn, + ConfigManager.failureFadeStay, + ConfigManager.failureFadeOut + ); + }, 8); } public void onCaughtEntity(PlayerFishEvent event) { final Player player = event.getPlayer(); - FishingPlayer fishingPlayer = fishingPlayerCache.remove(player); - if (fishingPlayer != null) { + FishingGame fishingGame = fishingPlayerMap.remove(player); + if (fishingGame != null) { Entity entity = event.getCaught(); if (entity != null && entity.getType() == EntityType.ARMOR_STAND) { - proceedReelIn(event, player, fishingPlayer); + proceedReelIn(event.getHook().getLocation(), player, fishingGame); } else { - fishingPlayer.cancel(); - nextBonus.remove(player); + fishingGame.cancel(); + nextEffect.remove(player); nextLoot.remove(player); AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.hookOther); } @@ -768,7 +775,7 @@ public class FishingManager extends Function { } public void showBar(Player player) { - if (fishingPlayerCache.get(player) != null) return; + if (fishingPlayerMap.get(player) != null) return; Loot loot = nextLoot.get(player); if (loot != null) { if (loot == Loot.EMPTY) return; @@ -802,13 +809,13 @@ public class FishingManager extends Function { return false; } - private void enchantBonus(Bonus initialBonus, ItemStack itemStack) { + private void enchantBonus(Effect initialEffect, ItemStack itemStack) { Map enchantments = itemStack.getEnchantments(); for (Map.Entry en : enchantments.entrySet()) { String key = en.getKey().getKey() + ":" + en.getValue(); - Bonus enchantBonus = BonusManager.ENCHANTS.get(key); - if (enchantBonus != null) { - initialBonus.addBonus(enchantBonus); + Effect enchantEffect = plugin.getEffectManager().getEnchantEffect(key); + if (enchantEffect != null) { + initialEffect.addEffect(enchantEffect); } } } @@ -852,29 +859,28 @@ public class FishingManager extends Function { if (block == null) return; String totemID = nbtItem.getString("Totem"); if (totemID.equals("")) return; - TotemConfig totem = TotemManager.TOTEMS.get(totemID); + TotemConfig totem = plugin.getTotemManager().getTotem(totemID); if (totem == null) return; if (isCoolDown(player, 1000)) return; - String blockID = CustomFishing.plugin.getIntegrationManager().getBlockInterface().getID(block); + String blockID = plugin.getIntegrationManager().getBlockInterface().getID(block); if (blockID == null) return; - List totemList = TotemManager.CORES.get(blockID); + List totemList = plugin.getTotemManager().getTotemsByCoreID(blockID); if (totemList == null || !totemList.contains(totem)) return; Location coreLoc = block.getLocation(); - int direction = CustomFishing.plugin.getTotemManager().checkLocationModel(totem.getOriginalModel(), coreLoc); + int direction = plugin.getTotemManager().checkLocationModel(totem.getOriginalModel(), coreLoc); if (direction == 0) return; - if (!AntiGriefInterface.testBreak(player, coreLoc)) return; TotemActivationEvent totemActivationEvent = new TotemActivationEvent(player, coreLoc, totem); Bukkit.getPluginManager().callEvent(totemActivationEvent); if (totemActivationEvent.isCancelled()) { return; } - if (totemCache.get(LocationUtils.getSimpleLocation(coreLoc)) != null) { - totemCache.get(LocationUtils.getSimpleLocation(coreLoc)).stop(); + if (activeTotemMap.get(LocationUtils.getSimpleLocation(coreLoc)) != null) { + activeTotemMap.get(LocationUtils.getSimpleLocation(coreLoc)).stop(); } - CustomFishing.plugin.getTotemManager().removeModel(totem.getFinalModel(), coreLoc, direction); + plugin.getTotemManager().removeModel(totem.getFinalModel(), coreLoc, direction); if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1); for (ActionInterface action : totem.getActivatorActions()) { @@ -888,14 +894,13 @@ public class FishingManager extends Function { Location bottomLoc = coreLoc.clone().subtract(0, totem.getOriginalModel().getCorePos().getY(), 0); ActivatedTotem activatedTotem = new ActivatedTotem(bottomLoc, totem, this, direction); - activatedTotem.runTaskTimer(CustomFishing.plugin, 10, 20); - totemCache.put(LocationUtils.getSimpleLocation(bottomLoc), activatedTotem); + activatedTotem.runTaskTimer(plugin, 10, 20); + activeTotemMap.put(LocationUtils.getSimpleLocation(bottomLoc), activatedTotem); } private void useFinder(Player player) { FishingCondition fishingCondition = new FishingCondition(player.getLocation(), player); - List possibleLoots = getPossibleLootList(fishingCondition, true, LootManager.WATERLOOTS.values()); - possibleLoots.addAll(getPossibleLootList(fishingCondition, true, LootManager.LAVALOOTS.values())); + List possibleLoots = getPossibleLootList(fishingCondition, true, plugin.getLootManager().getAllLoots()); FishFinderEvent fishFinderEvent = new FishFinderEvent(player, possibleLoots); Bukkit.getPluginManager().callEvent(fishFinderEvent); @@ -913,84 +918,66 @@ public class FishingManager extends Function { } private void showPlayerBar(Player player, @Nullable Loot loot){ - - Layout layout; - if (loot != null && loot.getLayout() != null){ - layout = loot.getLayout()[new Random().nextInt(loot.getLayout().length)]; + MiniGameConfig game; + if (loot != null && loot.getFishingGames() != null) { + game = loot.getFishingGames()[new Random().nextInt(loot.getFishingGames().length)]; } else { - layout = (Layout) LayoutManager.LAYOUTS.values().toArray()[new Random().nextInt(LayoutManager.LAYOUTS.values().size())]; + game = plugin.getBarMechanicManager().getRandomGame(); } - - int speed; - int timer; - int time; - if (loot != null){ - Difficulty difficulty = loot.getDifficulty()[new Random().nextInt(loot.getDifficulty().length)]; - speed = difficulty.speed(); - timer = difficulty.timer(); - time = loot.getTime(); + int difficult = game.getRandomDifficulty(); + Effect effect = nextEffect.get(player); + if (effect != null) { + difficult += effect.getDifficulty(); } - else { - speed = new Random().nextInt(5); - time = 10000; - timer = 1; - } - - Bonus bonus = nextBonus.get(player); - boolean isDouble = false; - double scoreMultiplier = 1; - if (bonus != null) { - speed += bonus.getDifficulty(); - isDouble = Math.random() < bonus.getDoubleLoot(); - scoreMultiplier = bonus.getScoreBonus(); - } - - if (speed < 1){ - speed = 1; - } - - Difficulty difficult = new Difficulty(timer, speed); - FishHookEvent fishHookEvent = new FishHookEvent(player, difficult); Bukkit.getPluginManager().callEvent(fishHookEvent); if (fishHookEvent.isCancelled()) { return; } + difficult = fishHookEvent.getDifficulty(); + if (difficult < 1) { + difficult = 1; + } - FishingPlayer fishingPlayer = new FishingPlayer(System.currentTimeMillis() + time, player, layout, difficult, this, isDouble, scoreMultiplier); - fishingPlayer.runTaskTimerAsynchronously(CustomFishing.plugin, 0, 1); - fishingPlayerCache.put(player, fishingPlayer); - + FishingBar fishingBar = game.getRandomBar(); + if (fishingBar instanceof ModeOneBar modeOneBar) { + ModeOneGame modeOneGame = new ModeOneGame(plugin, this, System.currentTimeMillis() + game.getTime() * 1000L, player, difficult, modeOneBar); + modeOneGame.runTaskTimer(CustomFishing.getInstance(), 0, 1); + fishingPlayerMap.put(player, modeOneGame); + } + else if (fishingBar instanceof ModeTwoBar modeTwoBar) { + ModeTwoGame modeTwoGame = new ModeTwoGame(plugin, this, System.currentTimeMillis() + game.getTime() * 1000L, player, difficult, modeTwoBar); + modeTwoGame.runTaskTimer(CustomFishing.getInstance(), 0, 1); + fishingPlayerMap.put(player, modeTwoGame); + } if (vanillaLoot.get(player) == null && loot != null){ for (ActionInterface action : loot.getHookActions()) { action.doOn(player, null); } } - - player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, time/50,3)); + player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, game.getTime() * 20,3)); } @Override public void onQuit(Player player) { coolDown.remove(player); nextLoot.remove(player); - nextBonus.remove(player); + nextEffect.remove(player); vanillaLoot.remove(player); - BobberCheckTask task = bobberTaskCache.remove(player); + BobberCheckTask task = hookCheckTaskMap.remove(player); if (task != null) task.stop(); // prevent bar duplication - FishHook fishHook = hooksCache.remove(player); - if (fishHook != null) fishHook.remove(); + removeBobber(player); } @Nullable - public FishingPlayer getFishingPlayer(Player player) { - return fishingPlayerCache.get(player); + public FishingGame getFishingPlayer(Player player) { + return fishingPlayerMap.get(player); } public void removeFishingPlayer(Player player) { - fishingPlayerCache.remove(player); + fishingPlayerMap.remove(player); } private Component getDisplayName(ItemStack itemStack){ @@ -1008,11 +995,11 @@ public class FishingManager extends Function { } public void removeTotem(Location location) { - totemCache.remove(LocationUtils.getSimpleLocation(location)); + activeTotemMap.remove(LocationUtils.getSimpleLocation(location)); } public void removePlayerFromLavaFishing(Player player) { - this.bobberTaskCache.remove(player); + this.hookCheckTaskMap.remove(player); } public float getSize(ItemStack itemStack) { @@ -1025,20 +1012,49 @@ public class FishingManager extends Function { } public void addTotemBreakDetectToCache(SimpleLocation part, SimpleLocation bottom) { - breakDetectCache.put(part, bottom); + breakDetectionMap.put(part, bottom); } public void removeTotemBreakDetectFromCache(SimpleLocation part) { - breakDetectCache.remove(part); + breakDetectionMap.remove(part); } @Override public void onBreakBlock(BlockBreakEvent event) { final Block block = event.getBlock(); - SimpleLocation bottomLoc = breakDetectCache.get(LocationUtils.getSimpleLocation(block.getLocation())); + SimpleLocation bottomLoc = breakDetectionMap.get(LocationUtils.getSimpleLocation(block.getLocation())); if (bottomLoc == null) return; - ActivatedTotem activatedTotem = totemCache.get(bottomLoc); + ActivatedTotem activatedTotem = activeTotemMap.get(bottomLoc); if (activatedTotem == null) return; activatedTotem.stop(); } -} + + public void removeBobber(Player player) { + FishHook fishHook = hooks.remove(player); + if (fishHook != null) { + fishHook.remove(); + } + } + + @Nullable + public FishHook getBobber(Player player) { + return hooks.get(player); + } + + @Override + public void onConsumeItem(PlayerItemConsumeEvent event) { + ItemStack itemStack = event.getItem(); + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound nbtCompound = nbtItem.getCompound("CustomFishing"); + if (nbtCompound == null) return; + if (!nbtCompound.getString("type").equals("loot")) return; + String lootKey = nbtCompound.getString("id"); + Loot loot = plugin.getLootManager().getLoot(lootKey); + if (loot == null) return; + if (!(loot instanceof DroppedItem droppedItem)) return; + final Player player = event.getPlayer(); + if (droppedItem.getConsumeActions() != null) + for (ActionInterface action : droppedItem.getConsumeActions()) + action.doOn(player, null); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/manager/IntegrationManager.java b/src/main/java/net/momirealms/customfishing/manager/IntegrationManager.java index dc2fa347..7c736672 100644 --- a/src/main/java/net/momirealms/customfishing/manager/IntegrationManager.java +++ b/src/main/java/net/momirealms/customfishing/manager/IntegrationManager.java @@ -20,7 +20,6 @@ package net.momirealms.customfishing.manager; import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.helper.Log; import net.momirealms.customfishing.integration.*; -import net.momirealms.customfishing.integration.antigrief.*; import net.momirealms.customfishing.integration.block.ItemsAdderBlockImpl; import net.momirealms.customfishing.integration.block.OraxenBlockImpl; import net.momirealms.customfishing.integration.block.VanillaBlockImpl; @@ -39,7 +38,6 @@ import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ConfigUtil; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.Damageable; @@ -57,175 +55,27 @@ public class IntegrationManager extends Function { private ItemInterface[] itemInterfaces; private MobInterface mobInterface; private BlockInterface blockInterface; - private PlaceholderManager placeholderManager; - private AntiGriefInterface[] antiGriefs; + private final PlaceholderManager placeholderManager; private VaultHook vaultHook; + private final CustomFishing plugin; + private final PluginManager pluginManager; + + public IntegrationManager(CustomFishing plugin) { + this.plugin = plugin; + this.pluginManager = Bukkit.getPluginManager(); + this.placeholderManager = new PlaceholderManager(); + this.blockInterface = new VanillaBlockImpl(); + } @Override public void load() { - - PluginManager pluginManager = Bukkit.getPluginManager(); - - if (this.placeholderManager != null) { - this.placeholderManager.unload(); - } - - this.placeholderManager = new PlaceholderManager(); - - YamlConfiguration config = ConfigUtil.getConfig("config.yml"); - - if (ConfigManager.vaultHook && pluginManager.getPlugin("Vault") != null) { - vaultHook = new VaultHook(); - if (!vaultHook.initialize()) { - ConfigManager.vaultHook = false; - Log.warn("Failed to initialize Vault!"); - } - else hookMessage("Vault"); - } - - this.blockInterface = new VanillaBlockImpl(); - - List itemInterfaceList = new ArrayList<>(); - if (config.getBoolean("integrations.ItemsAdder") && pluginManager.getPlugin("ItemsAdder") != null) { - this.blockInterface = new ItemsAdderBlockImpl(); - itemInterfaceList.add(new ItemsAdderItemImpl()); - hookMessage("ItemsAdder"); - } - if (config.getBoolean("integrations.Oraxen") && pluginManager.getPlugin("Oraxen") != null) { - this.blockInterface = new OraxenBlockImpl(); - itemInterfaceList.add(new OraxenItemImpl()); - hookMessage("Oraxen"); - } - if (config.getBoolean("integrations.MMOItems") && pluginManager.getPlugin("MMOItems") != null) { - itemInterfaceList.add(new MMOItemsItemImpl()); - hookMessage("MMOItems"); - } - if (config.getBoolean("integrations.MythicMobs") && pluginManager.getPlugin("MythicMobs") != null) { - itemInterfaceList.add(new MythicMobsItemImpl()); - this.mobInterface = new MythicMobsMobImpl(); - hookMessage("MythicMobs"); - } - itemInterfaceList.add(new CustomFishingItemImpl()); - this.itemInterfaces = itemInterfaceList.toArray(new ItemInterface[0]); - - if (pluginManager.getPlugin("eco") != null) { - EcoItemRegister.registerItems(); - hookMessage("eco"); - } - - if (config.getBoolean("integrations.RealisticSeasons", false) && pluginManager.getPlugin("RealisticSeasons") != null) { - this.seasonInterface = new RealisticSeasonsImpl(); - hookMessage("RealisticSeasons"); - } else if (config.getBoolean("integrations.CustomCrops", false) && pluginManager.getPlugin("CustomCrops") != null) { - this.seasonInterface = new CustomCropsSeasonImpl(); - hookMessage("CustomCrops"); - } - if (config.getBoolean("integrations.mcMMO", false) && Bukkit.getPluginManager().getPlugin("mcMMO") != null) { - this.skillInterface = new mcMMOImpl(); - hookMessage("mcMMO"); - } else if (config.getBoolean("integrations.MMOCore", false) && Bukkit.getPluginManager().getPlugin("MMOCore") != null) { - this.skillInterface = new MMOCoreImpl(config.getString("other-settings.MMOCore-profession-name", "fishing")); - hookMessage("MMOCore"); - } else if (config.getBoolean("integrations.AureliumSkills", false) && Bukkit.getPluginManager().getPlugin("AureliumSkills") != null) { - this.skillInterface = new AureliumsImpl(); - hookMessage("AureliumSkills"); - } else if (config.getBoolean("integrations.EcoSkills", false) && Bukkit.getPluginManager().getPlugin("EcoSkills") != null) { - this.skillInterface = new EcoSkillsImpl(); - hookMessage("EcoSkills"); - } else if (config.getBoolean("integrations.JobsReborn", false) && Bukkit.getPluginManager().getPlugin("Jobs") != null) { - this.skillInterface = new JobsRebornImpl(); - hookMessage("JobsReborn"); - } - - List antiGriefsList = new ArrayList<>(); - if (config.getBoolean("integrations.Residence",false)){ - if (Bukkit.getPluginManager().getPlugin("Residence") == null) Log.warn("Failed to initialize Residence!"); - else { - antiGriefsList.add(new ResidenceHook()); - hookMessage("Residence"); - } - } - if (config.getBoolean("integrations.Kingdoms",false)){ - if (Bukkit.getPluginManager().getPlugin("Kingdoms") == null) Log.warn("Failed to initialize Kingdoms!"); - else { - antiGriefsList.add(new KingdomsXHook()); - hookMessage("Kingdoms"); - } - } - if (config.getBoolean("integrations.WorldGuard",false)){ - if (Bukkit.getPluginManager().getPlugin("WorldGuard") == null) Log.warn("Failed to initialize WorldGuard!"); - else { - antiGriefsList.add(new WorldGuardHook()); - hookMessage("WorldGuard"); - } - } - if (config.getBoolean("integrations.GriefDefender",false)){ - if(Bukkit.getPluginManager().getPlugin("GriefDefender") == null) Log.warn("Failed to initialize GriefDefender!"); - else { - antiGriefsList.add(new GriefDefenderHook()); - hookMessage("GriefDefender"); - } - } - if (config.getBoolean("integrations.PlotSquared",false)){ - if(Bukkit.getPluginManager().getPlugin("PlotSquared") == null) Log.warn("Failed to initialize PlotSquared!"); - else { - antiGriefsList.add(new PlotSquaredHook()); - hookMessage("PlotSquared"); - } - } - if (config.getBoolean("integrations.Towny",false)){ - if (Bukkit.getPluginManager().getPlugin("Towny") == null) Log.warn("Failed to initialize Towny!"); - else { - antiGriefsList.add(new TownyHook()); - hookMessage("Towny"); - } - } - if (config.getBoolean("integrations.Lands",false)){ - if (Bukkit.getPluginManager().getPlugin("Lands") == null) Log.warn("Failed to initialize Lands!"); - else { - antiGriefsList.add(new LandsHook()); - hookMessage("Lands"); - } - } - if (config.getBoolean("integrations.GriefPrevention",false)){ - if (Bukkit.getPluginManager().getPlugin("GriefPrevention") == null) Log.warn("Failed to initialize GriefPrevention!"); - else { - antiGriefsList.add(new GriefPreventionHook()); - hookMessage("GriefPrevention"); - } - } - if (config.getBoolean("integrations.CrashClaim",false)){ - if (Bukkit.getPluginManager().getPlugin("CrashClaim") == null) Log.warn("Failed to initialize CrashClaim!"); - else { - antiGriefsList.add(new CrashClaimHook()); - hookMessage("CrashClaim"); - } - } - if (config.getBoolean("integrations.BentoBox",false)){ - if (Bukkit.getPluginManager().getPlugin("BentoBox") == null) Log.warn("Failed to initialize BentoBox!"); - else { - antiGriefsList.add(new BentoBoxHook()); - hookMessage("BentoBox"); - } - } - antiGriefs = antiGriefsList.toArray(new AntiGriefInterface[0]); - } - - public void registerQuests() { - if (Bukkit.getPluginManager().isPluginEnabled("ClueScrolls")) { - ClueScrollCFQuest clueScrollCFQuest = new ClueScrollCFQuest(); - Bukkit.getPluginManager().registerEvents(clueScrollCFQuest, CustomFishing.plugin); - hookMessage("ClueScrolls"); - } - if (Bukkit.getPluginManager().isPluginEnabled("BetonQuest")) { - if (Bukkit.getPluginManager().getPlugin("BetonQuest").getDescription().getVersion().startsWith("2.")) NewBetonQuestCFQuest.register(); - else OldBetonQuestCFQuest.register(); - hookMessage("BetonQuest"); - } - if (Bukkit.getPluginManager().isPluginEnabled("BattlePass")) { - BattlePassCFQuest.register(); - hookMessage("BattlePass"); - } + this.placeholderManager.load(); + hookSeasons(); + hookSkills(); + hookItems(); + hookVault(); + hookMobs(); + hookBlocks(); } @Override @@ -235,9 +85,104 @@ public class IntegrationManager extends Function { this.itemInterfaces = null; this.mobInterface = null; this.blockInterface = null; - if (this.placeholderManager != null) { - this.placeholderManager.unload(); - this.placeholderManager = null; + this.placeholderManager.unload(); + } + + private void hookMobs() { + if (pluginManager.isPluginEnabled("MythicMobs")) { + this.mobInterface = new MythicMobsMobImpl(); + } + } + + private void hookBlocks() { + if (pluginManager.isPluginEnabled("Oraxen")) { + this.blockInterface = new OraxenBlockImpl(); + } + else if (pluginManager.isPluginEnabled("ItemsAdder")) { + this.blockInterface = new ItemsAdderBlockImpl(); + } + } + + private void hookSeasons() { + if (pluginManager.isPluginEnabled("RealisticSeasons")) { + this.seasonInterface = new RealisticSeasonsImpl(); + hookMessage("RealisticSeasons"); + } else if (pluginManager.isPluginEnabled("CustomCrops")) { + this.seasonInterface = new CustomCropsSeasonImpl(); + hookMessage("CustomCrops"); + } + } + + private void hookSkills() { + if (pluginManager.getPlugin("mcMMO") != null) { + this.skillInterface = new mcMMOImpl(); + hookMessage("mcMMO"); + } else if (pluginManager.getPlugin("MMOCore") != null) { + this.skillInterface = new MMOCoreImpl(ConfigUtil.getConfig("config.yml").getString("other-settings.MMOCore-profession-name", "fishing")); + hookMessage("MMOCore"); + } else if (pluginManager.getPlugin("AureliumSkills") != null) { + this.skillInterface = new AureliumsImpl(); + hookMessage("AureliumSkills"); + } else if (pluginManager.getPlugin("EcoSkills") != null) { + this.skillInterface = new EcoSkillsImpl(); + hookMessage("EcoSkills"); + } else if (pluginManager.getPlugin("Jobs") != null) { + this.skillInterface = new JobsRebornImpl(); + hookMessage("JobsReborn"); + } + } + + private void hookVault() { + if (pluginManager.isPluginEnabled("Vault")) { + vaultHook = new VaultHook(); + if (!vaultHook.initialize()) { + Log.warn("Failed to initialize Vault!"); + } + else hookMessage("Vault"); + } + } + + private void hookItems() { + List itemInterfaceList = new ArrayList<>(); + if (pluginManager.isPluginEnabled("ItemsAdder")) { + itemInterfaceList.add(new ItemsAdderItemImpl()); + hookMessage("ItemsAdder"); + } + if (pluginManager.isPluginEnabled("Oraxen")) { + itemInterfaceList.add(new OraxenItemImpl()); + hookMessage("Oraxen"); + } + if (pluginManager.isPluginEnabled("MMOItems")) { + itemInterfaceList.add(new MMOItemsItemImpl()); + hookMessage("MMOItems"); + } + if (pluginManager.isPluginEnabled("MythicMobs")) { + itemInterfaceList.add(new MythicMobsItemImpl()); + hookMessage("MythicMobs"); + } + itemInterfaceList.add(new CustomFishingItemImpl(plugin)); + this.itemInterfaces = itemInterfaceList.toArray(new ItemInterface[0]); + + if (pluginManager.isPluginEnabled("eco")) { + EcoItemRegister.registerItems(); + hookMessage("eco"); + } + } + + public void registerQuests() { + if (pluginManager.isPluginEnabled("ClueScrolls")) { + ClueScrollCFQuest clueScrollCFQuest = new ClueScrollCFQuest(); + Bukkit.getPluginManager().registerEvents(clueScrollCFQuest, plugin); + hookMessage("ClueScrolls"); + } + if (pluginManager.isPluginEnabled("BetonQuest")) { + if (Bukkit.getPluginManager().getPlugin("BetonQuest").getDescription().getVersion().startsWith("2.")) NewBetonQuestCFQuest.register(); + else OldBetonQuestCFQuest.register(); + hookMessage("BetonQuest"); + } + if (pluginManager.isPluginEnabled("BattlePass")) { + BattlePassCFQuest.register(); + hookMessage("BattlePass"); } } @@ -271,11 +216,6 @@ public class IntegrationManager extends Function { return placeholderManager; } - @NotNull - public AntiGriefInterface[] getAntiGriefs() { - return antiGriefs; - } - @NotNull public ItemStack build(String key) { for (ItemInterface itemInterface : getItemInterfaces()) { @@ -298,7 +238,7 @@ public class IntegrationManager extends Function { } private void hookMessage(String plugin){ - AdventureUtil.consoleMessage("[CustomFishing] " + plugin + " Hooked!"); + AdventureUtil.consoleMessage("[CustomFishing] " + plugin + " hooked!"); } @Nullable diff --git a/src/main/java/net/momirealms/customfishing/manager/LayoutManager.java b/src/main/java/net/momirealms/customfishing/manager/LayoutManager.java deleted file mode 100644 index 7adc05fd..00000000 --- a/src/main/java/net/momirealms/customfishing/manager/LayoutManager.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.manager; - -import net.momirealms.customfishing.object.Function; -import net.momirealms.customfishing.object.fishing.Layout; -import net.momirealms.customfishing.util.AdventureUtil; -import net.momirealms.customfishing.util.ConfigUtil; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.util.HashMap; -import java.util.Objects; -import java.util.Set; - -public class LayoutManager extends Function { - - public static HashMap LAYOUTS; - - @Override - public void load() { - LAYOUTS = new HashMap<>(); - YamlConfiguration config = ConfigUtil.getConfig("bars.yml"); - Set keys = config.getKeys(false); - for (String key : keys) { - int range = config.getInt(key + ".range"); - Set rates = Objects.requireNonNull(config.getConfigurationSection(key + ".layout")).getKeys(false); - double[] successRate = new double[rates.size()]; - for(int i = 0; i < rates.size(); i++) - successRate[i] = config.getDouble(key + ".layout." + (i + 1)); - int size = rates.size() * range - 1; - Layout layout = new Layout( - range, - successRate, - size, - config.getString(key + ".subtitle.start",""), - config.getString(key + ".subtitle.bar","뀃"), - config.getString(key + ".subtitle.pointer","뀄"), - config.getString(key + ".subtitle.offset","뀁"), - config.getString(key + ".subtitle.end",""), - config.getString(key + ".subtitle.pointer_offset","뀂"), - config.getString(key + ".title"," ") - ); - LAYOUTS.put(key, layout); - } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + LAYOUTS.size() + " bars"); - } - - @Override - public void unload() { - if (LAYOUTS != null) LAYOUTS.clear(); - } -} diff --git a/src/main/java/net/momirealms/customfishing/manager/LootManager.java b/src/main/java/net/momirealms/customfishing/manager/LootManager.java index 274f0dd1..d20b3f98 100644 --- a/src/main/java/net/momirealms/customfishing/manager/LootManager.java +++ b/src/main/java/net/momirealms/customfishing/manager/LootManager.java @@ -18,65 +18,78 @@ package net.momirealms.customfishing.manager; import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.MiniGameConfig; +import net.momirealms.customfishing.fishing.loot.*; +import net.momirealms.customfishing.fishing.requirements.*; import net.momirealms.customfishing.object.Function; +import net.momirealms.customfishing.object.LeveledEnchantment; import net.momirealms.customfishing.object.action.*; -import net.momirealms.customfishing.object.fishing.Difficulty; -import net.momirealms.customfishing.object.fishing.Layout; -import net.momirealms.customfishing.object.loot.*; -import net.momirealms.customfishing.object.requirements.*; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ItemStackUtil; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; -import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.NamespacedKey; +import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.Nullable; import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Set; +import java.util.*; public class LootManager extends Function { - public static HashMap WATERLOOTS; - public static HashMap LAVALOOTS; - public static HashMap LOOTITEMS; + private final CustomFishing plugin; + private final HashMap waterLoots; + private final HashMap lavaLoots; + private final HashMap lootItems; + + public LootManager(CustomFishing plugin) { + this.plugin = plugin; + this.waterLoots = new HashMap<>(); + this.lavaLoots = new HashMap<>(); + this.lootItems = new HashMap<>(); + } @Nullable - public static ItemStack build(String key) { - ItemStack itemStack = LOOTITEMS.get(key); + public ItemStack build(String key) { + ItemStack itemStack = this.lootItems.get(key); return itemStack == null ? null : itemStack.clone(); } @Override public void load() { - WATERLOOTS = new HashMap<>(); - LAVALOOTS = new HashMap<>(); - LOOTITEMS = new HashMap<>(); - loadItems(); - loadMobs(); - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + (LAVALOOTS.size() + WATERLOOTS.size()) + " loots"); + this.loadItems(); + this.loadMobs(); + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + (this.lavaLoots.size() + this.waterLoots.size()) + " loot(s)"); } @Override public void unload() { - if (WATERLOOTS != null) WATERLOOTS.clear(); - if (LAVALOOTS != null) LAVALOOTS.clear(); - if (LOOTITEMS != null) LOOTITEMS.clear(); + this.waterLoots.clear(); + this.lavaLoots.clear(); + this.lootItems.clear(); + } + + @Nullable + public Loot getLoot(String key) { + Loot loot = this.waterLoots.get(key); + if (loot == null) { + loot = this.lavaLoots.get(key); + } + return loot; } private void loadMobs() { if (Bukkit.getPluginManager().getPlugin("MythicMobs") == null) return; - File mob_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "mobs"); + File mob_file = new File(plugin.getDataFolder() + File.separator + "mobs"); if (!mob_file.exists()) { if (!mob_file.mkdir()) return; - CustomFishing.plugin.saveResource("mobs" + File.separator + "example.yml", false); + plugin.saveResource("mobs" + File.separator + "default.yml", false); } File[] files = mob_file.listFiles(); if (files == null) return; @@ -85,54 +98,35 @@ public class LootManager extends Function { YamlConfiguration config = YamlConfiguration.loadConfiguration(file); Set keys = config.getKeys(false); for (String key : keys) { - if (!config.getBoolean(key + ".enable", true)) continue; - // Bar mechanic - List difficulties = new ArrayList<>(); - List difficultyList = config.getStringList(key + ".difficulty"); - if (difficultyList.size() == 0) { - String[] diff = StringUtils.split(config.getString(key + ".difficulty", "1-1"),"-"); - Difficulty difficulty = new Difficulty(Integer.parseInt(diff[0]), Integer.parseInt(diff[1])); - difficulties.add(difficulty); - } - else { - for (String difficultyStr : difficultyList) { - String[] diff = StringUtils.split(difficultyStr,"-"); - Difficulty difficulty = new Difficulty(Integer.parseInt(diff[0]), Integer.parseInt(diff[1])); - difficulties.add(difficulty); - } - } - - int weight = config.getInt(key + ".weight",10); - int time = config.getInt(key + ".time",10000); + ConfigurationSection mobSection = config.getConfigurationSection(key); + if (mobSection == null) continue; + if (!mobSection.getBoolean("enable", true)) continue; Mob loot = new Mob( key, - difficulties.toArray(new Difficulty[0]), - time, - weight, - config.getString(key + ".mobID", key), - config.getInt(key + ".level", 0), + mobSection.contains("nick") ? mobSection.getString("nick") : AdventureUtil.replaceLegacy(mobSection.getString("mobID", key)), + getMiniGames(mobSection), + mobSection.getInt("weight",10), + mobSection.getBoolean("show-in-fishfinder", true), + mobSection.getDouble("score",10d), + mobSection.getString(key + ".mobID", key), + mobSection.getInt(key + ".level", 0), new MobVector( - config.getDouble(key + ".vector.horizontal",1.1), - config.getDouble(key + ".vector.vertical",1.3) - )); - if (config.contains(key + ".nick")) loot.setNick(config.getString(key + ".nick")); - else loot.setNick(ChatColor.stripColor(config.getString(key + ".mobID", key))); - setActionsAndRequirements(config, loot, key); - if (config.getBoolean(key + ".in-lava", false)) { - LAVALOOTS.put(key, loot); - } else { - WATERLOOTS.put(key, loot); - } + mobSection.getDouble("vector.horizontal",1.1), + mobSection.getDouble("vector.vertical",1.3) + ) + ); + if (mobSection.getBoolean("in-lava", false)) lavaLoots.put(key, loot); + else waterLoots.put(key, loot); } } } private void loadItems() { - File loot_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "loots"); + File loot_file = new File(plugin.getDataFolder() + File.separator + "loots"); if (!loot_file.exists()) { if (!loot_file.mkdir()) return; - CustomFishing.plugin.saveResource("loots" + File.separator + "default.yml", false); - CustomFishing.plugin.saveResource("loots" + File.separator + "example.yml", false); + plugin.saveResource("loots" + File.separator + "default.yml", false); + plugin.saveResource("loots" + File.separator + "example.yml", false); } File[] files = loot_file.listFiles(); if (files == null) return; @@ -141,139 +135,155 @@ public class LootManager extends Function { YamlConfiguration config = YamlConfiguration.loadConfiguration(file); Set keys = config.getKeys(false); for (String key : keys) { - if (!config.getBoolean(key + ".enable", true)) continue; + ConfigurationSection lootSection = config.getConfigurationSection(key); + if (lootSection == null) continue; + if (!lootSection.getBoolean("enable", true)) continue; + String material = lootSection.getString("material","COD"); - String material = config.getString(key + ".material","COD"); - // Bar mechanic - List difficulties = new ArrayList<>(); - List difficultyList = config.getStringList(key + ".difficulty"); - if (difficultyList.size() == 0) { - String[] diff = StringUtils.split(config.getString(key + ".difficulty", "1-1"),"-"); - Difficulty difficulty = new Difficulty(Integer.parseInt(diff[0]), Integer.parseInt(diff[1])); - difficulties.add(difficulty); - } - else { - for (String difficultyStr : difficultyList) { - String[] diff = StringUtils.split(difficultyStr,"-"); - Difficulty difficulty = new Difficulty(Integer.parseInt(diff[0]), Integer.parseInt(diff[1])); - difficulties.add(difficulty); - } - } - int weight = config.getInt(key + ".weight",10); - int time = config.getInt(key + ".time",10000); DroppedItem loot = new DroppedItem( key, - difficulties.toArray(new Difficulty[0]), - time, - weight, - material.contains(":") ? material : key); - // Set nick - if (config.contains(key + ".nick")) loot.setNick(config.getString(key + ".nick")); - else loot.setNick(ChatColor.stripColor(config.getString(key + ".display.name", key))); - loot.setRandomDurability(config.getBoolean(key + ".random-durability", false)); - if (config.contains(key + ".size")) { - String[] size = StringUtils.split(config.getString(key + ".size", "1~10"), "~"); + lootSection.contains("nick") ? lootSection.getString("nick") : AdventureUtil.replaceLegacy(lootSection.getString("display.name", key)), + material.contains(":") ? material : key, + getMiniGames(lootSection), + lootSection.getInt("weight",10), + lootSection.getBoolean("show-in-fishfinder", true), + lootSection.getDouble("score"), + lootSection.getBoolean("random-durability", false) + ); + + if (lootSection.contains("size")) { + String[] size = StringUtils.split(lootSection.getString("size", "1~10"), "~"); if (size.length != 2) { AdventureUtil.consoleMessage("[CustomFishing] Wrong size found at " + key); continue; } loot.setSize(size); } - if (config.contains(key + ".price")) { - loot.setBasicPrice((float) config.getDouble(key + ".price.base", 0)); - loot.setSizeBonus((float) config.getDouble(key + ".price.bonus", 0)); + if (lootSection.contains("price")) { + loot.setBasicPrice((float) lootSection.getDouble("price.base", 0)); + loot.setSizeBonus((float) lootSection.getDouble("price.bonus", 0)); } - if (config.contains(key + ".random-enchantments")){ + if (lootSection.contains("random-enchantments")) { List randomEnchants = new ArrayList<>(); - config.getConfigurationSection(key + ".random-enchantments").getValues(false).forEach((order, enchant) -> { - if (enchant instanceof MemorySection memorySection){ - LeveledEnchantment enchantment = new LeveledEnchantment(NamespacedKey.fromString(memorySection.getString("enchant")), memorySection.getInt("level")); - enchantment.setChance(memorySection.getDouble("chance")); - randomEnchants.add(enchantment); + ConfigurationSection enchantSection = lootSection.getConfigurationSection("random-enchantments"); + if (enchantSection != null) { + for (Map.Entry entry : enchantSection.getValues(false).entrySet()) { + if (entry.getValue() instanceof MemorySection memorySection){ + LeveledEnchantment enchantment = new LeveledEnchantment(NamespacedKey.fromString(memorySection.getString("enchant", "minecraft:sharpness")), memorySection.getInt("level")); + enchantment.setChance(memorySection.getDouble("chance")); + randomEnchants.add(enchantment); + } } - }); + } loot.setRandomEnchants(randomEnchants.toArray(new LeveledEnchantment[0])); } - setActionsAndRequirements(config, loot, key); - if (config.getBoolean(key + ".in-lava", false)) { - LAVALOOTS.put(key, loot); - } else { - WATERLOOTS.put(key, loot); - } - // Construct ItemStack - if (material.contains(":")) { - continue; - } - Item item = new Item(Material.valueOf(material.toUpperCase()), key); - BonusManager.setItemProperties(config, key, item); - if (item.getMaterial() == Material.AIR) LOOTITEMS.put(key, new ItemStack(Material.AIR)); - else LOOTITEMS.put(key, ItemStackUtil.getFromItem(item)); + + setActions(lootSection, loot); + setRequirements(lootSection.getConfigurationSection("requirements"), loot); + + if (lootSection.getBoolean("in-lava", false)) lavaLoots.put(key, loot); + else waterLoots.put(key, loot); + + if (material.contains(":")) continue; + + Item item = new Item(lootSection, key); + if (item.getMaterial() == Material.AIR) lootItems.put(key, new ItemStack(Material.AIR)); + else lootItems.put(key, ItemStackUtil.getFromItem(item)); } } } - private void setActionsAndRequirements(YamlConfiguration config, Loot loot, String key) { + private void setActions(ConfigurationSection section, Loot loot) { + loot.setSuccessActions(getActions(section.getConfigurationSection("action.success"), loot.getNick())); + loot.setFailureActions(getActions(section.getConfigurationSection("action.failure"), loot.getNick())); + loot.setHookActions(getActions(section.getConfigurationSection("action.hook"), loot.getNick())); + loot.setConsumeActions(getActions(section.getConfigurationSection("action.consume"), loot.getNick())); + } - if (config.contains(key + ".layout")) { - List layoutList = new ArrayList<>(); - for (String layoutName : config.getStringList(key + ".layout")) { - Layout layout = LayoutManager.LAYOUTS.get(layoutName); - if (layout == null) { - AdventureUtil.consoleMessage("[CustomFishing] Bar " + layoutName + " doesn't exist"); - continue; + private void setRequirements(ConfigurationSection section, Loot loot) { + loot.setRequirements(getRequirements(section)); + } + + private ActionInterface[] getActions(ConfigurationSection section, String nick) { + List actions = new ArrayList<>(); + if (section != null) { + for (String action : section.getKeys(false)) { + switch (action) { + case "message" -> actions.add(new MessageActionImpl(section.getStringList(action).toArray(new String[0]), nick)); + case "command" -> actions.add(new CommandActionImpl(section.getStringList(action).toArray(new String[0]), nick)); + case "exp" -> actions.add(new VanillaXPImpl(section.getInt(action), false)); + case "mending" -> actions.add(new VanillaXPImpl(section.getInt(action), true)); + case "skill-xp" -> actions.add(new SkillXPImpl(section.getInt(action))); + case "sound" -> actions.add(new SoundActionImpl( + section.getString(action + ".source"), + section.getString(action + ".key"), + (float) section.getDouble(action + ".volume"), + (float) section.getDouble(action + ".pitch") + )); + case "potion-effect" -> { + PotionEffectType type = PotionEffectType.getByName(section.getString(action + ".type", "BLINDNESS").toUpperCase()); + if (type == null) AdventureUtil.consoleMessage("[CustomFishing] Potion effect " + section.getString(action + ".type", "BLINDNESS") + " doesn't exists"); + actions.add(new PotionEffectImpl( + new PotionEffect( + type == null ? PotionEffectType.LUCK : type, + section.getInt(action + ".duration"), + section.getInt(action + ".amplifier") + ) + )); + } } - layoutList.add(layout); } - loot.setLayout(layoutList.toArray(new Layout[0])); } - loot.setScore(config.getDouble(key + ".score", 0)); - loot.setShowInFinder(config.getBoolean(key + ".show-in-fishfinder", true)); + return actions.toArray(new ActionInterface[0]); + } - if (config.contains(key + ".group")) loot.setGroup(config.getString(key + ".group")); - // Set actions - List successActions = new ArrayList<>(); - if (config.contains(key + ".action.success.message")) successActions.add(new MessageActionImpl(config.getStringList(key + ".action.success.message").toArray(new String[0]), loot.getNick())); - if (config.contains(key + ".action.success.command")) successActions.add(new CommandActionImpl(config.getStringList(key + ".action.success.command").toArray(new String[0]), loot.getNick())); - if (config.contains(key + ".action.success.exp")) successActions.add(new VanillaXPImpl(config.getInt(key + ".action.success.exp"), false)); - if (config.contains(key + ".action.success.mending")) successActions.add(new VanillaXPImpl(config.getInt(key + ".action.success.mending"), true)); - if (config.contains(key + ".action.success.skill-xp")) successActions.add(new SkillXPImpl(config.getInt(key + ".action.success.skill-xp"))); - if (config.contains(key + ".action.success.sound")) successActions.add(new SoundActionImpl(config.getString(key + ".action.success.sound"))); - loot.setSuccessActions(successActions.toArray(new ActionInterface[0])); - - List failureActions = new ArrayList<>(); - if (config.contains(key + ".action.failure.message")) failureActions.add(new MessageActionImpl(config.getStringList(key + ".action.failure.message").toArray(new String[0]), loot.getNick())); - if (config.contains(key + ".action.failure.command")) failureActions.add(new CommandActionImpl(config.getStringList(key + ".action.failure.command").toArray(new String[0]), loot.getNick())); - if (config.contains(key + ".action.failure.exp")) failureActions.add(new VanillaXPImpl(config.getInt(key + ".action.failure.exp"), false)); - if (config.contains(key + ".action.failure.mending")) failureActions.add(new VanillaXPImpl(config.getInt(key + ".action.failure.mending"), true)); - if (config.contains(key + ".action.failure.skill-xp")) failureActions.add(new SkillXPImpl(config.getInt(key + ".action.failure.skill-xp"))); - if (config.contains(key + ".action.failure.sound")) failureActions.add(new SoundActionImpl(config.getString(key + ".action.failure.sound"))); - loot.setFailureActions(failureActions.toArray(new ActionInterface[0])); - - List hookActions = new ArrayList<>(); - if (config.contains(key + ".action.hook.message")) hookActions.add(new MessageActionImpl(config.getStringList(key + ".action.hook.message").toArray(new String[0]), loot.getNick())); - if (config.contains(key + ".action.hook.command")) hookActions.add(new CommandActionImpl(config.getStringList(key + ".action.hook.command").toArray(new String[0]), loot.getNick())); - if (config.contains(key + ".action.hook.exp")) hookActions.add(new VanillaXPImpl(config.getInt(key + ".action.hook.exp"), false)); - if (config.contains(key + ".action.hook.mending")) hookActions.add(new VanillaXPImpl(config.getInt(key + ".action.hook.mending"), true)); - if (config.contains(key + ".action.hook.skill-xp")) hookActions.add(new SkillXPImpl(config.getInt(key + ".action.hook.skill-xp"))); - if (config.contains(key + ".action.hook.sound")) hookActions.add(new SoundActionImpl(config.getString(key + ".action.hook.sound"))); - loot.setHookActions(hookActions.toArray(new ActionInterface[0])); - - if (config.contains(key + ".requirements")){ - List requirements = new ArrayList<>(); - config.getConfigurationSection(key + ".requirements").getKeys(false).forEach(requirement -> { - switch (requirement){ - case "weather" -> requirements.add(new WeatherImpl(config.getStringList(key + ".requirements.weather"))); - case "ypos" -> requirements.add(new YPosImpl(config.getStringList(key + ".requirements.ypos"))); - case "season" -> requirements.add(new SeasonImpl(config.getStringList(key + ".requirements.season"))); - case "world" -> requirements.add(new WorldImpl(config.getStringList(key + ".requirements.world"))); - case "biome" -> requirements.add(new BiomeImpl(config.getStringList(key + ".requirements.biome"))); - case "permission" -> requirements.add(new PermissionImpl(config.getString(key + ".requirements.permission"))); - case "time" -> requirements.add(new TimeImpl(config.getStringList(key + ".requirements.time"))); - case "skill-level" -> requirements.add(new SkillLevelImpl(config.getInt(key + ".requirements.skill-level"))); - case "papi-condition" -> requirements.add(new CustomPapi(config.getConfigurationSection(key + ".requirements.papi-condition").getValues(false))); + private RequirementInterface[] getRequirements(ConfigurationSection section) { + List requirements = new ArrayList<>(); + if (section != null) { + for (String type : section.getKeys(false)) { + switch (type) { + case "weather" -> requirements.add(new WeatherImpl(section.getStringList(type))); + case "ypos" -> requirements.add(new YPosImpl(section.getStringList(type))); + case "season" -> requirements.add(new SeasonImpl(section.getStringList(type))); + case "world" -> requirements.add(new WorldImpl(section.getStringList(type))); + case "permission" -> requirements.add(new PermissionImpl(section.getString(type))); + case "time" -> requirements.add(new TimeImpl(section.getStringList(type))); + case "skill-level" -> requirements.add(new SkillLevelImpl(section.getInt(type))); + case "papi-condition" -> requirements.add(new CustomPapi(Objects.requireNonNull(section.getConfigurationSection(type)).getValues(false))); } - }); - loot.setRequirements(requirements.toArray(new RequirementInterface[0])); + } } + return requirements.toArray(new RequirementInterface[0]); + } + + private MiniGameConfig[] getMiniGames(ConfigurationSection section) { + String[] games = section.getStringList("mini-game").size() == 0 ? new String[]{section.getString("mini-game", null)} : section.getStringList("mini-game").toArray(new String[0]); + MiniGameConfig[] gameConfigs = new MiniGameConfig[games.length]; + for (int i = 0, size = games.length; i < size; i++) { + if (games[i] == null) { + return null; + } + MiniGameConfig gameConfig = plugin.getBarMechanicManager().getGameConfig(games[i]); + if (gameConfig == null) { + AdventureUtil.consoleMessage("[CustomFishing] Mini game " + games[i] + " doesn't exist"); + return null; + } + gameConfigs[i] = gameConfig; + } + return gameConfigs; + } + + public HashMap getWaterLoots() { + return waterLoots; + } + + public HashMap getLavaLoots() { + return lavaLoots; + } + + public ArrayList getAllLoots() { + ArrayList loots = new ArrayList<>(getWaterLoots().values()); + loots.addAll(getLavaLoots().values()); + return loots; } } diff --git a/src/main/java/net/momirealms/customfishing/manager/OffsetManager.java b/src/main/java/net/momirealms/customfishing/manager/OffsetManager.java new file mode 100644 index 00000000..afa21718 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/OffsetManager.java @@ -0,0 +1,135 @@ +package net.momirealms.customfishing.manager; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.object.Function; +import net.momirealms.customfishing.util.ConfigUtil; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; + +public class OffsetManager extends Function { + + private CustomFishing plugin; + private final String[] negative; + private final String[] positive; + private String font; + + public OffsetManager(CustomFishing plugin) { + this.plugin = plugin; + this.negative = new String[8]; + this.positive = new String[8]; + } + + @Override + public void load() { + loadConfig(); + } + + public String getFont() { + return font; + } + + private void loadConfig() { + YamlConfiguration config = ConfigUtil.getConfig("config.yml"); + ConfigurationSection section = config.getConfigurationSection("other-settings.offset-characters"); + if (section != null) { + font = section.getString("font", "customfishing:offset_chars"); + positive[0] = section.getString("1"); + positive[1] = section.getString("2"); + positive[2] = section.getString("4"); + positive[3] = section.getString("8"); + positive[4] = section.getString("16"); + positive[5] = section.getString("32"); + positive[6] = section.getString("64"); + positive[7] = section.getString("128"); + negative[0] = section.getString("-1"); + negative[1] = section.getString("-2"); + negative[2] = section.getString("-4"); + negative[3] = section.getString("-8"); + negative[4] = section.getString("-16"); + negative[5] = section.getString("-32"); + negative[6] = section.getString("-64"); + negative[7] = section.getString("-128"); + } + } + + public String getShortestNegChars(int n) { + StringBuilder stringBuilder = new StringBuilder(); + while (n >= 128) { + stringBuilder.append(negative[7]); + n -= 128; + } + if (n - 64 >= 0) { + stringBuilder.append(negative[6]); + n -= 64; + } + if (n - 32 >= 0) { + stringBuilder.append(negative[5]); + n -= 32; + } + if (n - 16 >= 0) { + stringBuilder.append(negative[4]); + n -= 16; + } + if (n - 8 >= 0) { + stringBuilder.append(negative[3]); + n -= 8; + } + if (n - 4 >= 0) { + stringBuilder.append(negative[2]); + n -= 4; + } + if (n - 2 >= 0) { + stringBuilder.append(negative[1]); + n -= 2; + } + if (n - 1 >= 0) { + stringBuilder.append(negative[0]); + } + return stringBuilder.toString(); + } + + public String getShortestPosChars(int n) { + StringBuilder stringBuilder = new StringBuilder(); + while (n >= 128) { + stringBuilder.append(positive[7]); + n -= 128; + } + if (n - 64 >= 0) { + stringBuilder.append(positive[6]); + n -= 64; + } + if (n - 32 >= 0) { + stringBuilder.append(positive[5]); + n -= 32; + } + if (n - 16 >= 0) { + stringBuilder.append(positive[4]); + n -= 16; + } + if (n - 8 >= 0) { + stringBuilder.append(positive[3]); + n -= 8; + } + if (n - 4 >= 0) { + stringBuilder.append(positive[2]); + n -= 4; + } + if (n - 2 >= 0) { + stringBuilder.append(positive[1]); + n -= 2; + } + if (n - 1 >= 0) { + stringBuilder.append(positive[0]); + } + return stringBuilder.toString(); + } + + public String getOffsetChars(int n) { + if (n > 0) { + return getShortestPosChars(n); + } + else { + return getShortestNegChars(-n); + } + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/SellManager.java b/src/main/java/net/momirealms/customfishing/manager/SellManager.java index c94644ab..260e0d73 100644 --- a/src/main/java/net/momirealms/customfishing/manager/SellManager.java +++ b/src/main/java/net/momirealms/customfishing/manager/SellManager.java @@ -22,8 +22,6 @@ import com.comphenix.protocol.reflect.StructureModifier; import com.comphenix.protocol.wrappers.WrappedChatComponent; import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTItem; -import net.Indyuce.mmoitems.MMOItems; -import net.Indyuce.mmoitems.api.item.mmoitem.MMOItem; import net.kyori.adventure.key.Key; import net.kyori.adventure.sound.Sound; import net.kyori.adventure.text.minimessage.MiniMessage; @@ -31,12 +29,13 @@ import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.api.event.SellFishEvent; import net.momirealms.customfishing.data.PlayerSellData; +import net.momirealms.customfishing.data.storage.DataStorageInterface; +import net.momirealms.customfishing.fishing.loot.Item; import net.momirealms.customfishing.integration.papi.PlaceholderManager; import net.momirealms.customfishing.listener.InventoryListener; -import net.momirealms.customfishing.listener.SimpleListener; +import net.momirealms.customfishing.listener.JoinQuitListener; import net.momirealms.customfishing.listener.WindowPacketListener; import net.momirealms.customfishing.object.Function; -import net.momirealms.customfishing.object.loot.Item; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ConfigUtil; import net.momirealms.customfishing.util.ItemStackUtil; @@ -61,7 +60,8 @@ public class SellManager extends Function { private final WindowPacketListener windowPacketListener; private final InventoryListener inventoryListener; - private final SimpleListener simpleListener; + private final JoinQuitListener joinQuitListener; + private final CustomFishing plugin; public static String formula; public static String title; public static int guiSize; @@ -88,11 +88,12 @@ public class SellManager extends Function { private final HashMap inventoryCache; private final HashMap playerCache; - public SellManager() { + public SellManager(CustomFishing plugin) { + this.plugin = plugin; this.windowPacketListener = new WindowPacketListener(this); this.inventoryListener = new InventoryListener(this); this.inventoryCache = new HashMap<>(); - this.simpleListener = new SimpleListener(this); + this.joinQuitListener = new JoinQuitListener(this); this.playerCache = new HashMap<>(); } @@ -102,9 +103,9 @@ public class SellManager extends Function { guiItems = new HashMap<>(); vanillaPrices = new HashMap<>(); loadConfig(); - CustomFishing.protocolManager.addPacketListener(windowPacketListener); - Bukkit.getPluginManager().registerEvents(inventoryListener, CustomFishing.plugin); - Bukkit.getPluginManager().registerEvents(simpleListener, CustomFishing.plugin); + CustomFishing.getProtocolManager().addPacketListener(windowPacketListener); + Bukkit.getPluginManager().registerEvents(inventoryListener, plugin); + Bukkit.getPluginManager().registerEvents(joinQuitListener, plugin); } @Override @@ -113,14 +114,16 @@ public class SellManager extends Function { player.closeInventory(); } this.inventoryCache.clear(); - CustomFishing.protocolManager.removePacketListener(windowPacketListener); + CustomFishing.getProtocolManager().removePacketListener(windowPacketListener); HandlerList.unregisterAll(inventoryListener); - HandlerList.unregisterAll(simpleListener); + HandlerList.unregisterAll(joinQuitListener); } public void disable() { - for (Map.Entry entry : playerCache.entrySet()) {; - CustomFishing.plugin.getDataManager().getDataStorageInterface().saveSellCache(entry.getKey(), entry.getValue()); + unload(); + DataStorageInterface dataStorage = plugin.getDataManager().getDataStorageInterface(); + for (Map.Entry entry : playerCache.entrySet()) { + dataStorage.saveSellCache(entry.getKey(), entry.getValue()); } playerCache.clear(); } @@ -132,26 +135,26 @@ public class SellManager extends Function { public void savePlayerToFile(UUID uuid) { PlayerSellData sellData = playerCache.remove(uuid); if (sellData == null) return; - CustomFishing.plugin.getDataManager().getDataStorageInterface().saveSellCache(uuid, sellData); + plugin.getDataManager().getDataStorageInterface().saveSellCache(uuid, sellData); } @Override public void onQuit(Player player) { - Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.plugin, () -> { + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { savePlayerToFile(player.getUniqueId()); }); } @Override public void onJoin(Player player) { - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.plugin, () -> { + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { if (player == null || !player.isOnline()) return; - CustomFishing.plugin.getDataManager().getDataStorageInterface().loadSellCache(player); + plugin.getDataManager().getDataStorageInterface().loadSellCache(player); }, 20); } private void loadConfig() { - YamlConfiguration config = ConfigUtil.getConfig("sell-fish.yml"); + YamlConfiguration config = ConfigUtil.getConfig("sell-fish-gui.yml"); formula = config.getString("price-formula", "{base} + {bonus} * {size}"); sellLimitation = config.getBoolean("sell-limitation.enable", false); upperLimit = config.getInt("sell-limitation.upper-limit", 10000); @@ -163,34 +166,30 @@ public class SellManager extends Function { denyKey = config.contains("sounds.deny") ? Key.key(config.getString("sounds.deny")) : null; soundSource = Sound.Source.valueOf(config.getString("sounds.type","player").toUpperCase()); if (config.contains("decorative-icons")){ - config.getConfigurationSection("decorative-icons").getKeys(false).forEach(key -> { - Item item = new Item(Material.valueOf(config.getString("decorative-icons." + key + ".material", "PAPER").toUpperCase()), key); - if (config.contains("decorative-icons." + key + ".display.name")) item.setName(config.getString("decorative-icons." + key + ".display.name")); - if (config.contains("decorative-icons." + key + ".display.lore")) item.setLore(config.getStringList("decorative-icons." + key + ".display.lore")); - if (config.contains("decorative-icons." + key + ".custom-model-data")) item.setCustomModelData(config.getInt("decorative-icons." + key + ".custom-model-data")); - ItemStack itemStack = ItemStackUtil.getFromItem(item); - if (config.contains("decorative-icons." + key + ".slots")) { - for (int slot : config.getIntegerList("decorative-icons." + key + ".slots")) { - guiItems.put(slot - 1, itemStack); + ConfigurationSection dec_section = config.getConfigurationSection("decorative-icons"); + if (dec_section != null) { + for (String key : dec_section.getKeys(false)) { + ConfigurationSection item_section = dec_section.getConfigurationSection(key); + if (item_section == null) continue; + Item item = new Item(item_section, key); + ItemStack itemStack = ItemStackUtil.getFromItem(item); + if (item_section.contains("slots")) { + for (int slot : item_section.getIntegerList("slots")) { + guiItems.put(slot - 1, itemStack); + } } } - // for old version compatibility - if (config.contains("decorative-icons." + key + ".slot")) { - for (int slot : config.getIntegerList("decorative-icons." + key + ".slot")) { - guiItems.put(slot - 1, itemStack); - } - } - }); + } } - sellIcon = new Item(Material.valueOf(config.getString("functional-icons.sell.material", "PAPER").toUpperCase()), "sellIcon"); - if (config.contains("functional-icons.sell.display.name")) sellIcon.setName(config.getString("functional-icons.sell.display.name")); - if (config.contains("functional-icons.sell.display.lore")) sellIcon.setLore(config.getStringList("functional-icons.sell.display.lore")); - if (config.contains("functional-icons.sell.custom-model-data")) sellIcon.setCustomModelData(config.getInt("functional-icons.sell.custom-model-data")); - denyIcon = new Item(Material.valueOf(config.getString("functional-icons.deny.material", "PAPER").toUpperCase()), "denyIcon"); - if (config.contains("functional-icons.deny.display.name")) denyIcon.setName(config.getString("functional-icons.deny.display.name")); - if (config.contains("functional-icons.deny.display.lore")) denyIcon.setLore(config.getStringList("functional-icons.deny.display.lore")); - if (config.contains("functional-icons.deny.custom-model-data")) denyIcon.setCustomModelData(config.getInt("functional-icons.deny.custom-model-data")); + ConfigurationSection sellIconSection = config.getConfigurationSection("functional-icons.sell"); + if (sellIconSection != null) { + sellIcon = new Item(sellIconSection, "sellIcon"); + } + ConfigurationSection denyIconSection = config.getConfigurationSection("functional-icons.deny"); + if (denyIconSection != null) { + denyIcon = new Item(denyIconSection, "denyIcon"); + } for (int slot : config.getIntegerList("functional-icons.slots")) { guiItems.put(slot - 1, ItemStackUtil.getFromItem(sellIcon)); @@ -270,7 +269,7 @@ public class SellManager extends Function { if (sellData == null) { inventory.close(); - AdventureUtil.playerMessage(player, MessageManager.prefix + "Internal error, please contact the server owner"); + AdventureUtil.playerMessage(player, MessageManager.prefix + "Your data is not loaded! Try to rejoin the server"); AdventureUtil.consoleMessage("[CustomFishing] Unexpected issue, " + player.getName() + "'s sell-cache is not loaded!"); if (denyKey != null) AdventureUtil.playerSound(player, soundSource, denyKey, 1, 1); return; @@ -318,7 +317,7 @@ public class SellManager extends Function { } } if (update) { - Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.plugin, () -> { + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { ItemStack icon = ItemStackUtil.getFromItem(sellIcon.cloneWithPrice(getTotalPrice(getPlayerItems(inventory)))); for (int slot : functionIconSlots) { inventory.setItem(slot, icon); @@ -358,7 +357,7 @@ public class SellManager extends Function { private boolean hasEmptySlot(PlayerInventory inventory) { for (ItemStack itemStack : inventory.getStorageContents()) { - if (itemStack == null || itemStack.getType() == Material.AIR) return true; + if (itemStack.getType() == Material.AIR) return true; } return false; } @@ -399,33 +398,15 @@ public class SellManager extends Function { } private void doActions(Player player, float earnings, double remains) { - if (titleNotification != null) AdventureUtil.playerTitle( - player, - titleNotification.replace("{money}", String.format("%.2f", earnings)).replace("{remains}", sellLimitation ? String.format("%.2f", remains) : "unlimited"), - subtitleNotification.replace("{money}", String.format("%.2f", earnings)).replace("{remains}", sellLimitation ? String.format("%.2f", remains) : "unlimited"), - titleIn * 50, - titleStay * 50, - titleOut * 50 - ); - if (msgNotification != null) { - AdventureUtil.playerMessage(player, msgNotification.replace("{money}", String.format("%.2f", earnings)).replace("{remains}", sellLimitation ? String.format("%.2f", remains) : "unlimited")); - } - if (actionbarNotification != null) { - AdventureUtil.playerActionbar(player, actionbarNotification.replace("{money}", String.format("%.2f", earnings)).replace("{remains}", sellLimitation ? String.format("%.2f", remains) : "unlimited")); - } - if (commands != null) { - for (String cmd : commands) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd.replace("{player}", player.getName()).replace("{money}", String.format("%.2f", earnings)).replace("{remains}", sellLimitation ? String.format("%.2f", remains) : "unlimited")); - } - } - if (ConfigManager.logEarning) { - AdventureUtil.consoleMessage("[CustomFishing] Log: " + player.getName() + " earns " + String.format("%.2f", earnings) + " from selling fish"); - } + if (titleNotification != null) AdventureUtil.playerTitle(player, titleNotification.replace("{money}", String.format("%.2f", earnings)).replace("{remains}", sellLimitation ? String.format("%.2f", remains) : "unlimited"), subtitleNotification.replace("{money}", String.format("%.2f", earnings)).replace("{remains}", sellLimitation ? String.format("%.2f", remains) : "unlimited"), titleIn * 50, titleStay * 50, titleOut * 50); + if (msgNotification != null) AdventureUtil.playerMessage(player, msgNotification.replace("{money}", String.format("%.2f", earnings)).replace("{remains}", sellLimitation ? String.format("%.2f", remains) : "unlimited")); + if (actionbarNotification != null) AdventureUtil.playerActionbar(player, actionbarNotification.replace("{money}", String.format("%.2f", earnings)).replace("{remains}", sellLimitation ? String.format("%.2f", remains) : "unlimited")); + if (ConfigManager.logEarning) AdventureUtil.consoleMessage("[CustomFishing] Log: " + player.getName() + " earns " + String.format("%.2f", earnings) + " from selling fish"); if (successKey != null) AdventureUtil.playerSound(player, soundSource, successKey, 1, 1); - if (ConfigManager.vaultHook) { - assert CustomFishing.plugin.getIntegrationManager().getVaultHook() != null; - CustomFishing.plugin.getIntegrationManager().getVaultHook().getEconomy().depositPlayer(player, earnings); - } + if (plugin.getIntegrationManager().getVaultHook() != null) plugin.getIntegrationManager().getVaultHook().getEconomy().depositPlayer(player, earnings); + if (commands != null) + for (String cmd : commands) + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd.replace("{player}", player.getName()).replace("{money}", String.format("%.2f", earnings)).replace("{remains}", sellLimitation ? String.format("%.2f", remains) : "unlimited")); } @Override @@ -433,7 +414,7 @@ public class SellManager extends Function { StructureModifier wrappedChatComponentStructureModifier = packet.getChatComponents(); WrappedChatComponent component = wrappedChatComponentStructureModifier.getValues().get(0); if (component.getJson().equals("{\"text\":\"{CustomFishing_Sell}\"}")) { - PlaceholderManager placeholderManager = CustomFishing.plugin.getIntegrationManager().getPlaceholderManager(); + PlaceholderManager placeholderManager = plugin.getIntegrationManager().getPlaceholderManager(); String text = SellManager.title.replace("{player}", player.getName()); placeholderManager.parse(player, text); wrappedChatComponentStructureModifier.write(0, diff --git a/src/main/java/net/momirealms/customfishing/manager/TotemManager.java b/src/main/java/net/momirealms/customfishing/manager/TotemManager.java index f6198403..e1bb1cdb 100644 --- a/src/main/java/net/momirealms/customfishing/manager/TotemManager.java +++ b/src/main/java/net/momirealms/customfishing/manager/TotemManager.java @@ -18,16 +18,16 @@ package net.momirealms.customfishing.manager; import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.fishing.requirements.*; +import net.momirealms.customfishing.fishing.totem.CorePos; +import net.momirealms.customfishing.fishing.totem.FinalModel; +import net.momirealms.customfishing.fishing.totem.OriginalModel; +import net.momirealms.customfishing.fishing.totem.TotemConfig; import net.momirealms.customfishing.integration.BlockInterface; import net.momirealms.customfishing.object.Function; import net.momirealms.customfishing.object.action.ActionInterface; import net.momirealms.customfishing.object.action.CommandActionImpl; import net.momirealms.customfishing.object.action.MessageActionImpl; -import net.momirealms.customfishing.object.requirements.*; -import net.momirealms.customfishing.object.totem.CorePos; -import net.momirealms.customfishing.object.totem.FinalModel; -import net.momirealms.customfishing.object.totem.OriginalModel; -import net.momirealms.customfishing.object.totem.TotemConfig; import net.momirealms.customfishing.util.AdventureUtil; import net.momirealms.customfishing.util.ConfigUtil; import net.momirealms.customfishing.util.LocationUtils; @@ -37,6 +37,7 @@ import org.bukkit.Particle; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashMap; @@ -47,41 +48,77 @@ public class TotemManager extends Function { private final CustomFishing plugin; - public static HashMap TOTEMS; - public static HashMap> CORES; - public static HashMap BLOCKS; - public static HashMap INVERTED; + private final HashMap totems; + private final HashMap> cores; + private final HashMap blockIDs; + private final HashMap invertedIDs; public TotemManager(CustomFishing plugin) { this.plugin = plugin; + totems = new HashMap<>(); + cores = new HashMap<>(); + blockIDs = new HashMap<>(); + invertedIDs = new HashMap<>(); } @Override public void unload() { - if (TOTEMS != null) TOTEMS.clear(); - if (CORES != null) CORES.clear(); - if (BLOCKS != null) BLOCKS.clear(); - if (INVERTED != null) INVERTED.clear(); + totems.clear(); + cores.clear(); + blockIDs.clear(); + invertedIDs.clear(); } @Override public void load(){ - TOTEMS = new HashMap<>(); - CORES = new HashMap<>(); - BLOCKS = new HashMap<>(); - INVERTED = new HashMap<>(); loadBlocks(); loadTotems(); } + @Nullable + public TotemConfig getTotem(String key) { + return totems.get(key); + } + + public HashMap getTotems() { + return totems; + } + + @Nullable + public List getTotemsByCoreID(String core) { + return cores.get(core); + } + + public HashMap> getCores() { + return cores; + } + + @Nullable + public String getBlockID(String block) { + return blockIDs.get(block); + } + + public HashMap getBlockIDs() { + return blockIDs; + } + + @Nullable + public String getInvertedBlock(String id) { + return invertedIDs.get(id); + } + + public HashMap getInvertedIDs() { + return invertedIDs; + } + private void loadBlocks() { - YamlConfiguration config = ConfigUtil.getConfig("totem-blocks.yml"); - config.getKeys(false).forEach(key -> BLOCKS.put(key, config.getString(key))); - config.getKeys(false).forEach(key -> INVERTED.put(config.getString(key), key)); + YamlConfiguration config = ConfigUtil.getConfig("totem-blocks/default.yml"); + config.getKeys(false).forEach(key -> blockIDs.put(key, config.getString(key))); + config.getKeys(false).forEach(key -> invertedIDs.put(config.getString(key), key)); } private void loadTotems() { - YamlConfiguration config = ConfigUtil.getConfig("totems.yml"); + YamlConfiguration config = ConfigUtil.getConfig("totems/default.yml"); for (String key : config.getKeys(false)) { List cores = config.getStringList(key + ".core"); List flat = config.getStringList(key + ".layer.1"); @@ -144,13 +181,13 @@ public class TotemManager extends Function { config.getInt(key + ".radius", 16), config.getInt(key + ".duration", 300), Particle.valueOf(config.getString(key + ".particle", "SPELL_MOB").toUpperCase()), - BonusManager.getBonus(config, key) + EffectManager.getEffect(config.getConfigurationSection(key + ".modifier")) ); List actionList = new ArrayList<>(); List nearActionList = new ArrayList<>(); if (config.contains(key + ".action")) { - for (String action : config.getConfigurationSection(key + ".action").getKeys(false)) { + for (String action : Objects.requireNonNull(config.getConfigurationSection(key + ".action")).getKeys(false)) { switch (action) { case "commands-activator" -> actionList.add(new CommandActionImpl(config.getStringList(key + ".action." + action).toArray(new String[0]), null)); case "commands-nearby-players" -> nearActionList.add(new CommandActionImpl(config.getStringList(key + ".action." + action).toArray(new String[0]), null)); @@ -164,7 +201,7 @@ public class TotemManager extends Function { if (config.contains(key + ".requirements")) { List requirements = new ArrayList<>(); - config.getConfigurationSection(key + ".requirements").getKeys(false).forEach(requirement -> { + Objects.requireNonNull(config.getConfigurationSection(key + ".requirements")).getKeys(false).forEach(requirement -> { switch (requirement){ case "weather" -> requirements.add(new WeatherImpl(config.getStringList(key + ".requirements.weather"))); case "ypos" -> requirements.add(new YPosImpl(config.getStringList(key + ".requirements.ypos"))); @@ -202,20 +239,20 @@ public class TotemManager extends Function { totem.setPotionEffects(potionEffectList.toArray(new PotionEffect[0])); } - TOTEMS.put(key, totem); + totems.put(key, totem); for (String core : cores) { - if (CORES.get(core) == null){ + if (this.cores.get(core) == null){ List totems = new ArrayList<>(); totems.add(totem); - CORES.put(core, totems); + this.cores.put(core, totems); } else { - CORES.get(core).add(totem); + this.cores.get(core).add(totem); } } } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + TOTEMS.size() + " totems"); + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + totems.size() + " totem(s)"); } private CorePos getCorePos(List cores, CorePos corePos, OriginalModel originalModel, int k, int j, int i, String content) { @@ -233,7 +270,7 @@ public class TotemManager extends Function { public int checkLocationModel(OriginalModel model, Location location){ - BlockInterface blockInterface = CustomFishing.plugin.getIntegrationManager().getBlockInterface(); + BlockInterface blockInterface = plugin.getIntegrationManager().getBlockInterface(); CorePos corePos = model.getCorePos(); int xOffset = corePos.getX(); @@ -409,7 +446,7 @@ public class TotemManager extends Function { public void removeModel(FinalModel model, Location location, int direction) { - BlockInterface blockInterface = CustomFishing.plugin.getIntegrationManager().getBlockInterface(); + BlockInterface blockInterface = plugin.getIntegrationManager().getBlockInterface(); CorePos corePos = model.getCorePos(); int xOffset = corePos.getX(); diff --git a/src/main/java/net/momirealms/customfishing/object/TextCache.java b/src/main/java/net/momirealms/customfishing/object/DynamicText.java similarity index 88% rename from src/main/java/net/momirealms/customfishing/object/TextCache.java rename to src/main/java/net/momirealms/customfishing/object/DynamicText.java index 0f34d65e..51fbb9ff 100644 --- a/src/main/java/net/momirealms/customfishing/object/TextCache.java +++ b/src/main/java/net/momirealms/customfishing/object/DynamicText.java @@ -18,8 +18,8 @@ package net.momirealms.customfishing.object; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.competition.Competition; -import net.momirealms.customfishing.competition.ranking.RankingInterface; +import net.momirealms.customfishing.fishing.competition.Competition; +import net.momirealms.customfishing.fishing.competition.ranking.RankingInterface; import net.momirealms.customfishing.integration.papi.PlaceholderManager; import net.momirealms.customfishing.manager.MessageManager; import org.bukkit.entity.Player; @@ -28,20 +28,20 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -public class TextCache { +public class DynamicText { private final Player owner; private String originalValue; private String latestValue; private String[] ownerPlaceholders; - public TextCache(Player owner, String rawValue) { + public DynamicText(Player owner, String rawValue) { this.owner = owner; analyze(rawValue); } private void analyze(String value) { - List placeholdersOwner = new ArrayList<>(CustomFishing.plugin.getIntegrationManager().getPlaceholderManager().detectPlaceholders(value)); + List placeholdersOwner = new ArrayList<>(CustomFishing.getInstance().getIntegrationManager().getPlaceholderManager().detectPlaceholders(value)); String origin = value; for (String placeholder : placeholdersOwner) { origin = origin.replace(placeholder, "%s"); @@ -59,7 +59,7 @@ public class TextCache { public boolean update() { String string = originalValue; if (ownerPlaceholders.length != 0) { - PlaceholderManager placeholderManager = CustomFishing.plugin.getIntegrationManager().getPlaceholderManager(); + PlaceholderManager placeholderManager = CustomFishing.getInstance().getIntegrationManager().getPlaceholderManager(); if ("%s".equals(originalValue)) { string = placeholderManager.parse(owner, ownerPlaceholders[0]); } @@ -74,7 +74,7 @@ public class TextCache { RankingInterface ranking = Competition.currentCompetition.getRanking(); - string = string.replace("{rank}", Competition.currentCompetition.getPlayerRank(owner)) + string = string .replace("{rank}", Competition.currentCompetition.getPlayerRank(owner)) .replace("{time}", String.valueOf(Competition.currentCompetition.getRemainingTime())) .replace("{minute}", String.format("%02d", Competition.currentCompetition.getRemainingTime() / 60)) .replace("{second}",String.format("%02d", Competition.currentCompetition.getRemainingTime() % 60)) diff --git a/src/main/java/net/momirealms/customfishing/object/Function.java b/src/main/java/net/momirealms/customfishing/object/Function.java index bd335d1b..fc6d442f 100644 --- a/src/main/java/net/momirealms/customfishing/object/Function.java +++ b/src/main/java/net/momirealms/customfishing/object/Function.java @@ -24,6 +24,7 @@ import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerItemConsumeEvent; public class Function { @@ -62,4 +63,7 @@ public class Function { public void onBreakBlock(BlockBreakEvent event) { } + + public void onConsumeItem(PlayerItemConsumeEvent event) { + } } diff --git a/src/main/java/net/momirealms/customfishing/object/loot/LeveledEnchantment.java b/src/main/java/net/momirealms/customfishing/object/LeveledEnchantment.java similarity index 95% rename from src/main/java/net/momirealms/customfishing/object/loot/LeveledEnchantment.java rename to src/main/java/net/momirealms/customfishing/object/LeveledEnchantment.java index 6a2773d5..474dc42b 100644 --- a/src/main/java/net/momirealms/customfishing/object/loot/LeveledEnchantment.java +++ b/src/main/java/net/momirealms/customfishing/object/LeveledEnchantment.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.object.loot; +package net.momirealms.customfishing.object; import org.bukkit.NamespacedKey; diff --git a/src/main/java/net/momirealms/customfishing/object/action/CommandActionImpl.java b/src/main/java/net/momirealms/customfishing/object/action/CommandActionImpl.java index f5f9dd08..9f7c74ae 100644 --- a/src/main/java/net/momirealms/customfishing/object/action/CommandActionImpl.java +++ b/src/main/java/net/momirealms/customfishing/object/action/CommandActionImpl.java @@ -17,7 +17,6 @@ package net.momirealms.customfishing.object.action; -import net.momirealms.customfishing.CustomFishing; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.Nullable; @@ -32,7 +31,7 @@ public record CommandActionImpl(String[] commands, String nick) implements Actio @Override public void doOn(Player player, @Nullable Player anotherPlayer) { for (String command : commands) { - CustomFishing.plugin.getServer().dispatchCommand(Bukkit.getConsoleSender(), + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName()) .replace("{x}", String.valueOf(player.getLocation().getBlockX())) .replace("{y}", String.valueOf(player.getLocation().getBlockY())) diff --git a/src/main/java/net/momirealms/customfishing/object/action/SkillXPImpl.java b/src/main/java/net/momirealms/customfishing/object/action/SkillXPImpl.java index c2a0ea3b..c6e97279 100644 --- a/src/main/java/net/momirealms/customfishing/object/action/SkillXPImpl.java +++ b/src/main/java/net/momirealms/customfishing/object/action/SkillXPImpl.java @@ -25,7 +25,7 @@ public record SkillXPImpl(double amount) implements ActionInterface { @Override public void doOn(Player player, Player another) { - SkillInterface skillInterface = CustomFishing.plugin.getIntegrationManager().getSkillInterface(); + SkillInterface skillInterface = CustomFishing.getInstance().getIntegrationManager().getSkillInterface(); if (skillInterface == null) return; skillInterface.addXp(player, amount); } diff --git a/src/main/java/net/momirealms/customfishing/object/action/SoundActionImpl.java b/src/main/java/net/momirealms/customfishing/object/action/SoundActionImpl.java index 27ac83a3..95747af4 100644 --- a/src/main/java/net/momirealms/customfishing/object/action/SoundActionImpl.java +++ b/src/main/java/net/momirealms/customfishing/object/action/SoundActionImpl.java @@ -22,10 +22,10 @@ import net.kyori.adventure.sound.Sound; import net.momirealms.customfishing.util.AdventureUtil; import org.bukkit.entity.Player; -public record SoundActionImpl(String sound) implements ActionInterface { +public record SoundActionImpl(String source, String sound, float volume, float pitch) implements ActionInterface { @Override public void doOn(Player player, Player another) { - AdventureUtil.playerSound(player, Sound.Source.PLAYER, Key.key(sound), 1, 1); + AdventureUtil.playerSound(player, Sound.Source.valueOf(source.toUpperCase()), Key.key(sound), volume, pitch); } } diff --git a/src/main/java/net/momirealms/customfishing/object/fishing/FishingPlayer.java b/src/main/java/net/momirealms/customfishing/object/fishing/FishingPlayer.java deleted file mode 100644 index 845ecf2f..00000000 --- a/src/main/java/net/momirealms/customfishing/object/fishing/FishingPlayer.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.object.fishing; - -import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.manager.FishingManager; -import net.momirealms.customfishing.manager.MessageManager; -import net.momirealms.customfishing.util.AdventureUtil; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.PlayerInventory; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; - -public class FishingPlayer extends BukkitRunnable { - - private final long deadline; - private final Player player; - private final Difficulty difficulty; - private final FishingManager fishingManager; - private int progress; - private int internalTimer; - private final int size; - private boolean face; - private final String start; - private final String bar; - private final String pointer; - private final String offset; - private final String end; - private final String pointerOffset; - private final String title; - private final double[] successRate; - private final int range; - private final boolean isDouble; - private final double scoreMultiplier; - - public FishingPlayer(long deadline, Player player, Layout layout, Difficulty difficulty, FishingManager fishingManager, boolean isDouble, double scoreMultiplier) { - this.deadline = deadline; - this.player = player; - this.difficulty = difficulty; - this.fishingManager = fishingManager; - this.size = layout.getSize(); - this.start = layout.getStart(); - this.bar = layout.getBar(); - this.pointer = layout.getPointer(); - this.offset = layout.getOffset(); - this.end = layout.getEnd(); - this.pointerOffset = layout.getPointerOffset();; - this.title = layout.getTitle(); - this.range = layout.getRange(); - this.successRate = layout.getSuccessRate(); - this.isDouble = isDouble; - this.scoreMultiplier = scoreMultiplier; - } - - @Override - public void run() { - - if (System.currentTimeMillis() > deadline) { - AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.escape); - fishingManager.removeFishingPlayer(player); - cancel(); - return; - } - - if (internalTimer < difficulty.timer() - 1) { - internalTimer++; - return; - } else { - if (face) { - progress += difficulty.speed(); - } - else { - progress -= difficulty.speed(); - } - if (progress > size) { - face = !face; - progress = 2 * size - progress; - } - else if (progress < 0) { - face = !face; - progress = -progress; - } - } - StringBuilder stringBuilder = new StringBuilder(start + bar + pointerOffset); - for (int index = 0; index <= size; index++) { - if (index == progress){ - stringBuilder.append(pointer); - } else { - stringBuilder.append(offset); - } - } - stringBuilder.append(end); - AdventureUtil.playerTitle(player, title, stringBuilder.toString(),0,500,0); - - PlayerInventory playerInventory = player.getInventory(); - if (playerInventory.getItemInMainHand().getType() != Material.FISHING_ROD && playerInventory.getItemInOffHand().getType() != Material.FISHING_ROD) { - fishingManager.removeFishingPlayer(player); - cancel(); - Bukkit.getScheduler().runTask(CustomFishing.plugin, () -> player.removePotionEffect(PotionEffectType.SLOW)); - } - } - - - public boolean isSuccess() { - int last = progress / range; - return (Math.random() < successRate[last]); - } - - public boolean isDouble() { - return isDouble; - } - - public double getScoreMultiplier() { - return scoreMultiplier; - } -} diff --git a/src/main/java/net/momirealms/customfishing/object/fishing/Layout.java b/src/main/java/net/momirealms/customfishing/object/fishing/Layout.java deleted file mode 100644 index e4221355..00000000 --- a/src/main/java/net/momirealms/customfishing/object/fishing/Layout.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.object.fishing; - -public class Layout { - - private final int range; - private final double[] successRate; - private final int size; - private final String start; - private final String bar; - private final String pointer; - private final String offset; - private final String end; - private final String pointerOffset; - private final String title; - - public Layout(int range, double[] successRate, int size, String start, String bar, String pointer, String offset, String end, String pointerOffset, String title) { - this.range = range; - this.successRate = successRate; - this.size = size; - this.start = start; - this.bar = bar; - this.pointer = pointer; - this.offset = offset; - this.end = end; - this.pointerOffset = pointerOffset; - this.title = title; - } - - public int getRange() { - return range; - } - - public double[] getSuccessRate() { - return successRate; - } - - public int getSize() { - return size; - } - - public String getStart() { - return start; - } - - public String getBar() { - return bar; - } - - public String getPointer() { - return pointer; - } - - public String getOffset() { - return offset; - } - - public String getEnd() { - return end; - } - - public String getPointerOffset() { - return pointerOffset; - } - - public String getTitle() { - return title; - } -} diff --git a/src/main/java/net/momirealms/customfishing/object/fishing/Modifier.java b/src/main/java/net/momirealms/customfishing/object/fishing/Modifier.java deleted file mode 100644 index a5d8cc61..00000000 --- a/src/main/java/net/momirealms/customfishing/object/fishing/Modifier.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) <2022> - * - * 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 - * 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 net.momirealms.customfishing.object.fishing; - -public class Modifier { - - private int difficulty; - private double score; - private boolean willDouble; - - public void setDifficulty(int difficulty) { - this.difficulty = difficulty; - } - - public void setScore(double score) { - this.score = score; - } - - public void setWillDouble(boolean willDouble) { - this.willDouble = willDouble; - } - - public int getDifficulty() { - return difficulty; - } - - public double getScore() { - return score; - } - - public boolean isWillDouble() { - return willDouble; - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/SkillLevelImpl.java b/src/main/java/net/momirealms/customfishing/object/requirements/SkillLevelImpl.java deleted file mode 100644 index 40abaa38..00000000 --- a/src/main/java/net/momirealms/customfishing/object/requirements/SkillLevelImpl.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.momirealms.customfishing.object.requirements; - -import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.object.fishing.FishingCondition; - -public record SkillLevelImpl(int level) implements RequirementInterface { - - @Override - public boolean isConditionMet(FishingCondition fishingCondition) { - - return CustomFishing.plugin.getIntegrationManager().getSkillInterface().getLevel(fishingCondition.getPlayer()) >= level; - } -} diff --git a/src/main/java/net/momirealms/customfishing/util/AdventureUtil.java b/src/main/java/net/momirealms/customfishing/util/AdventureUtil.java index 20865726..802dfa6e 100644 --- a/src/main/java/net/momirealms/customfishing/util/AdventureUtil.java +++ b/src/main/java/net/momirealms/customfishing/util/AdventureUtil.java @@ -32,52 +32,102 @@ import java.time.Duration; public class AdventureUtil { + /** + * Send a message to a command sender + * @param sender sender + * @param s message + */ public static void sendMessage(CommandSender sender, String s) { if (sender instanceof Player player) playerMessage(player, s); else consoleMessage(s); } + /** + * Send a message to console + * @param s message + */ public static void consoleMessage(String s) { - Audience au = CustomFishing.adventure.sender(Bukkit.getConsoleSender()); + Audience au = CustomFishing.getAdventure().sender(Bukkit.getConsoleSender()); MiniMessage mm = MiniMessage.miniMessage(); Component parsed = mm.deserialize(replaceLegacy(s)); au.sendMessage(parsed); } + /** + * Send a message to a player + * @param player player + * @param s message + */ public static void playerMessage(Player player, String s) { - Audience au = CustomFishing.adventure.player(player); + Audience au = CustomFishing.getAdventure().player(player); MiniMessage mm = MiniMessage.miniMessage(); Component parsed = mm.deserialize(replaceLegacy(s)); au.sendMessage(parsed); } + /** + * Send a title to a player + * @param player player + * @param s1 title + * @param s2 subtitle + * @param in in (ms) + * @param duration duration (ms) + * @param out out (ms) + */ public static void playerTitle(Player player, String s1, String s2, int in, int duration, int out) { - Audience au = CustomFishing.adventure.player(player); + Audience au = CustomFishing.getAdventure().player(player); MiniMessage mm = MiniMessage.miniMessage(); Title.Times times = Title.Times.times(Duration.ofMillis(in), Duration.ofMillis(duration), Duration.ofMillis(out)); Title title = Title.title(mm.deserialize(replaceLegacy(s1)), mm.deserialize(replaceLegacy(s2)), times); au.showTitle(title); } + /** + * Send a title to a player + * @param player player + * @param s1 title + * @param s2 subtitle + * @param in in (ms) + * @param duration duration (ms) + * @param out out (ms) + */ public static void playerTitle(Player player, Component s1, Component s2, int in, int duration, int out) { - Audience au = CustomFishing.adventure.player(player); + Audience au = CustomFishing.getAdventure().player(player); Title.Times times = Title.Times.times(Duration.ofMillis(in), Duration.ofMillis(duration), Duration.ofMillis(out)); Title title = Title.title(s1, s2, times); au.showTitle(title); } + /** + * Send an actionbar to a player + * @param player player + * @param s actionbar + */ public static void playerActionbar(Player player, String s) { - Audience au = CustomFishing.adventure.player(player); + Audience au = CustomFishing.getAdventure().player(player); MiniMessage mm = MiniMessage.miniMessage(); au.sendActionBar(mm.deserialize(replaceLegacy(s))); } + /** + * Play a sound to a player + * @param player player + * @param source sound source + * @param key sound key + * @param volume volume + * @param pitch pitch + */ public static void playerSound(Player player, Sound.Source source, Key key, float volume, float pitch) { Sound sound = Sound.sound(key, source, volume, pitch); - Audience au = CustomFishing.adventure.player(player); + Audience au = CustomFishing.getAdventure().player(player); au.playSound(sound); } + /** + * Replace the legacy codes with MiniMessage Format + * @param s text + * @return MiniMessage format text + */ public static String replaceLegacy(String s) { StringBuilder stringBuilder = new StringBuilder(); char[] chars = s.replaceAll("&","§").toCharArray(); @@ -85,98 +135,29 @@ public class AdventureUtil { if (chars[i] == '§') { if (i + 1 < chars.length) { switch (chars[i+1]){ - case '0' -> { - i++; - stringBuilder.append(""); - } - case '1' -> { - i++; - stringBuilder.append(""); - } - case '2' -> { - i++; - stringBuilder.append(""); - } - case '3' -> { - i++; - stringBuilder.append(""); - } - case '4' -> { - i++; - stringBuilder.append(""); - } - case '5' -> { - i++; - stringBuilder.append(""); - } - case '6' -> { - i++; - stringBuilder.append(""); - } - case '7' -> { - i++; - stringBuilder.append(""); - } - case '8' -> { - i++; - stringBuilder.append(""); - } - case '9' -> { - i++; - stringBuilder.append(""); - } - case 'a' -> { - i++; - stringBuilder.append(""); - } - case 'b' -> { - i++; - stringBuilder.append(""); - } - case 'c' -> { - i++; - stringBuilder.append(""); - } - case 'd' -> { - i++; - stringBuilder.append(""); - } - case 'e' -> { - i++; - stringBuilder.append(""); - } - case 'f' -> { - i++; - stringBuilder.append(""); - } - case 'r' -> { - i++; - stringBuilder.append(""); - } - case 'l' -> { - i++; - stringBuilder.append(""); - } - case 'm' -> { - i++; - stringBuilder.append(""); - } - case 'o' -> { - i++; - stringBuilder.append(""); - } - case 'n' -> { - i++; - stringBuilder.append(""); - } - case 'x' -> { - stringBuilder.append("<#").append(chars[i+3]).append(chars[i+5]).append(chars[i+7]).append(chars[i+9]).append(chars[i+11]).append(chars[i+13]).append(">"); - i += 13; - } - case 'k' -> { - i++; - stringBuilder.append(""); - } + case '0' -> {i++;stringBuilder.append("");} + case '1' -> {i++;stringBuilder.append("");} + case '2' -> {i++;stringBuilder.append("");} + case '3' -> {i++;stringBuilder.append("");} + case '4' -> {i++;stringBuilder.append("");} + case '5' -> {i++;stringBuilder.append("");} + case '6' -> {i++;stringBuilder.append("");} + case '7' -> {i++;stringBuilder.append("");} + case '8' -> {i++;stringBuilder.append("");} + case '9' -> {i++;stringBuilder.append("");} + case 'a' -> {i++;stringBuilder.append("");} + case 'b' -> {i++;stringBuilder.append("");} + case 'c' -> {i++;stringBuilder.append("");} + case 'd' -> {i++;stringBuilder.append("");} + case 'e' -> {i++;stringBuilder.append("");} + case 'f' -> {i++;stringBuilder.append("");} + case 'r' -> {i++;stringBuilder.append("");} + case 'l' -> {i++;stringBuilder.append("");} + case 'm' -> {i++;stringBuilder.append("");} + case 'o' -> {i++;stringBuilder.append("");} + case 'n' -> {i++;stringBuilder.append("");} + case 'k' -> {i++;stringBuilder.append("");} + case 'x' -> {stringBuilder.append("<#").append(chars[i+3]).append(chars[i+5]).append(chars[i+7]).append(chars[i+9]).append(chars[i+11]).append(chars[i+13]).append(">");i += 13;} } } } diff --git a/src/main/java/net/momirealms/customfishing/util/ArmorStandUtil.java b/src/main/java/net/momirealms/customfishing/util/ArmorStandUtil.java index 2d354893..303caa7b 100644 --- a/src/main/java/net/momirealms/customfishing/util/ArmorStandUtil.java +++ b/src/main/java/net/momirealms/customfishing/util/ArmorStandUtil.java @@ -24,7 +24,6 @@ import com.google.common.collect.Lists; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.manager.BonusManager; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.EntityType; @@ -40,6 +39,7 @@ public class ArmorStandUtil { destroyPacket.getIntLists().write(0, List.of(id)); return destroyPacket; } + public static PacketContainer getSpawnPacket(int id, Location location) { PacketContainer entityPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY); entityPacket.getModifier().write(0, id); @@ -56,29 +56,28 @@ public class ArmorStandUtil { metaPacket.getIntegers().write(0, id); if (CustomFishing.getInstance().getVersionHelper().isVersionNewerThan1_19_R2()) { WrappedDataWatcher wrappedDataWatcher = createDataWatcher(); - List wrappedDataValueList = Lists.newArrayList(); - wrappedDataWatcher.getWatchableObjects().stream().filter(Objects::nonNull).forEach(entry -> { - final WrappedDataWatcher.WrappedDataWatcherObject dataWatcherObject = entry.getWatcherObject(); - wrappedDataValueList.add(new WrappedDataValue(dataWatcherObject.getIndex(), dataWatcherObject.getSerializer(), entry.getRawValue())); - }); - metaPacket.getDataValueCollectionModifier().write(0, wrappedDataValueList); + setValueList(metaPacket, wrappedDataWatcher); } else { metaPacket.getWatchableCollectionModifier().write(0, createDataWatcher().getWatchableObjects()); } return metaPacket; } + static void setValueList(PacketContainer metaPacket, WrappedDataWatcher wrappedDataWatcher) { + List wrappedDataValueList = Lists.newArrayList(); + wrappedDataWatcher.getWatchableObjects().stream().filter(Objects::nonNull).forEach(entry -> { + final WrappedDataWatcher.WrappedDataWatcherObject dataWatcherObject = entry.getWatcherObject(); + wrappedDataValueList.add(new WrappedDataValue(dataWatcherObject.getIndex(), dataWatcherObject.getSerializer(), entry.getRawValue())); + }); + metaPacket.getDataValueCollectionModifier().write(0, wrappedDataValueList); + } + public static PacketContainer getMetaPacket(int id, String text) { PacketContainer metaPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); metaPacket.getIntegers().write(0, id); if (CustomFishing.getInstance().getVersionHelper().isVersionNewerThan1_19_R2()) { WrappedDataWatcher wrappedDataWatcher = createDataWatcher(text); - List wrappedDataValueList = Lists.newArrayList(); - wrappedDataWatcher.getWatchableObjects().stream().filter(Objects::nonNull).forEach(entry -> { - final WrappedDataWatcher.WrappedDataWatcherObject dataWatcherObject = entry.getWatcherObject(); - wrappedDataValueList.add(new WrappedDataValue(dataWatcherObject.getIndex(), dataWatcherObject.getSerializer(), entry.getRawValue())); - }); - metaPacket.getDataValueCollectionModifier().write(0, wrappedDataValueList); + setValueList(metaPacket, wrappedDataWatcher); } else { metaPacket.getWatchableCollectionModifier().write(0, createDataWatcher(text).getWatchableObjects()); } @@ -118,14 +117,14 @@ public class ArmorStandUtil { } public static void sendAnimationToPlayer(Location location, Player player, String item, int time) { - int id = new Random().nextInt(100000000); - ItemStack itemStack = BonusManager.UTILITEMS.get(item); + int id = new Random().nextInt(Integer.MAX_VALUE); + ItemStack itemStack = CustomFishing.getInstance().getEffectManager().getUtilItem(item); if (itemStack == null) return; - CustomFishing.protocolManager.sendServerPacket(player, getSpawnPacket(id, location.clone().subtract(0,1,0))); - CustomFishing.protocolManager.sendServerPacket(player, getMetaPacket(id)); - CustomFishing.protocolManager.sendServerPacket(player, getEquipPacket(id, itemStack)); - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.plugin, () -> { - CustomFishing.protocolManager.sendServerPacket(player, getDestroyPacket(id)); + CustomFishing.getProtocolManager().sendServerPacket(player, getSpawnPacket(id, location.clone().subtract(0,1,0))); + CustomFishing.getProtocolManager().sendServerPacket(player, getMetaPacket(id)); + CustomFishing.getProtocolManager().sendServerPacket(player, getEquipPacket(id, itemStack)); + Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.getInstance(), () -> { + CustomFishing.getProtocolManager().sendServerPacket(player, getDestroyPacket(id)); }, time); } } \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/util/ConfigUtil.java b/src/main/java/net/momirealms/customfishing/util/ConfigUtil.java index ba1c5592..e250abac 100644 --- a/src/main/java/net/momirealms/customfishing/util/ConfigUtil.java +++ b/src/main/java/net/momirealms/customfishing/util/ConfigUtil.java @@ -25,52 +25,42 @@ import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings; import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings; import net.momirealms.customfishing.CustomFishing; import net.momirealms.customfishing.helper.Log; -import net.momirealms.customfishing.manager.ConfigManager; -import net.momirealms.customfishing.manager.MessageManager; import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; +import java.util.Objects; public class ConfigUtil { + /** + * Get a config by name + * @param configName config's name + * @return yaml + */ public static YamlConfiguration getConfig(String configName) { - File file = new File(CustomFishing.plugin.getDataFolder(), configName); - if (!file.exists()) CustomFishing.plugin.saveResource(configName, false); + File file = new File(CustomFishing.getInstance().getDataFolder(), configName); + if (!file.exists()) CustomFishing.getInstance().saveResource(configName, false); return YamlConfiguration.loadConfiguration(file); } - public static void reload() { - ConfigManager.load(); - MessageManager.load(); - CustomFishing.plugin.getLayoutManager().unload(); - CustomFishing.plugin.getLayoutManager().load(); - CustomFishing.plugin.getLootManager().unload(); - CustomFishing.plugin.getLootManager().load(); - CustomFishing.plugin.getBonusManager().unload(); - CustomFishing.plugin.getBonusManager().load(); - CustomFishing.plugin.getFishingManager().unload(); - CustomFishing.plugin.getFishingManager().load(); - CustomFishing.plugin.getCompetitionManager().unload(); - CustomFishing.plugin.getCompetitionManager().load(); - CustomFishing.plugin.getTotemManager().unload(); - CustomFishing.plugin.getTotemManager().load(); - CustomFishing.plugin.getIntegrationManager().unload(); - CustomFishing.plugin.getIntegrationManager().load(); - CustomFishing.plugin.getSellManager().unload(); - CustomFishing.plugin.getSellManager().load(); - CustomFishing.plugin.getBagDataManager().unload(); - CustomFishing.plugin.getBagDataManager().load(); - } - + /** + * Update config + * @param fileName config + */ public static void update(String fileName){ try { - YamlDocument.create(new File(CustomFishing.plugin.getDataFolder(), fileName), CustomFishing.plugin.getResource(fileName), GeneralSettings.DEFAULT, LoaderSettings.builder().setAutoUpdate(true).build(), DumperSettings.DEFAULT, UpdaterSettings.builder().setVersioning(new BasicVersioning("config-version")).build()); + YamlDocument.create(new File(CustomFishing.getInstance().getDataFolder(), fileName), Objects.requireNonNull(CustomFishing.getInstance().getResource(fileName)), GeneralSettings.DEFAULT, LoaderSettings.builder().setAutoUpdate(true).build(), DumperSettings.DEFAULT, UpdaterSettings.builder().setVersioning(new BasicVersioning("config-version")).build()); } catch (IOException e){ Log.warn(e.getMessage()); } } + /** + * Create a data file if not exists + * @param file file path + * @return yaml data + */ public static YamlConfiguration readData(File file) { if (!file.exists()) { try { diff --git a/src/main/java/net/momirealms/customfishing/util/FakeItemUtil.java b/src/main/java/net/momirealms/customfishing/util/FakeItemUtil.java index e91e1347..7a183d5f 100644 --- a/src/main/java/net/momirealms/customfishing/util/FakeItemUtil.java +++ b/src/main/java/net/momirealms/customfishing/util/FakeItemUtil.java @@ -2,9 +2,7 @@ package net.momirealms.customfishing.util; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedDataValue; import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.google.common.collect.Lists; import net.momirealms.customfishing.CustomFishing; import org.bukkit.Location; import org.bukkit.entity.EntityType; @@ -12,7 +10,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import java.util.List; -import java.util.Objects; import java.util.UUID; public class FakeItemUtil { @@ -39,12 +36,7 @@ public class FakeItemUtil { metaPacket.getIntegers().write(0, id); if (CustomFishing.getInstance().getVersionHelper().isVersionNewerThan1_19_R2()) { WrappedDataWatcher wrappedDataWatcher = createDataWatcher(itemStack); - List wrappedDataValueList = Lists.newArrayList(); - wrappedDataWatcher.getWatchableObjects().stream().filter(Objects::nonNull).forEach(entry -> { - final WrappedDataWatcher.WrappedDataWatcherObject dataWatcherObject = entry.getWatcherObject(); - wrappedDataValueList.add(new WrappedDataValue(dataWatcherObject.getIndex(), dataWatcherObject.getSerializer(), entry.getRawValue())); - }); - metaPacket.getDataValueCollectionModifier().write(0, wrappedDataValueList); + ArmorStandUtil.setValueList(metaPacket, wrappedDataWatcher); } else { metaPacket.getWatchableCollectionModifier().write(0, createDataWatcher(itemStack).getWatchableObjects()); } diff --git a/src/main/java/net/momirealms/customfishing/util/InventoryUtil.java b/src/main/java/net/momirealms/customfishing/util/InventoryUtil.java index 3e4c9fd4..4032f847 100644 --- a/src/main/java/net/momirealms/customfishing/util/InventoryUtil.java +++ b/src/main/java/net/momirealms/customfishing/util/InventoryUtil.java @@ -29,24 +29,25 @@ import java.io.IOException; public class InventoryUtil { + /** + * Converts itemStacks to base64 + * @param contents items + * @return base64 + */ @Nullable public static String toBase64(ItemStack[] contents) { boolean convert = false; - for (ItemStack content : contents) { if (content != null) { convert = true; break; } } - if (convert) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - dataOutput.writeInt(contents.length); - for (ItemStack itemStack : contents) { dataOutput.writeObject(itemStack); } @@ -60,6 +61,11 @@ public class InventoryUtil { return null; } + /** + * Get itemStacks from base64 + * @param base64 base64 + * @return itemStacks + */ @Nullable public static ItemStack[] getInventoryItems(String base64) { ItemStack[] itemStacks = null; @@ -80,7 +86,6 @@ public class InventoryUtil { } catch (IllegalArgumentException e) { return new ItemStack[]{}; } - BukkitObjectInputStream dataInput = null; ItemStack[] stacks = null; try { @@ -89,9 +94,7 @@ public class InventoryUtil { } catch (IOException e) { e.printStackTrace(); } - if (stacks == null) return new ItemStack[]{}; - for (int i = 0; i < stacks.length; i++) { try { stacks[i] = (ItemStack) dataInput.readObject(); @@ -105,11 +108,9 @@ public class InventoryUtil { return null; } } - try { dataInput.close(); } catch (IOException ignored) { - } return stacks; } diff --git a/src/main/java/net/momirealms/customfishing/util/ItemStackUtil.java b/src/main/java/net/momirealms/customfishing/util/ItemStackUtil.java index daa0e95d..4ed9412c 100644 --- a/src/main/java/net/momirealms/customfishing/util/ItemStackUtil.java +++ b/src/main/java/net/momirealms/customfishing/util/ItemStackUtil.java @@ -24,12 +24,10 @@ import de.tr7zw.changeme.nbtapi.iface.ReadWriteNBT; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.manager.BonusManager; -import net.momirealms.customfishing.manager.LootManager; -import net.momirealms.customfishing.object.loot.DroppedItem; -import net.momirealms.customfishing.object.loot.Item; -import net.momirealms.customfishing.object.loot.LeveledEnchantment; -import net.momirealms.customfishing.object.loot.Loot; +import net.momirealms.customfishing.fishing.loot.DroppedItem; +import net.momirealms.customfishing.fishing.loot.Item; +import net.momirealms.customfishing.fishing.loot.Loot; +import net.momirealms.customfishing.object.LeveledEnchantment; import org.bukkit.Material; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; @@ -45,8 +43,14 @@ import java.util.*; public class ItemStackUtil { + /** + * Build itemStack from item's config + * @param item item + * @return itemStack + */ public static ItemStack getFromItem(Item item) { ItemStack itemStack = new ItemStack(item.getMaterial()); + itemStack.setAmount(item.getAmount()); ItemMeta itemMeta = itemStack.getItemMeta(); if (item.getCustomModelData() != 0) itemMeta.setCustomModelData(item.getCustomModelData()); if (item.isUnbreakable()) itemMeta.setUnbreakable(true); @@ -93,6 +97,10 @@ public class ItemStackUtil { return nbtItem.getItem(); } + /** + * Get an itemStack with random durability + * @param itemStack itemStack + */ public static void addRandomDamage(ItemStack itemStack){ if (itemStack.getItemMeta() instanceof Damageable damageable){ damageable.setDamage((int) (itemStack.getType().getMaxDurability() * Math.random())); @@ -100,12 +108,22 @@ public class ItemStackUtil { } } + /** + * Adds owner tag + * @param itemStack itemStack + * @param name owner + */ public static void addOwner(ItemStack itemStack, String name){ NBTItem nbtItem = new NBTItem(itemStack); nbtItem.setString("M_Owner", name); itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); } + /** + * Add random enchantments + * @param itemStack itemStack + * @param enchantments enchantments + */ public static void addRandomEnchants(ItemStack itemStack, LeveledEnchantment[] enchantments){ ItemMeta itemMeta = itemStack.getItemMeta(); if (itemStack.getType() == Material.ENCHANTED_BOOK){ @@ -123,6 +141,13 @@ public class ItemStackUtil { } } + /** + * Add customFishing tags + * @param itemStack itemStack + * @param type type + * @param id id + * @return itemStack + */ public static ItemStack addIdentifier(ItemStack itemStack, String type, String id){ NBTItem nbtItem = new NBTItem(itemStack); NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing"); @@ -132,69 +157,60 @@ public class ItemStackUtil { return itemStack; } - public static void givePlayerLoot(Player player, String lootKey, int amount){ - Loot loot = LootManager.WATERLOOTS.get(lootKey); - if (loot == null) { - loot = LootManager.LAVALOOTS.get(lootKey); - if (loot == null) return; - } + public static void givePlayerLoot(Player player, String key, int amount){ + Loot loot = CustomFishing.getInstance().getLootManager().getLoot(key); if (!(loot instanceof DroppedItem droppedItem)) return; - ItemStack itemStack = CustomFishing.plugin.getFishingManager().getCustomFishingLootItemStack(droppedItem, player); + ItemStack itemStack = CustomFishing.getInstance().getFishingManager().getCustomFishingLootItemStack(droppedItem, player); if (itemStack.getType() == Material.AIR) return; itemStack.setAmount(amount); player.getInventory().addItem(itemStack); } public static void givePlayerRod(Player player, String rodKey, int amount){ - ItemStack itemStack = BonusManager.RODITEMS.get(rodKey); + ItemStack itemStack = CustomFishing.getInstance().getEffectManager().getRodItem(rodKey); + if (itemStack == null) return; for (int i = 0; i < amount; i++) { player.getInventory().addItem(itemStack); } } public static void givePlayerBait(Player player, String baitKey, int amount){ - ItemStack itemStack = BonusManager.BAITITEMS.get(baitKey); + ItemStack itemStack = CustomFishing.getInstance().getEffectManager().getBaitItem(baitKey); if (itemStack == null) return; itemStack.setAmount(amount); player.getInventory().addItem(itemStack); } public static void givePlayerUtil(Player player, String utilKey, int amount){ - ItemStack itemStack = BonusManager.UTILITEMS.get(utilKey); + ItemStack itemStack = CustomFishing.getInstance().getEffectManager().getUtilItem(utilKey); if (itemStack == null) return; itemStack.setAmount(amount); player.getInventory().addItem(itemStack); } public static boolean saveToFile(ItemStack itemStack, String fileName){ - if (itemStack == null || itemStack.getType() == Material.AIR) return false; - YamlConfiguration yamlConfiguration = new YamlConfiguration(); yamlConfiguration.set(fileName + ".material", itemStack.getType().toString()); NBTItem nbtItem = new NBTItem(itemStack); - Map map0 = compoundToMap(nbtItem); if (map0.size() != 0) { yamlConfiguration.createSection(fileName + ".nbt", map0); } - - File file = new File(CustomFishing.plugin.getDataFolder(), File.separator + "loots" + File.separator + fileName + ".yml"); - + File file = new File(CustomFishing.getInstance().getDataFolder(), File.separator + "loots" + File.separator + fileName + ".yml"); try { yamlConfiguration.save(file); - CustomFishing.plugin.getLootManager().unload(); - CustomFishing.plugin.getLootManager().load(); + CustomFishing.getInstance().getLootManager().unload(); + CustomFishing.getInstance().getLootManager().load(); } catch (IOException e) { e.printStackTrace(); } - return true; } - public static void addExtraMeta(ItemStack itemStack, DroppedItem droppedItem) { + public static void addExtraMeta(ItemStack itemStack, DroppedItem droppedItem, double sizeMultiplier) { NBTItem nbtItem = new NBTItem(itemStack); - boolean changed = replaceSizeLore(droppedItem.getSize(), nbtItem); + boolean changed = replaceSizeLore(droppedItem.getSize(), nbtItem, sizeMultiplier); if (droppedItem.getBasicPrice() != 0) { NBTCompound fishMetaCompound = nbtItem.addCompound("FishMeta"); fishMetaCompound.setFloat("base", droppedItem.getBasicPrice()); @@ -210,15 +226,15 @@ public class ItemStackUtil { } } - private static boolean replaceSizeLore(String[] sizes, NBTItem nbtItem) { + private static boolean replaceSizeLore(String[] sizes, NBTItem nbtItem, double sizeMultiplier) { if (sizes == null) return false; float min = Float.parseFloat(sizes[0]); float max = Float.parseFloat(sizes[1]); if (max - min < 0) return false; - float size = (float) (min + Math.random() * (max - min)); + float size = (float) ((min + Math.random() * (max - min)) * sizeMultiplier); String sizeText = String.format("%.1f", size); NBTCompound nbtCompound = nbtItem.getCompound("display"); - if (nbtCompound == null || !nbtCompound.hasKey("Lore")) return false; + if (nbtCompound == null || !nbtCompound.hasTag("Lore")) return false; List lore = nbtCompound.getStringList("Lore"); lore.replaceAll(s -> s.replace("{size}", sizeText)); NBTCompound fishMetaCompound = nbtItem.addCompound("FishMeta"); diff --git a/src/main/java/net/momirealms/customfishing/util/JedisUtil.java b/src/main/java/net/momirealms/customfishing/util/JedisUtil.java index 463285a9..c3a1fa70 100644 --- a/src/main/java/net/momirealms/customfishing/util/JedisUtil.java +++ b/src/main/java/net/momirealms/customfishing/util/JedisUtil.java @@ -35,7 +35,6 @@ public class JedisUtil { } public static void initializeRedis(YamlConfiguration configuration){ - JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setTestWhileIdle(true); jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000); @@ -76,4 +75,15 @@ public class JedisUtil { } } } + + public static void closePool() { + if (jedisPool != null) { + jedisPool.close(); + jedisPool = null; + } + } + + public static boolean isPoolEnabled() { + return jedisPool != null; + } } diff --git a/src/main/resources/baits/default.yml b/src/main/resources/baits/default.yml index 0f788ca2..7d54bed7 100644 --- a/src/main/resources/baits/default.yml +++ b/src/main/resources/baits/default.yml @@ -6,8 +6,8 @@ simple_bait: - 'Reduce the time spent fishing' - 'But make it more difficult to catch fish' custom-model-data: 646 - # Click here to learn how modifier system works: https://www.yuque.com/docs/share/4842ac5f-b5ea-4568-acef-d510f8bc9064?# 《Modifier System》 - modifier: + # Click here to learn how effect system works: https://www.yuque.com/docs/share/4842ac5f-b5ea-4568-acef-d510f8bc9064?# 《Modifier System》 + effect: time: 0.85 difficulty: 2 @@ -18,7 +18,7 @@ wild_bait: lore: - 'Decreases fishing time by 30%.' custom-model-data: 696 - modifier: + effect: time: 0.7 magnet_bait: @@ -28,7 +28,7 @@ magnet_bait: lore: - 'Increases the probability of better loots by 15%.' custom-model-data: 695 - modifier: + effect: weight-multiply: silver: 1.15 gold: 1.15 \ No newline at end of file diff --git a/src/main/resources/bars.yml b/src/main/resources/bars.yml deleted file mode 100644 index 9d5111f5..00000000 --- a/src/main/resources/bars.yml +++ /dev/null @@ -1,460 +0,0 @@ -rainbow_1: - range: 16 - title: '<#B22222>RED!' - subtitle: - start: '' - # unicodes are not in minecraft:default font - # So they would not affect player's chatting - bar: '뀋' - pointer_offset: '넂' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 1 - 2: 0 - 3: 0 - 4: 0 - 5: 0 - 6: 0 - 7: 0 -rainbow_2: - range: 16 - title: '<#FFA500>ORANGE!' - subtitle: - start: '' - bar: '뀋' - pointer_offset: '넂' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 1 - 3: 0 - 4: 0 - 5: 0 - 6: 0 - 7: 0 -rainbow_3: - range: 16 - title: '<#FFFF00>YELLOW!' - subtitle: - start: '' - bar: '뀋' - pointer_offset: '넂' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0 - 3: 1 - 4: 0 - 5: 0 - 6: 0 - 7: 0 -rainbow_4: - range: 16 - title: 'GREEN!' - subtitle: - start: '' - bar: '뀋' - pointer_offset: '넂' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0 - 3: 0 - 4: 1 - 5: 0 - 6: 0 - 7: 0 -rainbow_5: - range: 16 - title: '<#00FFFF>AQUA!' - subtitle: - start: '' - bar: '뀋' - pointer_offset: '넂' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0 - 3: 0 - 4: 0 - 5: 1 - 6: 0 - 7: 0 -rainbow_6: - range: 16 - title: '<#1E90FF>BLUE!' - subtitle: - start: '' - bar: '뀋' - pointer_offset: '넂' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0 - 3: 0 - 4: 0 - 5: 0 - 6: 1 - 7: 0 -rainbow_7: - range: 16 - title: '<#9400D3>PURPLE!' - subtitle: - start: '' - bar: '뀋' - pointer_offset: '넂' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0 - 3: 0 - 4: 0 - 5: 0 - 6: 0 - 7: 1 - - -bar_1: - range: 16 - title: 'The fish is hooked, focus on it!' - subtitle: - start: '' - bar: '뀂' - pointer_offset: '넁' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0 - 3: 0 - 4: 0.2 - 5: 0.6 - 6: 1 - 7: 0.6 - 8: 0.2 - 9: 0 - 10: 0 - 11: 0 -bar_2: - range: 16 - title: 'The fish is hooked, focus on it!' - subtitle: - start: '' - bar: '뀃' - pointer_offset: '넁' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0.2 - 3: 0.6 - 4: 1 - 5: 0.6 - 6: 0.2 - 7: 0 - 8: 0 - 9: 0 - 10: 0 - 11: 0 -bar_3: - range: 16 - title: 'The fish is hooked, focus on it!' - subtitle: - start: '' - bar: '뀄' - pointer_offset: '넁' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0 - 3: 0 - 4: 0 - 5: 0 - 6: 0.2 - 7: 0.6 - 8: 1 - 9: 0.6 - 10: 0.2 - 11: 0 -bar_4: - range: 8 - title: 'The fish is hooked, focus on it!' - subtitle: - start: '' - bar: '뀅' - pointer_offset: '넁' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0 - 3: 0.1 - 4: 0.1 - 5: 0 - 6: 0 - 7: 0.2 - 8: 0.2 - 9: 0.6 - 10: 0.6 - 11: 1 - 12: 0.6 - 13: 0.2 - 14: 0 - 15: 0.2 - 16: 0.6 - 17: 1 - 18: 0.6 - 19: 0.2 - 20: 0.1 - 21: 0 - 22: 0 -bar_5: - range: 8 - title: 'The fish is hooked, focus on it!' - subtitle: - start: '' - bar: '뀆' - pointer_offset: '넁' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 1 - 2: 0 - 3: 0.1 - 4: 0.2 - 5: 0.2 - 6: 0.6 - 7: 0.6 - 8: 1 - 9: 0.6 - 10: 0.2 - 11: 0 - 12: 0.2 - 13: 0.6 - 14: 1 - 15: 0.6 - 16: 0.2 - 17: 0 - 18: 1 - 19: 0.2 - 20: 0.1 - 21: 0 - 22: 0 -bar_6: - range: 8 - title: 'The fish is hooked, focus on it!' - subtitle: - start: '' - bar: '뀇' - pointer_offset: '넁' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0.1 - 2: 0.1 - 3: 0.1 - 4: 0.1 - 5: 0.1 - 6: 0.1 - 7: 0.1 - 8: 0.1 - 9: 1 - 10: 0 - 11: 1 - 12: 0 - 13: 1 - 14: 0 - 15: 0.1 - 16: 0.1 - 17: 0.1 - 18: 0.1 - 19: 0.1 - 20: 0.1 - 21: 0.1 - 22: 0.1 -bar_7: - range: 4 - title: 'The fish is hooked, focus on it!' - subtitle: - start: '' - bar: '뀈' - pointer_offset: '넁' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0 - 3: 0 - 4: 0 - 5: 0 - 6: 0 - 7: 0 - 8: 0 - 9: 0 - 10: 0 - 11: 0 - 12: 0 - 13: 0 - 14: 0 - 15: 0 - 16: 0 - 17: 0 - 18: 0 - 19: 0 - 20: 0 - 21: 0 - 22: 0 - 23: 0 - 24: 0 - 25: 0 - 26: 0 - 27: 0 - 28: 0 - 29: 0 - 30: 0 - 31: 0 - 32: 0 - 33: 0 - 34: 0 - 35: 0.1 - 36: 0.1 - 37: 0 - 38: 0 - 39: 1 - 40: 0 - 41: 0 - 42: 0.3 - 43: 0.3 - 44: 0.3 -bar_8: - range: 4 - title: 'The fish is hooked, focus on it!' - subtitle: - start: '' - bar: '뀉' - pointer_offset: '넁' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 0 - 2: 0 - 3: 0 - 4: 0 - 5: 0 - 6: 0 - 7: 0 - 8: 0 - 9: 0 - 10: 0 - 11: 0 - 12: 0 - 13: 0 - 14: 0 - 15: 0 - 16: 0 - 17: 0.2 - 18: 0.2 - 19: 0.2 - 20: 0.6 - 21: 1 - 22: 0.6 - 23: 0.2 - 24: 0.2 - 25: 0.2 - 26: 0.2 - 27: 0 - 28: 0 - 29: 0 - 30: 0 - 31: 0 - 32: 0 - 33: 0 - 34: 0 - 35: 0 - 36: 0 - 37: 0 - 38: 0 - 39: 0 - 40: 0 - 41: 0 - 42: 0 - 43: 0 - 44: 0 -bar_9: - range: 4 - title: 'The fish is hooked, focus on it!' - subtitle: - start: '' - bar: '뀊' - pointer_offset: '넁' - pointer: '뀁' - offset: '넀' - end: '' - layout: - 1: 1 - 2: 0 - 3: 0 - 4: 0 - 5: 0 - 6: 0 - 7: 0 - 8: 0 - 9: 0 - 10: 0 - 11: 0 - 12: 0 - 13: 0 - 14: 0 - 15: 0 - 16: 0 - 17: 0 - 18: 0 - 19: 0 - 20: 0 - 21: 0 - 22: 0 - 23: 0 - 24: 0 - 25: 0 - 26: 0 - 27: 0 - 28: 0 - 29: 0 - 30: 0 - 31: 0 - 32: 0 - 33: 0 - 34: 0 - 35: 0 - 36: 0 - 37: 0 - 38: 0 - 39: 0 - 40: 0 - 41: 0 - 42: 0 - 43: 0 - 44: 1 \ No newline at end of file diff --git a/src/main/resources/bars/default.yml b/src/main/resources/bars/default.yml new file mode 100644 index 00000000..81362bb2 --- /dev/null +++ b/src/main/resources/bars/default.yml @@ -0,0 +1,536 @@ +############### +# Game Type 1 # +############### +rainbow_1: + game-type: 1 + title: '<#B22222>RED!' + subtitle: + font: 'customfishing:default' + bar: '뀋' + pointer: '뀁' + arguments: + pointer-offset: -119 + pointer-width: 5 + width-per-section: 16 + success-rate-sections: + 1: 1 + 2: 0 + 3: 0 + 4: 0 + 5: 0 + 6: 0 + 7: 0 +rainbow_2: + game-type: 1 + title: '<#FFA500>ORANGE!' + subtitle: + font: 'customfishing:default' + bar: '뀋' + pointer: '뀁' + arguments: + pointer-offset: -119 + pointer-width: 5 + width-per-section: 16 + success-rate-sections: + 1: 0 + 2: 1 + 3: 0 + 4: 0 + 5: 0 + 6: 0 + 7: 0 +rainbow_3: + game-type: 1 + title: '<#FFFF00>YELLOW!' + subtitle: + font: 'customfishing:default' + bar: '뀋' + pointer: '뀁' + arguments: + pointer-offset: -119 + pointer-width: 5 + width-per-section: 16 + success-rate-sections: + 1: 0 + 2: 0 + 3: 1 + 4: 0 + 5: 0 + 6: 0 + 7: 0 +rainbow_4: + game-type: 1 + title: 'GREEN!' + subtitle: + font: 'customfishing:default' + bar: '뀋' + pointer: '뀁' + arguments: + pointer-offset: -119 + pointer-width: 5 + width-per-section: 16 + success-rate-sections: + 1: 0 + 2: 0 + 3: 0 + 4: 1 + 5: 0 + 6: 0 + 7: 0 +rainbow_5: + game-type: 1 + title: '<#00FFFF>AQUA!' + subtitle: + font: 'customfishing:default' + bar: '뀋' + pointer: '뀁' + arguments: + pointer-offset: -119 + pointer-width: 5 + width-per-section: 16 + success-rate-sections: + 1: 0 + 2: 0 + 3: 0 + 4: 0 + 5: 1 + 6: 0 + 7: 0 +rainbow_6: + game-type: 1 + title: '<#1E90FF>BLUE!' + subtitle: + font: 'customfishing:default' + bar: '뀋' + pointer: '뀁' + arguments: + pointer-offset: -119 + pointer-width: 5 + width-per-section: 16 + success-rate-sections: + 1: 0 + 2: 0 + 3: 0 + 4: 0 + 5: 0 + 6: 1 + 7: 0 +rainbow_7: + game-type: 1 + title: '<#9400D3>PURPLE!' + subtitle: + font: 'customfishing:default' + bar: '뀋' + pointer: '뀁' + arguments: + pointer-offset: -119 + pointer-width: 5 + width-per-section: 16 + success-rate-sections: + 1: 0 + 2: 0 + 3: 0 + 4: 0 + 5: 0 + 6: 0 + 7: 1 +bar_1: + game-type: 1 + title: + - 'So close, stay cool!' + - 'The fish is hooked, focus on it!' + - 'Sturdy on! Victory is almost ours!' + subtitle: + font: 'customfishing:default' + bar: '뀂' + pointer: '뀁' + arguments: + pointer-offset: -183 + pointer-width: 5 + width-per-section: 16 + success-rate-sections: + 1: 0 + 2: 0 + 3: 0 + 4: 0.2 + 5: 0.6 + 6: 1 + 7: 0.6 + 8: 0.2 + 9: 0 + 10: 0 + 11: 0 +bar_2: + game-type: 1 + title: + - 'So close, stay cool!' + - 'The fish is hooked, focus on it!' + - 'Sturdy on! Victory is almost ours!' + subtitle: + font: 'customfishing:default' + bar: '뀃' + pointer: '뀁' + arguments: + pointer-offset: -183 + pointer-width: 5 + width-per-section: 16 + success-rate-sections: + 1: 0 + 2: 0.2 + 3: 0.6 + 4: 1 + 5: 0.6 + 6: 0.2 + 7: 0 + 8: 0 + 9: 0 + 10: 0 + 11: 0 +bar_3: + game-type: 1 + title: + - 'So close, stay cool!' + - 'The fish is hooked, focus on it!' + - 'Sturdy on! Victory is almost ours!' + subtitle: + font: 'customfishing:default' + bar: '뀄' + pointer: '뀁' + arguments: + pointer-offset: -183 + pointer-width: 5 + width-per-section: 16 + success-rate-sections: + 1: 0 + 2: 0 + 3: 0 + 4: 0 + 5: 0 + 6: 0.2 + 7: 0.6 + 8: 1 + 9: 0.6 + 10: 0.2 + 11: 0 +bar_4: + game-type: 1 + title: + - 'So close, stay cool!' + - 'The fish is hooked, focus on it!' + - 'Sturdy on! Victory is almost ours!' + subtitle: + font: 'customfishing:default' + bar: '뀅' + pointer: '뀁' + arguments: + pointer-offset: -183 + pointer-width: 5 + width-per-section: 8 + success-rate-sections: + 1: 0 + 2: 0 + 3: 0.1 + 4: 0.1 + 5: 0 + 6: 0 + 7: 0.2 + 8: 0.2 + 9: 0.6 + 10: 0.6 + 11: 1 + 12: 0.6 + 13: 0.2 + 14: 0 + 15: 0.2 + 16: 0.6 + 17: 1 + 18: 0.6 + 19: 0.2 + 20: 0.1 + 21: 0 + 22: 0 +bar_5: + game-type: 1 + title: + - 'So close, stay cool!' + - 'The fish is hooked, focus on it!' + - 'Sturdy on! Victory is almost ours!' + subtitle: + font: 'customfishing:default' + bar: '뀆' + pointer: '뀁' + arguments: + pointer-offset: -183 + pointer-width: 5 + width-per-section: 8 + success-rate-sections: + 1: 1 + 2: 0 + 3: 0.1 + 4: 0.2 + 5: 0.2 + 6: 0.6 + 7: 0.6 + 8: 1 + 9: 0.6 + 10: 0.2 + 11: 0 + 12: 0.2 + 13: 0.6 + 14: 1 + 15: 0.6 + 16: 0.2 + 17: 0 + 18: 1 + 19: 0.2 + 20: 0.1 + 21: 0 + 22: 0 +bar_6: + game-type: 1 + title: + - 'So close, stay cool!' + - 'The fish is hooked, focus on it!' + - 'Sturdy on! Victory is almost ours!' + subtitle: + font: 'customfishing:default' + bar: '뀇' + pointer: '뀁' + arguments: + pointer-offset: -183 + pointer-width: 5 + width-per-section: 8 + success-rate-sections: + 1: 0.1 + 2: 0.1 + 3: 0.1 + 4: 0.1 + 5: 0.1 + 6: 0.1 + 7: 0.1 + 8: 0.1 + 9: 1 + 10: 0 + 11: 1 + 12: 0 + 13: 1 + 14: 0 + 15: 0.1 + 16: 0.1 + 17: 0.1 + 18: 0.1 + 19: 0.1 + 20: 0.1 + 21: 0.1 + 22: 0.1 +bar_7: + game-type: 1 + title: + - 'So close, stay cool!' + - 'The fish is hooked, focus on it!' + - 'Sturdy on! Victory is almost ours!' + subtitle: + font: 'customfishing:default' + bar: '뀈' + pointer: '뀁' + arguments: + pointer-offset: -183 + pointer-width: 5 + width-per-section: 4 + success-rate-sections: + 1: 0 + 2: 0 + 3: 0 + 4: 0 + 5: 0 + 6: 0 + 7: 0 + 8: 0 + 9: 0 + 10: 0 + 11: 0 + 12: 0 + 13: 0 + 14: 0 + 15: 0 + 16: 0 + 17: 0 + 18: 0 + 19: 0 + 20: 0 + 21: 0 + 22: 0 + 23: 0 + 24: 0 + 25: 0 + 26: 0 + 27: 0 + 28: 0 + 29: 0 + 30: 0 + 31: 0 + 32: 0 + 33: 0 + 34: 0 + 35: 0.1 + 36: 0.1 + 37: 0 + 38: 0 + 39: 1 + 40: 0 + 41: 0 + 42: 0.3 + 43: 0.3 + 44: 0.3 +bar_8: + game-type: 1 + title: + - 'So close, stay cool!' + - 'The fish is hooked, focus on it!' + - 'Sturdy on! Victory is almost ours!' + subtitle: + font: 'customfishing:default' + bar: '뀉' + pointer: '뀁' + arguments: + pointer-offset: -183 + pointer-width: 5 + width-per-section: 4 + success-rate-sections: + 1: 0 + 2: 0 + 3: 0 + 4: 0 + 5: 0 + 6: 0 + 7: 0 + 8: 0 + 9: 0 + 10: 0 + 11: 0 + 12: 0 + 13: 0 + 14: 0 + 15: 0 + 16: 0 + 17: 0.2 + 18: 0.2 + 19: 0.2 + 20: 0.6 + 21: 1 + 22: 0.6 + 23: 0.2 + 24: 0.2 + 25: 0.2 + 26: 0.2 + 27: 0 + 28: 0 + 29: 0 + 30: 0 + 31: 0 + 32: 0 + 33: 0 + 34: 0 + 35: 0 + 36: 0 + 37: 0 + 38: 0 + 39: 0 + 40: 0 + 41: 0 + 42: 0 + 43: 0 + 44: 0 +bar_9: + game-type: 1 + title: + - 'So close, stay cool!' + - 'The fish is hooked, focus on it!' + - 'Sturdy on! Victory is almost ours!' + subtitle: + font: 'customfishing:default' + bar: '뀊' + pointer: '뀁' + arguments: + pointer-offset: -183 + pointer-width: 5 + width-per-section: 4 + success-rate-sections: + 1: 1 + 2: 0 + 3: 0 + 4: 0 + 5: 0 + 6: 0 + 7: 0 + 8: 0 + 9: 0 + 10: 0 + 11: 0 + 12: 0 + 13: 0 + 14: 0 + 15: 0 + 16: 0 + 17: 0 + 18: 0 + 19: 0 + 20: 0 + 21: 0 + 22: 0 + 23: 0 + 24: 0 + 25: 0 + 26: 0 + 27: 0 + 28: 0 + 29: 0 + 30: 0 + 31: 0 + 32: 0 + 33: 0 + 34: 0 + 35: 0 + 36: 0 + 37: 0 + 38: 0 + 39: 0 + 40: 0 + 41: 0 + 42: 0 + 43: 0 + 44: 1 + +############### +# Game Type 2 # +############### +pull_bar: + game-type: 2 + title: '{progress}' + subtitle: + font: 'customfishing:default' + bar: '뀌' + judgment-area: '뀍' + fish: '뀎' + arguments: + punishment: 0.1 + bar-effective-area-width: 155 + judgment-area-offset: -160 + judgment-area-width: 33 + fish-icon-width: 7 + hold-time-requirements: + - 3 + - 4 + - 5 + - 6 + - 7 + progress: + - '뀁' + - '뀂' + - '뀃' + - '뀄' + - '뀅' + - '뀆' + - '뀇' + - '뀈' + - '뀉' \ No newline at end of file diff --git a/src/main/resources/competition.yml b/src/main/resources/competitions/default.yml similarity index 100% rename from src/main/resources/competition.yml rename to src/main/resources/competitions/default.yml diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 9f0a88d7..8f2f2098 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,41 +1,9 @@ -# don't change -config-version: '15' +# Don't change +config-version: '16' # chinese/english/spanish lang: english -# Plugin hooks -integrations: - # Sell fish - Vault: true - # Skill-xp - mcMMO: false - MMOCore: false - AureliumSkills: false - EcoSkills: false - JobsReborn: false - # Season condition - CustomCrops: false - RealisticSeasons: false - # Prevent players from activating totems in some regions - Residence: false - WorldGuard: false - Kingdoms: false - GriefDefender: false - PlotSquared: false - Towny: false - Lands: false - GriefPrevention: false - CrashClaim: false - BentoBox: false - # Mobs & Items - MythicMobs: false - # Items & Totem Blocks - ItemsAdder: false - Oraxen: false - # Items - MMOItems: false - # Worlds where fishing mechanic takes effects # 启用本插件的世界 worlds: @@ -48,7 +16,11 @@ worlds: # Mechanic settings mechanics: - + # Add custom nbt tags to the loots so plugin could identify + # Disable this will lose the trigger actions when eating fish + # 为每个战利品增加特殊的CustomFishing NBT标签以被插件识别 + # 禁用此项目将会导致吃食物触发的动作失效 + add-custom-fishing-tags-to-loots: true # Disable the fishing bar totally # 关闭捕鱼条 disable-bar-mechanic: false @@ -57,7 +29,8 @@ mechanics: # 是否在鱼咬钩后立刻显示捕鱼条,而不是需要右键后才显示 # 注意:启用本设置会导致无法获取原版钓鱼战利品 instant-bar: false - + # other loots + # 其他战利品 other-loots: # Should other loots have the same fishing mechanic CustomFishing provides # 其他战利品是否有插件提供的钓鱼特性 @@ -85,6 +58,9 @@ mechanics: # Does the CustomFishing loots requires special rod # 是否需要特殊鱼竿才能获取钓鱼插件物品库的内容 need-special-rod-for-loots: false + # Do all the rods have the ability to fish in lava + # 任何鱼竿都能在岩浆中钓鱼吗 + all-rods-fish-in-lava: false # Does rod lose durability when player successfully fish # 钓鱼成功后是否消耗耐久度 rod-lose-durability: true @@ -102,9 +78,8 @@ mechanics: # Fishing bag window title # 渔具袋的容器标题 bag-title: '{player}''s Fishing Bag' - # Can fishing bag store the loots? - # This would add additional NBT Tags to the loot - # 渔具袋是否能存放捕鱼战利品,这会在捕鱼战利品上增加额外NBT + # Can fishing bag store the loots? (Requires add-custom-fishing-tags-to-loots: true) + # 渔具袋是否能存储钓鱼战利品(需要设置add-custom-fishing-tags-to-loots: true) can-store-loot: false # Other whitelist-items # 允许放入渔具袋的其他物品白名单 @@ -131,16 +106,16 @@ mechanics: # ticks time: 25 -# Fishing result titles titles: success: title: - - 'Success!' - 'GG!' - 'Good Job!' subtitle: - - 'You have captured a {loot}' - - '{loot} Here we go!' + - 'You caught a {loot}' + - 'Whoa! Nice catch!' + - 'Oh {loot} here we go!' + - 'Let''s see what it is!' fade: # ticks in: 10 @@ -149,11 +124,11 @@ titles: failure: title: - 'Be concentrated!' - - 'Failure!' + - 'What a pity!' - 'Try next time!' + - 'Bad luck' subtitle: - - 'The fish escaped' - - 'Pay more attention on it!' + - 'The fish escaped...' fade: in: 10 stay: 30 @@ -179,4 +154,24 @@ other-settings: # 后台记录玩家销售鱼类所得金额 log-earnings: true # Set the MMOCore profession name - MMOCore-profession-name: 'customfishing' \ No newline at end of file + MMOCore-profession-name: 'customfishing' + # Set the offset characters' unicodes + # 设置左右偏移字符的unicode + offset-characters: + font: customfishing:offset_chars + '1':  + '2':  + '4':  + '8':  + '16':  + '32':  + '64':  + '128':  + '-1':  + '-2':  + '-4':  + '-8':  + '-16':  + '-32':  + '-64':  + '-128':  \ No newline at end of file diff --git a/src/main/resources/database.yml b/src/main/resources/database.yml index a4b0696a..47b6f76d 100644 --- a/src/main/resources/database.yml +++ b/src/main/resources/database.yml @@ -1,7 +1,12 @@ +config-version: '1' # YAML/MySQL/MariaDB # 存储模式 data-storage-method: YAML +# Migrate from 1.2 to 1.3 +# This option would automatically be set to false when migration finishes +migration: false + # MySQL settings MySQL: host: localhost diff --git a/src/main/resources/enchant-bonus.yml b/src/main/resources/enchants/default.yml similarity index 100% rename from src/main/resources/enchant-bonus.yml rename to src/main/resources/enchants/default.yml diff --git a/src/main/resources/loots/default.yml b/src/main/resources/loots/default.yml index f1dc2bf7..de18715c 100644 --- a/src/main/resources/loots/default.yml +++ b/src/main/resources/loots/default.yml @@ -6,8 +6,6 @@ rubbish: lore: - 'Maybe we need to protect the environment...' weight: 130 - time: 20000 - difficulty: 1-1 custom-model-data: 640 action: success: @@ -16,9 +14,6 @@ obsidian: nick: '<#4B0082>Obsidian' material: obsidian in-lava: true - weight: 80 - time: 20000 - difficulty: 1-2 action: success: mending: 15 @@ -27,8 +22,6 @@ wither_skeleton_skull: material: wither_skeleton_skull in-lava: true weight: 1 - time: 20000 - difficulty: 1-6 action: success: mending: 80 @@ -36,7 +29,6 @@ pufferfish: nick: '<#DAA520>Pufferfish' material: PUFFERFISH weight: 50 - difficulty: 1-1 action: success: mending: 7 @@ -44,7 +36,6 @@ cod: nick: '<#FFFACD>Cod' material: COD weight: 300 - difficulty: 1-1 action: success: mending: 3 @@ -52,12 +43,10 @@ salmon: nick: '<#D2691E>Salmon' material: SALMON weight: 250 - difficulty: 1-1 tropical_fish: nick: '&cT&fr&co&fp&ci&fc&ca&fl &cF&fi&cs&fh' material: TROPICAL_FISH weight: 50 - difficulty: 1-1 action: success: mending: 4 @@ -78,8 +67,6 @@ tuna_fish: - 'Tuna is a kind of healthy food.' - 'size: {size}cm' weight: 50 - time: 10000 - difficulty: 1-4 custom-model-data: 641 action: success: @@ -107,8 +94,6 @@ tuna_fish_silver_star: - 'Tuna is a kind of healthy food.' - 'size: {size}cm' weight: 20 - time: 8000 - difficulty: 1-5 group: silver custom-model-data: 666 action: @@ -137,8 +122,6 @@ tuna_fish_golden_star: - 'Tuna is a kind of healthy food.' - 'size: {size}cm' weight: 10 - time: 5000 - difficulty: 1-6 group: gold custom-model-data: 667 action: @@ -170,8 +153,6 @@ pike_fish: - 'water and inland freshwater lakes' - 'size: {size}cm' weight: 70 - time: 7000 - difficulty: 1-2 custom-model-data: 642 action: success: @@ -200,8 +181,6 @@ pike_fish_silver_star: - 'water and inland freshwater lakes' - 'size: {size}cm' weight: 30 - time: 7000 - difficulty: 1-3 group: silver action: success: @@ -231,8 +210,6 @@ pike_fish_golden_star: - 'water and inland freshwater lakes' - 'size: {size}cm' weight: 10 - time: 7000 - difficulty: 1-4 group: gold action: success: @@ -261,8 +238,6 @@ gold_fish: weight: 50 price: base: 70 - time: 12000 - difficulty: 1-1 custom-model-data: 643 action: success: @@ -277,10 +252,8 @@ gold_fish_silver_star: - 'fishes in the world. It originated in China' - 'and has a history of more than 1700 years' weight: 20 - time: 11000 price: base: 80 - difficulty: 1-2 group: silver custom-model-data: 658 action: @@ -296,11 +269,9 @@ gold_fish_golden_star: - 'fishes in the world. It originated in China' - 'and has a history of more than 1700 years' weight: 10 - time: 10000 price: base: 100 group: gold - difficulty: 1-3 custom-model-data: 659 action: success: @@ -314,8 +285,6 @@ perch_fish: - 'foraging at dusk and early morning' - 'size: {size}cm' weight: 100 - time: 10000 - difficulty: 1-2 custom-model-data: 644 action: success: @@ -338,9 +307,7 @@ perch_fish_silver_star: - 'foraging at dusk and early morning' - 'size: {size}cm' weight: 30 - time: 9000 group: silver - difficulty: 1-2 custom-model-data: 660 action: success: @@ -364,8 +331,6 @@ perch_fish_golden_star: - 'size: {size}cm' weight: 15 group: gold - time: 8000 - difficulty: 1-1 custom-model-data: 661 action: success: @@ -388,8 +353,6 @@ mullet_fish: - 'to treat spleen and stomach weakness' - 'size: {size}cm' weight: 50 - time: 10000 - difficulty: 1-2 custom-model-data: 645 action: success: @@ -409,8 +372,6 @@ mullet_fish_silver_star: - 'size: {size}cm' weight: 20 group: silver - time: 8000 - difficulty: 1-3 custom-model-data: 662 action: success: @@ -429,9 +390,7 @@ mullet_fish_golden_star: - 'to treat spleen and stomach weakness' - 'size: {size}cm' weight: 10 - time: 6000 group: gold - difficulty: 1-4 custom-model-data: 663 action: success: @@ -450,8 +409,6 @@ sardine_fish: - 'Therefore, sardine are also called "smart food"' - 'size: {size}cm' weight: 50 - time: 8000 - difficulty: 1-2 custom-model-data: 668 action: success: @@ -470,9 +427,7 @@ sardine_fish_silver_star: - 'Therefore, sardine are also called "smart food"' - 'size: {size}cm' weight: 20 - time: 8000 group: silver - difficulty: 1-3 custom-model-data: 669 action: success: @@ -491,9 +446,7 @@ sardine_fish_golden_star: - 'Therefore, sardine are also called "smart food"' - 'size: {size}cm' weight: 10 - time: 8000 group: gold - difficulty: 1-4 custom-model-data: 670 action: success: @@ -511,8 +464,6 @@ carp_fish: - 'One of the most common edible fish' - 'size: {size}cm' weight: 100 - time: 10000 - difficulty: 1-2 custom-model-data: 671 action: success: @@ -541,9 +492,7 @@ carp_fish_silver_star: - 'One of the most common edible fish' - 'size: {size}cm' weight: 20 - time: 10000 group: silver - difficulty: 1-2 custom-model-data: 672 action: success: @@ -572,9 +521,7 @@ carp_fish_golden_star: - 'One of the most common edible fish' - 'size: {size}cm' weight: 10 - time: 10000 group: gold - difficulty: 1-2 custom-model-data: 673 action: success: @@ -603,8 +550,6 @@ cat_fish: - 'sharp jaw teeth, short intestine and stomach' - 'size: {size}cm' weight: 50 - time: 8000 - difficulty: 1-3 custom-model-data: 674 action: success: @@ -635,8 +580,6 @@ cat_fish_silver_star: - 'size: {size}cm' weight: 20 group: silver - time: 8000 - difficulty: 1-4 custom-model-data: 675 action: success: @@ -666,9 +609,7 @@ cat_fish_golden_star: - 'sharp jaw teeth, short intestine and stomach' - 'size: {size}cm' weight: 10 - time: 8000 group: gold - difficulty: 1-5 custom-model-data: 676 action: success: @@ -698,8 +639,6 @@ octopus: - 'People often use pots to catch octopus' - 'size: {size}cm' weight: 50 - time: 15000 - difficulty: 1-1 custom-model-data: 677 action: success: @@ -727,8 +666,6 @@ octopus_silver_star: - 'size: {size}cm' weight: 20 group: silver - time: 15000 - difficulty: 1-1 custom-model-data: 678 action: success: @@ -757,9 +694,7 @@ octopus_golden_star: - 'People often use pots to catch octopus' - 'size: {size}cm' weight: 10 - time: 15000 group: gold - difficulty: 1-1 custom-model-data: 679 action: success: @@ -787,8 +722,6 @@ sunfish: - 'It only has one huge head' - 'size: {size}cm' weight: 50 - time: 10000 - difficulty: 1-2 custom-model-data: 680 action: success: @@ -807,8 +740,6 @@ sunfish_silver_star: - 'size: {size}cm' weight: 20 group: silver - time: 10000 - difficulty: 1-2 custom-model-data: 681 action: success: @@ -826,9 +757,7 @@ sunfish_golden_star: - 'It only has one huge head' - 'size: {size}cm' weight: 10 - time: 10000 group: gold - difficulty: 1-2 custom-model-data: 682 action: success: @@ -846,8 +775,6 @@ red_snapper_fish: - 'with a male as the "head of the family"' - 'size: {size}cm' weight: 100 - time: 10000 - difficulty: 1-1 custom-model-data: 683 action: success: @@ -866,9 +793,7 @@ red_snapper_fish_silver_star: - 'with a male as the "head of the family"' - 'size: {size}cm' weight: 40 - time: 10000 group: silver - difficulty: 1-2 custom-model-data: 684 action: success: @@ -887,9 +812,7 @@ red_snapper_fish_golden_star: - 'with a male as the "head of the family"' - 'size: {size}cm' weight: 20 - time: 10000 group: gold - difficulty: 1-3 custom-model-data: 685 action: success: @@ -907,8 +830,6 @@ salmon_void_fish: lore: - 'A fish from the hell' weight: 50 - time: 10000 - difficulty: 1-2 custom-model-data: 686 action: success: @@ -927,9 +848,7 @@ salmon_void_fish_silver_star: lore: - 'A fish from the hell' weight: 20 - time: 10000 group: silver - difficulty: 1-2 custom-model-data: 687 action: success: @@ -948,9 +867,7 @@ salmon_void_fish_golden_star: lore: - 'A fish from the hell' weight: 10 - time: 10000 group: gold - difficulty: 1-2 custom-model-data: 688 action: success: @@ -970,8 +887,6 @@ woodskip_fish: - 'live in pools deep in the forest' - 'size: {size}cm' weight: 50 - time: 8000 - difficulty: 1-2 custom-model-data: 689 action: success: @@ -997,8 +912,6 @@ woodskip_fish_silver_star: - 'size: {size}cm' weight: 20 group: silver - time: 7000 - difficulty: 1-3 custom-model-data: 690 action: success: @@ -1024,8 +937,6 @@ woodskip_fish_golden_star: - 'size: {size}cm' weight: 10 group: gold - time: 6000 - difficulty: 1-4 custom-model-data: 691 action: success: @@ -1050,8 +961,6 @@ sturgeon_fish: - 'population. Females can live up to 150 years' - 'size: {size}cm' weight: 5 - time: 10000 - difficulty: 1-3 custom-model-data: 692 action: success: @@ -1074,8 +983,6 @@ sturgeon_fish_silver_star: - 'size: {size}cm' weight: 2 group: silver - time: 10000 - difficulty: 1-5 custom-model-data: 693 action: success: @@ -1097,9 +1004,7 @@ sturgeon_fish_golden_star: - 'population. Females can live up to 150 years' - 'size: {size}cm' weight: 1 - time: 10000 group: gold - difficulty: 1-7 custom-model-data: 694 action: success: diff --git a/src/main/resources/loots/example.yml b/src/main/resources/loots/example.yml index 76d9fc6d..a5a3e605 100644 --- a/src/main/resources/loots/example.yml +++ b/src/main/resources/loots/example.yml @@ -1,29 +1,28 @@ rainbow_fish: - # Enable + # 是否启用 enable: false - # Nick is what to show in fish finder and titles + # 昵称将在标题和找鱼器信息中显示 nick: 'Example Fish' # Should it be displayed in fish finder? + # 是否能被找鱼器定位 show-in-fishfinder: false # Is this loot only available when player fish in lava + # 是否是岩浆鱼 in-lava: false # The weight(relative chance) of getting this fish + # 获得此鱼的权重(相对概率) weight: 10 # Optional + # The group of this fish + # 鱼所在的组,可以无限自定义,以供效果识别进行权重操作 group: normal # The score to get in competition + # 比赛中获取的分数 score: 10 - # Specify the bar. If not specified, it will be random - layout: - - bar_1 - # Difficulty - # '1' represents the pointer moves every 1 tick - # '7' represents the pointer moves 7 pixels each time - difficulty: 1-7 - # How long can a player fish on each bite(ms) - time: 5000 + + # Basic elements of an item # You can use MiniMessage format in name & lore @@ -31,17 +30,22 @@ rainbow_fish: # https://docs.adventure.kyori.net/minimessage/format.html material: COD display: - name: '✖Example Rainbow Fish✖' + name: 'Rainbow Fish' lore: - 'This is a rainbow fish!' - 'It is {size}cm long!' custom-model-data: 1 - # breakable + + # unbreakable + # 不可破坏 unbreakable: false # Optional + # The size of the fish + # 鱼的大小 size: 10~200 # Optional + # The base price and size bonus, and you can customize price formula in sell-fish-gui.yml price: base: 50 bonus: 0.3 @@ -54,13 +58,13 @@ rainbow_fish: namespace: '(String) momirealms' id: '(String) rainbow_fish' - # Available events: eat/success/failure/hook + # Available events: consume/success/failure/hook # Available actions: message/command/exp/mending/skill-xp/sound/potion-effect action: - eat: + consume: potion-effect: type: blindness - level: 1 + amplifier: 1 duration: 200 success: message: diff --git a/src/main/resources/messages/messages_english.yml b/src/main/resources/messages/messages_english.yml index 822aedb4..cc6c0f2f 100644 --- a/src/main/resources/messages/messages_english.yml +++ b/src/main/resources/messages/messages_english.yml @@ -7,7 +7,7 @@ messages: not-online: 'That player is not online!' item-not-exist: 'That item does not exist!' player-not-exist: 'That player does not exist!' - escape: 'It has been too long since I pulled the hook and the fish ran away!' + escape: 'It has been too long since the fish is hooked. Oh my god, it escaped!' give-item: 'Successfully given players {Player} {Amount}x {Item}.' get-item: 'Successfully obtained {Amount}x {Item}.' no-console: 'This command cannot be executed from the console!' diff --git a/src/main/resources/minigames/default.yml b/src/main/resources/minigames/default.yml new file mode 100644 index 00000000..0cc679a0 --- /dev/null +++ b/src/main/resources/minigames/default.yml @@ -0,0 +1,75 @@ +rainbow: + # limit time to fish (seconds) + time: 15 + # Fishing bar + # The higher the frequency of a bar, the more likely the bar is + bars: + - rainbow_1 + - rainbow_2 + - rainbow_3 + - rainbow_4 + - rainbow_5 + - rainbow_6 + - rainbow_7 + # Available difficulty: 1-10 + # The higher the frequency of a difficulty, the more likely the difficulty is + difficulty: + - 1 + - 2 + - 2 + - 3 + - 3 + - 3 + - 4 + - 4 + - 5 + +normal: + time: 15 + bars: + - bar_1 + - bar_2 + - bar_3 + - bar_4 + - bar_5 + - bar_6 + - bar_7 + - bar_8 + - bar_9 + difficulty: + - 1 + - 2 + - 3 + - 3 + - 4 + - 4 + - 4 + - 4 + - 5 + - 5 + - 5 + - 6 + - 6 + - 6 + - 7 + +pull: + time: 30 + bars: + - pull_bar + difficulty: + - 1 + - 2 + - 3 + - 3 + - 4 + - 4 + - 4 + - 4 + - 5 + - 5 + - 5 + - 6 + - 6 + - 6 + - 7 \ No newline at end of file diff --git a/src/main/resources/mobs/example.yml b/src/main/resources/mobs/default.yml similarity index 94% rename from src/main/resources/mobs/example.yml rename to src/main/resources/mobs/default.yml index e55c0c09..11f0512c 100644 --- a/src/main/resources/mobs/example.yml +++ b/src/main/resources/mobs/default.yml @@ -18,8 +18,6 @@ skeletalknight: group: creature weight: 10 - difficulty: 1-6 - time: 5000 requirements: weather: diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index a49cd076..403289fa 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -10,21 +10,12 @@ softdepend: - MythicMobs - Oraxen - PlaceholderAPI - - Residence - - Kingdoms - - WorldGuard - - GriefDefender - - PlotSquared - - Towny - EcoEnchants - - Lands - - GriefPrevention - mcMMO - AureliumSkills - CustomCrops - MMOCore - EcoSkills - - CrashClaim - RealisticSeasons - Jobs - MMOItems diff --git a/src/main/resources/sell-fish.yml b/src/main/resources/sell-fish-gui.yml similarity index 91% rename from src/main/resources/sell-fish.yml rename to src/main/resources/sell-fish-gui.yml index aea165ea..771448cf 100644 --- a/src/main/resources/sell-fish.yml +++ b/src/main/resources/sell-fish-gui.yml @@ -1,5 +1,3 @@ -# Fish got from command can't be sold! Only those from fishing would have special price NBT tags - container-title: 'Sell Fish' rows: 6 @@ -11,6 +9,12 @@ sell-limitation: price-formula: '{base} + {bonus} * {size}' +vanilla-item-price: + COD: 10 + PUFFERFISH: 10 + SALMON: 10 + TROPICAL_FISH: 10 + sounds: open: minecraft:block.chest.open close: minecraft:block.chest.close @@ -36,7 +40,7 @@ actions: commands: enable: false value: - - 'money give {player} {money}' + - 'cmi broadcast {player} earned {money}' functional-icons: slots: @@ -56,7 +60,6 @@ functional-icons: - 'Nothing to sell!' custom-model-data: 1 - decorative-icons: glass-pane: material: BLACK_STAINED_GLASS_PANE @@ -87,10 +90,4 @@ decorative-icons: - 51 - 52 - 53 - - 54 - -vanilla-item-price: - COD: 10 - PUFFERFISH: 10 - SALMON: 10 - TROPICAL_FISH: 10 \ No newline at end of file + - 54 \ No newline at end of file diff --git a/src/main/resources/totem-blocks.yml b/src/main/resources/totem-blocks/default.yml similarity index 100% rename from src/main/resources/totem-blocks.yml rename to src/main/resources/totem-blocks/default.yml diff --git a/src/main/resources/totems.yml b/src/main/resources/totems/default.yml similarity index 100% rename from src/main/resources/totems.yml rename to src/main/resources/totems/default.yml diff --git a/src/main/resources/utils/fishfinder.yml b/src/main/resources/utils/fish_finder.yml similarity index 100% rename from src/main/resources/utils/fishfinder.yml rename to src/main/resources/utils/fish_finder.yml