diff --git a/build.gradle b/build.gradle index fbd1a844..b58fe4d1 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } group = 'net.momirealms' -version = '1.1.4.3' +version = '1.2.0-SNAPSHOT' repositories { mavenCentral() @@ -46,6 +46,7 @@ dependencies { compileOnly fileTree(dir:'libs',includes:['*.jar']) compileOnly('io.papermc.paper:paper-api:1.17.1-R0.1-SNAPSHOT') compileOnly('com.github.Archy-X:AureliumSkills:Beta1.3.6') + compileOnly('com.comphenix.protocol:ProtocolLib:4.8.0') compileOnly('redis.clients:jedis:4.2.3') compileOnly('me.clip:placeholderapi:2.11.1') compileOnly('com.sk89q.worldguard:worldguard-bukkit:7.0.7') @@ -60,6 +61,7 @@ dependencies { implementation('net.kyori:adventure-text-minimessage:4.11.0') implementation('net.kyori:adventure-text-serializer-legacy:4.11.0') implementation('de.tr7zw:item-nbt-api:2.10.0') + implementation("org.bstats:bstats-bukkit:3.0.0") } def targetJavaVersion = 16 @@ -92,6 +94,7 @@ tasks.withType(JavaCompile) { } shadowJar { - relocate 'de.tr7zw', 'net.momirealms.customfishing.libs' - relocate 'net.kyori', 'net.momirealms.customfishing.libs' + relocate 'de.tr7zw', 'net.momirealms.customfishing.libs.de.tr7zw' + relocate 'net.kyori', 'net.momirealms.customfishing.libs.net.kyori' + relocate 'org.bstats', 'net.momirealms.customfishing.libs.org.bstats' } \ No newline at end of file diff --git a/gradlew b/gradlew index 1b6c7873..535fb9f7 100644 --- a/gradlew +++ b/gradlew @@ -86,7 +86,7 @@ APP_NAME="Gradle" APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +DEFAULT_JVM_OPTS='"-Xmx128m" "-Xms128m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum diff --git a/src/main/java/net/momirealms/customfishing/ConfigReader.java b/src/main/java/net/momirealms/customfishing/ConfigReader.java deleted file mode 100644 index b61bae6a..00000000 --- a/src/main/java/net/momirealms/customfishing/ConfigReader.java +++ /dev/null @@ -1,1015 +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; - -import net.kyori.adventure.bossbar.BossBar; -import net.momirealms.customfishing.helper.Log; -import net.momirealms.customfishing.competition.CompetitionConfig; -import net.momirealms.customfishing.competition.Goal; -import net.momirealms.customfishing.competition.bossbar.BossBarConfig; -import net.momirealms.customfishing.hook.EcoItemRegister; -import net.momirealms.customfishing.hook.season.CustomCropsSeason; -import net.momirealms.customfishing.hook.season.RealisticSeason; -import net.momirealms.customfishing.hook.season.SeasonInterface; -import net.momirealms.customfishing.hook.skill.*; -import net.momirealms.customfishing.object.*; -import net.momirealms.customfishing.object.action.*; -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.requirements.*; -import net.momirealms.customfishing.utils.*; -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.MemorySection; -import org.bukkit.configuration.file.FileConfiguration; -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 ConfigReader{ - - public static HashMap LOOT = new HashMap<>(); - public static HashMap LootItem = new HashMap<>(); - public static HashMap UtilItem = new HashMap<>(); - public static HashMap ROD = new HashMap<>(); - public static HashMap RodItem = new HashMap<>(); - public static HashMap BAIT = new HashMap<>(); - public static HashMap BaitItem = new HashMap<>(); - public static HashMap LAYOUT = new HashMap<>(); - public static HashMap OTHERS = new HashMap<>(); - public static HashMap> ENCHANTS = new HashMap<>(); - public static HashMap CompetitionsT = new HashMap<>(); - public static HashMap CompetitionsC = new HashMap<>(); - public static boolean useRedis; - - public static YamlConfiguration getConfig(String configName) { - File file = new File(CustomFishing.instance.getDataFolder(), configName); - if (!file.exists()) { - CustomFishing.instance.saveResource(configName, false); - } - return YamlConfiguration.loadConfiguration(file); - } - - public static void Reload() { - Config.loadConfig(); - Message.loadMessage(); - Title.loadTitle(); - loadBars(); - loadLoot(); - loadUtil(); - loadRod(); - loadBait(); - loadEnchants(); - loadCompetitions(); - if (Bukkit.getPluginManager().isPluginEnabled("eco")) { - EcoItemRegister.registerItems(); - } - } - - public static class Config { - - public static boolean wg; - public static boolean mm; - public static boolean papi; - public static boolean needOpenWater; - public static boolean needSpecialRod; - public static boolean competition; - public static boolean convertMMOItems; - public static boolean loseDurability; - public static boolean preventPick; - public static boolean doubleRealIn; - public static boolean vanillaLoot; - public static boolean showBar; - public static boolean mcMMOLoot; - public static boolean hasWhitelist; - public static boolean needRodFishing; - public static boolean disableJobXp; - public static boolean isSpigot; - public static int fishFinderCoolDown; - public static double timeMultiply; - public static double vanillaRatio; - public static double mcMMOLootChance; - public static SkillXP skillXP; - public static String version; - public static String lang; - public static String priority; - public static List whitelistWorlds = new ArrayList<>(); - public static SeasonInterface season; - - public static void loadConfig() { - - CustomFishing.instance.saveDefaultConfig(); - CustomFishing.instance.reloadConfig(); - FileConfiguration config = CustomFishing.instance.getConfig(); - - wg = (mm = (papi = false)); - if (config.getBoolean("config.integrations.WorldGuard")){ - if (Bukkit.getPluginManager().getPlugin("WorldGuard") == null) AdventureUtil.consoleMessage("[CustomFishing] Failed to initialize WorldGuard!"); - else { - AdventureUtil.consoleMessage("[CustomFishing] WorldGuard Hooked!"); - wg = true; - } - } - if (config.getBoolean("config.integrations.MythicMobs")){ - if (Bukkit.getPluginManager().getPlugin("MythicMobs") == null) AdventureUtil.consoleMessage("[CustomFishing] Failed to initialize MythicMobs!"); - else { - AdventureUtil.consoleMessage("[CustomFishing] MythicMobs Hooked!"); - mm = true; - } - } - if (config.getBoolean("config.integrations.PlaceholderAPI")){ - if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") == null) AdventureUtil.consoleMessage("[CustomFishing] Failed to initialize PlaceholderAPI!"); - else papi = true; - } - - skillXP = null; - if(config.getBoolean("config.integrations.mcMMO",false)){ - if (Bukkit.getPluginManager().getPlugin("mcMMO") == null) CustomFishing.instance.getLogger().warning("Failed to initialize mcMMO!"); - else { - skillXP = new mcMMO(); - AdventureUtil.consoleMessage("[CustomFishing] mcMMO Hooked!"); - } - } - if(config.getBoolean("config.integrations.AureliumSkills",false)){ - if (Bukkit.getPluginManager().getPlugin("AureliumSkills") == null) CustomFishing.instance.getLogger().warning("Failed to initialize AureliumSkills!"); - else { - skillXP = new Aurelium(); - AdventureUtil.consoleMessage("[CustomFishing] AureliumSkills Hooked!"); - } - } - if(config.getBoolean("config.integrations.MMOCore",false)){ - if (Bukkit.getPluginManager().getPlugin("MMOCore") == null) CustomFishing.instance.getLogger().warning("Failed to initialize MMOCore!"); - else { - skillXP = new MMOCore(); - AdventureUtil.consoleMessage("[CustomFishing] MMOCore Hooked!"); - } - } - if(config.getBoolean("config.integrations.EcoSkills",false)){ - if (Bukkit.getPluginManager().getPlugin("EcoSkills") == null) CustomFishing.instance.getLogger().warning("Failed to initialize EcoSkills!"); - else { - skillXP = new EcoSkill(); - AdventureUtil.consoleMessage("[CustomFishing] EcoSkills Hooked!"); - } - } - if(config.getBoolean("config.integrations.JobsReborn",false)){ - if (Bukkit.getPluginManager().getPlugin("Jobs") == null) CustomFishing.instance.getLogger().warning("Failed to initialize JobsReborn!"); - else { - skillXP = new JobsReborn(); - AdventureUtil.consoleMessage("[CustomFishing] JobsReborn Hooked!"); - } - } - - season = null; - if (config.getBoolean("config.integrations.RealisticSeasons",false)){ - if (Bukkit.getPluginManager().getPlugin("RealisticSeasons") == null) Log.warn("Failed to initialize RealisticSeasons!"); - else { - season = new RealisticSeason(); - AdventureUtil.consoleMessage("[CustomFishing] RealisticSeasons Hooked!"); - } - } - if (config.getBoolean("config.integrations.CustomCrops",false)){ - if (Bukkit.getPluginManager().getPlugin("CustomCrops") == null) Log.warn("Failed to initialize CustomCrops!"); - else { - season = new CustomCropsSeason(); - AdventureUtil.consoleMessage("[CustomFishing] CustomCrops Hooked!"); - } - } - - isSpigot = Bukkit.getVersion().contains("Spigot"); - - version = config.getString("config-version"); - - doubleRealIn = config.getBoolean("config.double-reel-in", true); - - mcMMOLoot = config.getBoolean("config.other-loot.mcMMO", false); - mcMMOLootChance = config.getDouble("config.other-loot.mcMMO-chance", 0.5); - - vanillaLoot = config.getBoolean("config.other-loot.vanilla", true); - showBar = config.getBoolean("config.other-loot.bar", true); - vanillaRatio = config.getDouble("config.other-loot.vanilla-ratio"); - - convertMMOItems = config.getBoolean("config.convert-MMOITEMS", false); - needOpenWater = config.getBoolean("config.need-open-water", false); - needSpecialRod = config.getBoolean("config.need-special-rod.for-loots", false); - needRodFishing = config.getBoolean("config.need-special-rod.to-fish", false); - - loseDurability = config.getBoolean("config.rod-lose-durability", true); - preventPick = config.getBoolean("config.prevent-other-players-pick-up-loot", false); - - priority = config.getString("config.event-priority"); - fishFinderCoolDown = config.getInt("config.fishfinder-cooldown"); - timeMultiply = config.getDouble("config.time-multiply"); - lang = config.getString("config.lang","cn"); - competition = config.getBoolean("config.fishing-competition",true); - disableJobXp = config.getBoolean("config.disable-JobsReborn-fishing-exp",false); - - hasWhitelist = config.getBoolean("config.whitelist-worlds.enable",false); - - if (hasWhitelist){ - whitelistWorlds.clear(); - config.getStringList("config.whitelist-worlds.worlds").forEach(whitelistWorld -> { - try { - whitelistWorlds.add(Bukkit.getWorld(whitelistWorld)); - } - catch (Exception e){ - AdventureUtil.consoleMessage("[CustomFishing] Invalid world " + whitelistWorld); - e.printStackTrace(); - } - }); - } - } - } - - public static class Message { - - public static String prefix; - public static String reload; - public static String escape; - public static String noPerm; - public static String notExist; - public static String noConsole; - public static String wrongAmount; - public static String lackArgs; - public static String notOnline; - public static String giveItem; - public static String getItem; - public static String coolDown; - public static String possibleLoots; - public static String splitChar; - public static String noLoot; - public static String notOpenWater; - public static String competitionOn; - public static String notEnoughPlayers; - public static String noRank; - public static String forceSuccess; - public static String forceFailure; - public static String forceEnd; - public static String forceCancel; - public static String noPlayer; - public static String noScore; - public static String noRod; - public static String hookOther; - - public static void loadMessage() { - - YamlConfiguration config = getConfig("messages/messages_" + Config.lang +".yml"); - - prefix = config.getString("messages.prefix", "messages.prefix is missing"); - reload = config.getString("messages.reload", "messages.reload is missing"); - escape = config.getString("messages.escape", "messages.escape is missing"); - noPerm = config.getString("messages.no-perm", "messages.no-perm is missing"); - notExist = config.getString("messages.not-exist", "messages.not-exist is missing"); - noConsole = config.getString("messages.no-console", "messages.no-console is missing"); - wrongAmount = config.getString("messages.wrong-amount"); - lackArgs = config.getString("messages.lack-args"); - notOnline = config.getString("messages.not-online"); - giveItem = config.getString("messages.give-item"); - getItem = config.getString("messages.get-item"); - coolDown = config.getString("messages.cooldown"); - possibleLoots = config.getString("messages.possible-loots"); - splitChar = config.getString("messages.split-char"); - noLoot = config.getString("messages.no-loot"); - notOpenWater = config.getString("messages.not-open-water"); - competitionOn = config.getString("messages.competition-ongoing"); - notEnoughPlayers = config.getString("messages.players-not-enough"); - noRank = config.getString("messages.no-rank"); - forceSuccess = config.getString("messages.force-competition-success"); - forceFailure = config.getString("messages.force-competition-failure"); - forceEnd = config.getString("messages.force-competition-end"); - forceCancel = config.getString("messages.force-competition-cancel","messages.force-competition-cancel is messing"); - noPlayer = config.getString("messages.no-player", "messages.no-player is missing"); - noScore = config.getString("messages.no-score", "messages.no-score is missing"); - noRod = config.getString("messages.no-rod", "messages.no-rod is missing"); - hookOther = config.getString("messages.hook-other-entity","messages.hook-other-entity is missing"); - } - } - - public static class Title { - - public static List success_title; - public static List success_subtitle; - public static List failure_title; - public static List failure_subtitle; - public static int success_in; - public static int success_out; - public static int success_stay; - public static int failure_in; - public static int failure_out; - public static int failure_stay; - - public static void loadTitle() { - - YamlConfiguration config = getConfig("titles.yml"); - - success_title = config.getStringList("titles.success.title"); - success_subtitle = config.getStringList("titles.success.subtitle"); - success_in = config.getInt("titles.success.fade.in")*50; - success_out = config.getInt("titles.success.fade.out")*50; - success_stay = config.getInt("titles.success.fade.stay")*50; - failure_title = config.getStringList("titles.failure.title"); - failure_subtitle = config.getStringList("titles.failure.subtitle"); - failure_in = config.getInt("titles.failure.fade.in")*50; - failure_out = config.getInt("titles.failure.fade.out")*50; - failure_stay = config.getInt("titles.failure.fade.stay")*50; - } - } - - public static void loadLoot() { - - LOOT.clear(); - LootItem.clear(); - OTHERS.clear(); - CustomPapi.allPapi.clear(); - - File loot_file = new File(CustomFishing.instance.getDataFolder() + File.separator + "loots"); - - if (!loot_file.exists()) { - if (!loot_file.mkdir()) { - AdventureUtil.consoleMessage("[CustomFishing] Error! Failed to create loots folder..."); - return; - } - CustomFishing.instance.saveResource("loots" + File.separator + "default.yml", false); - CustomFishing.instance.saveResource("loots" + File.separator + "example.yml", false); - } - - File[] files = loot_file.listFiles(); - - if (files != null) { - - for (File file : files) { - - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - Set keys = config.getKeys(false); - - keys.forEach(key -> { - - if (!config.getBoolean(key + ".enable", true)) return; - - DroppedItem loot = new DroppedItem(key); - - String[] diff = StringUtils.split(config.getString(key + ".difficulty", "1-1"),"-"); - Difficulty difficulty = new Difficulty(Integer.parseInt(diff[0]), Integer.parseInt(diff[1])); - - int weight = config.getInt(key + ".weight",10); - int time = config.getInt(key + ".time",10000); - - loot.setDifficulty(difficulty); - loot.setTime(time); - loot.setWeight(weight); - if (config.contains(key + ".nick")) loot.setNick(config.getString(key + ".nick")); - else loot.setNick(ChatColor.stripColor(config.getString(key + ".display.name", key))); - loot.setScore(config.getDouble(key + ".score",0)); - loot.setShowInFinder(config.getBoolean(key + ".show-in-fishfinder", true)); - loot.setRandomDurability(config.getBoolean(key + ".random-durability", false)); - - if (config.contains(key + ".group")) - loot.setGroup(config.getString(key + ".group")); - if (config.contains(key + ".layout")) - loot.setLayout(config.getStringList(key + ".layout")); - if (config.contains(key + ".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); - } - }); - loot.setRandomEnchants(randomEnchants); - } - - List successActions = new ArrayList<>(); - if (config.contains(key + ".action.success.message")) - successActions.add(new MessageA(config.getStringList(key + ".action.success.message"), loot.getNick())); - if (config.contains(key + ".action.success.command")) - successActions.add(new CommandA(config.getStringList(key + ".action.success.command"), loot.getNick())); - if (config.contains(key + ".action.success.exp")) - successActions.add(new XPB(config.getInt(key + ".action.success.exp"))); - if (config.contains(key + ".action.success.mending")) - successActions.add(new XPA(config.getInt(key + ".action.success.mending"))); - if (config.contains(key + ".action.success.skill-xp")) - successActions.add(new FishingXPB(config.getInt(key + ".action.success.skill-xp"))); - loot.setSuccessActions(successActions); - - List failureActions = new ArrayList<>(); - if (config.contains(key + ".action.failure.message")) - failureActions.add(new MessageA(config.getStringList(key + ".action.failure.message"), loot.getNick())); - if (config.contains( key + ".action.failure.command")) - failureActions.add(new CommandA(config.getStringList(key + ".action.failure.command"), loot.getNick())); - if (config.contains( key + ".action.failure.exp")) - failureActions.add(new XPB(config.getInt( key + ".action.failure.exp"))); - if (config.contains(key + ".action.failure.mending")) - failureActions.add(new XPA(config.getInt(key + ".action.failure.mending"))); - if (config.contains( key + ".action.failure.skill-xp")) - failureActions.add(new FishingXPB(config.getInt( key + ".action.failure.skill-xp"))); - loot.setFailureActions(failureActions); - - List hookActions = new ArrayList<>(); - if (config.contains(key + ".action.hook.message")) - hookActions.add(new MessageA(config.getStringList(key + ".action.hook.message"), loot.getNick())); - if (config.contains(key + ".action.hook.command")) - hookActions.add(new CommandA(config.getStringList(key + ".action.hook.command"), loot.getNick())); - if (config.contains(key + ".action.hook.exp")) - successActions.add(new XPB(config.getInt(key + ".action.hook.exp"))); - if (config.contains(key + ".action.hook.mending")) - successActions.add(new XPA(config.getInt(key + ".action.hook.mending"))); - if (config.contains(key + ".action.hook.skill-xp")) - successActions.add(new FishingXPB(config.getInt(key + ".action.hook.skill-xp"))); - loot.setHookActions(hookActions); - - if (config.contains(key + ".requirements")){ - List requirements = new ArrayList<>(); - config.getConfigurationSection(key + ".requirements").getKeys(false).forEach(requirement -> { - switch (requirement){ - case "weather" -> requirements.add(new Weather(config.getStringList(key + ".requirements.weather"))); - case "ypos" -> requirements.add(new YPos(config.getStringList(key + ".requirements.ypos"))); - case "season" -> { - if (Config.season != null) requirements.add(new Season(config.getStringList(key + ".requirements.season"))); - else AdventureUtil.consoleMessage("[CustomFishing] You need to enable season hook in config.yml to use season condition!"); - } - case "world" -> requirements.add(new World(config.getStringList(key + ".requirements.world"))); - case "biome" -> requirements.add(new Biome(config.getStringList(key + ".requirements.biome"))); - case "permission" -> requirements.add(new Permission(config.getString(key + ".requirements.permission"))); - case "region" -> { - if (Config.wg) requirements.add(new Region(config.getStringList(key + ".requirements.regions"))); - else AdventureUtil.consoleMessage("[CustomFishing] You need to enable WorldGuard Integration to use region condition!"); - } - case "time" -> requirements.add(new Time(config.getStringList(key + ".requirements.time"))); - case "skill-level" -> requirements.add(new SkillLevel(config.getInt(key + ".requirements.skill-level"))); - case "papi-condition" -> { - if (Config.papi) requirements.add(new CustomPapi(config.getConfigurationSection(key + ".requirements.papi-condition").getValues(false))); - else AdventureUtil.consoleMessage("[CustomFishing] You need to enable PlaceholderAPI Integration to use papi condition!"); - } - } - }); - loot.setRequirements(requirements); - } - - String material = config.getString(key + ".material","COD"); - if (material.contains(":")) { - if (material.startsWith("ItemsAdder:")){ - loot.setType("ia"); - loot.setId(material.substring(11)); - } - else if (material.startsWith("Oraxen:")){ - loot.setType("oraxen"); - loot.setId(material.substring(7)); - } - else if (material.startsWith("MMOItems:")){ - loot.setType("mmoitems"); - loot.setId(material.substring(9)); - } - else if (material.startsWith("MythicMobs:")){ - loot.setType("mm"); - loot.setId(material.substring(11)); - } - else { - AdventureUtil.consoleMessage("Unknown Item: " + key); - return; - } - OTHERS.put(key, material); - LOOT.put(key, loot); - } - else { - - Item item = new Item(material); - - 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); - } - loot.setType("default"); - LOOT.put(key, loot); - if (item.getMaterial().equalsIgnoreCase("AIR")) LootItem.put(key, new ItemStack(Material.AIR)); - else LootItem.put(key, ItemStackUtil.getFromItem(item)); - } - }); - } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + LOOT.size() + " loots"); - } - - if (Config.mm){ - File mob_file = new File(CustomFishing.instance.getDataFolder() + File.separator + "mobs"); - if (!mob_file.exists()) { - if (!mob_file.mkdir()) { - AdventureUtil.consoleMessage("[CustomFishing] Error! Failed to create mobs folder..."); - return; - } - CustomFishing.instance.saveResource("mobs" + File.separator + "example.yml", false); - } - File[] mobFiles = mob_file.listFiles(); - if (mobFiles != null) { - - int size = LOOT.size(); - - for (File file : mobFiles) { - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - Set mobs = config.getKeys(false); - mobs.forEach(key -> { - - if (!config.getBoolean(key + ".enable", true)) return; - - Mob loot = new Mob(key, config.getString(key + ".mythicmobsID", key)); - - String[] diff = StringUtils.split(config.getString(key + ".difficulty", "1-1"),"-"); - Difficulty difficulty = new Difficulty(Integer.parseInt(diff[0]), Integer.parseInt(diff[1])); - - int weight = config.getInt(key + ".weight",10); - int time = config.getInt(key + ".time",10000); - - loot.setDifficulty(difficulty); - loot.setTime(time); - loot.setWeight(weight); - if (config.contains(key + ".nick")) loot.setNick(config.getString(key + ".nick")); - else loot.setNick(config.getString(key + ".display.name", key)); - loot.setScore(config.getDouble(key + ".score",0)); - loot.setShowInFinder(config.getBoolean(key + ".show-in-fishfinder", true)); - loot.setMmLevel(config.getInt(key + ".level", 0)); - loot.setMobVector(new MobVector( - config.getDouble(key + ".vector.horizontal",1.1), - config.getDouble(key + ".vector.vertical",1.3) - )); - - if (config.contains(key + ".group")) - loot.setGroup(config.getString(key + ".group")); - if (config.contains(key + ".layout")) - loot.setLayout(config.getStringList(key + ".layout")); - - List successActions = new ArrayList<>(); - if (config.contains(key + ".action.success.message")) - successActions.add(new MessageA(config.getStringList(key + ".action.success.message"), loot.getNick())); - if (config.contains(key + ".action.success.command")) - successActions.add(new CommandA(config.getStringList(key + ".action.success.command"), loot.getNick())); - if (config.contains(key + ".action.success.exp")) - successActions.add(new XPB(config.getInt(key + ".action.success.exp"))); - if (config.contains(key + ".action.success.mending")) - successActions.add(new XPA(config.getInt(key + ".action.success.mending"))); - if (config.contains(key + ".action.success.skill-xp")) - successActions.add(new FishingXPB(config.getInt(key + ".action.success.skill-xp"))); - loot.setSuccessActions(successActions); - - List failureActions = new ArrayList<>(); - if (config.contains(key + ".action.failure.message")) - failureActions.add(new MessageA(config.getStringList(key + ".action.failure.message"), loot.getNick())); - if (config.contains(key + ".action.failure.command")) - failureActions.add(new CommandA(config.getStringList(key + ".action.failure.command"), loot.getNick())); - if (config.contains(key + ".action.failure.exp")) - failureActions.add(new XPB(config.getInt(key + ".action.failure.exp"))); - if (config.contains(key + ".action.failure.mending")) - failureActions.add(new XPA(config.getInt(key + ".action.failure.mending"))); - if (config.contains(key + ".action.failure.skill-xp")) - failureActions.add(new FishingXPB(config.getInt(key + ".action.failure.skill-xp"))); - loot.setFailureActions(failureActions); - - List hookActions = new ArrayList<>(); - if (config.contains(key + ".action.hook.message")) - hookActions.add(new MessageA(config.getStringList(key + ".action.hook.message"), loot.getNick())); - if (config.contains(key + ".action.hook.command")) - hookActions.add(new CommandA(config.getStringList(key + ".action.hook.command"), loot.getNick())); - if (config.contains(key + ".action.hook.exp")) - successActions.add(new XPB(config.getInt(key + ".action.hook.exp"))); - if (config.contains(key + ".action.hook.mending")) - successActions.add(new XPA(config.getInt(key + ".action.hook.mending"))); - if (config.contains(key + ".action.hook.skill-xp")) - successActions.add(new FishingXPB(config.getInt(key + ".action.hook.skill-xp"))); - loot.setHookActions(hookActions); - - if (config.contains(key + ".requirements")){ - List requirements = new ArrayList<>(); - config.getConfigurationSection(key + ".requirements").getKeys(false).forEach(requirement -> { - switch (requirement){ - case "weather" -> requirements.add(new Weather(config.getStringList(key + ".requirements.weather"))); - case "ypos" -> requirements.add(new YPos(config.getStringList(key + ".requirements.ypos"))); - case "season" -> { - if (Config.season != null) requirements.add(new Season(config.getStringList(key + ".requirements.season"))); - else AdventureUtil.consoleMessage("[CustomFishing] You need to enable season hook in config.yml to use season condition!"); - } - case "world" -> requirements.add(new World(config.getStringList(key + ".requirements.world"))); - case "biome" -> requirements.add(new Biome(config.getStringList(key + ".requirements.biome"))); - case "permission" -> requirements.add(new Permission(config.getString(key + ".requirements.permission"))); - case "region" -> { - if (Config.wg) requirements.add(new Region(config.getStringList(key + ".requirements.regions"))); - else AdventureUtil.consoleMessage("[CustomFishing] You need to enable WorldGuard Integration to use region condition!"); - } - case "time" -> requirements.add(new Time(config.getStringList(key + ".requirements.time"))); - case "skill-level" -> requirements.add(new SkillLevel(config.getInt(key + ".requirements.skill-level"))); - case "papi-condition" -> { - if (Config.papi) requirements.add(new CustomPapi(config.getConfigurationSection(key + ".requirements.papi-condition").getValues(false))); - else AdventureUtil.consoleMessage("[CustomFishing] You need to enable PlaceholderAPI Integration to use papi condition!"); - } - } - }); - loot.setRequirements(requirements); - } - LOOT.put(key, loot); - }); - } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + (LOOT.size() - size) + " mobs"); - } - } - } - - public static void loadUtil() { - - UtilItem.clear(); - - File util_file = new File(CustomFishing.instance.getDataFolder() + File.separator + "utils"); - - if (!util_file.exists()) { - if (!util_file.mkdir()) { - AdventureUtil.consoleMessage("[CustomFishing] Error! Failed to create utils folder..."); - return; - } - CustomFishing.instance.saveResource("utils" + File.separator + "fishfinder.yml", false); - } - - File[] files = util_file.listFiles(); - - if (files != null) { - for (File file : files) { - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - Set keys = config.getKeys(false); - keys.forEach(key -> { - - if (!config.getBoolean(key + ".enable", true)) return; - - Item item = new Item(config.getString(key + ".material", "COMPASS")); - 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); - } - UtilItem.put(key, NBTUtil.addIdentifier(ItemStackUtil.getFromItem(item), "util", key)); - }); - } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + UtilItem.size() + " utils"); - } - } - - public static void loadRod() { - - ROD.clear(); - RodItem.clear(); - - File rod_file = new File(CustomFishing.instance.getDataFolder() + File.separator + "rods"); - - if (!rod_file.exists()) { - if (!rod_file.mkdir()) { - AdventureUtil.consoleMessage("[CustomFishing] Error! Failed to create rods folder..."); - return; - } - CustomFishing.instance.saveResource("rods" + File.separator + "default.yml", false); - } - - File[] files = rod_file.listFiles(); - - if (files != null) { - for (File file : files) { - - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - Set keys = config.getKeys(false); - - keys.forEach(key -> { - - Item item = new Item("FISHING_ROD"); - 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); - } - RodItem.put(key, NBTUtil.addIdentifier(ItemStackUtil.getFromItem(item), "rod", key)); - - if (config.contains(key + ".modifier")) { - Bonus bonus = new Bonus(); - config.getConfigurationSection(key + ".modifier").getKeys(false).forEach(modifier -> { - switch (modifier) { - case "weight-PM" -> { - HashMap pm = new HashMap<>(); - config.getConfigurationSection(key + ".modifier.weight-PM").getValues(false).forEach((group, value) -> { - pm.put(group, (Integer) value); - }); - bonus.setWeightPM(pm); - } - case "weight-MQ" -> { - HashMap mq = new HashMap<>(); - config.getConfigurationSection(key + ".modifier.weight-MQ").getValues(false).forEach((group, value) -> { - mq.put(group, Double.parseDouble(String.valueOf(value))-1); - }); - bonus.setWeightMQ(mq); - } - 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")); - } - }); - ROD.put(key, bonus); - } - }); - } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + RodItem.size() + " rods"); - } - } - - public static void loadBait(){ - - BAIT.clear(); - BaitItem.clear(); - - File bait_file = new File(CustomFishing.instance.getDataFolder() + File.separator + "baits"); - - if (!bait_file.exists()) { - if (!bait_file.mkdir()) { - AdventureUtil.consoleMessage("[CustomFishing] Error! Failed to create baits folder..."); - return; - } - CustomFishing.instance.saveResource("baits" + File.separator + "default.yml", false); - } - - File[] files = bait_file.listFiles(); - - if (files != null) { - for (File file : files) { - - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - Set keys = config.getKeys(false); - keys.forEach(key -> { - - Item item = new Item(config.getString(key + ".material", "PAPER")); - 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); - } - BaitItem.put(key, NBTUtil.addIdentifier(ItemStackUtil.getFromItem(item), "bait", key)); - - if (config.contains(key + ".modifier")) { - Bonus bonus = new Bonus(); - config.getConfigurationSection(key + ".modifier").getKeys(false).forEach(modifier -> { - switch (modifier) { - case "weight-PM" -> { - HashMap pm = new HashMap<>(); - config.getConfigurationSection(key + ".modifier.weight-PM").getValues(false).forEach((group, value) -> { - pm.put(group, (Integer) value); - }); - bonus.setWeightPM(pm); - } - case "weight-MQ" -> { - HashMap mq = new HashMap<>(); - config.getConfigurationSection(key + ".modifier.weight-MQ").getValues(false).forEach((group, value) -> { - mq.put(group, Double.parseDouble(String.valueOf(value))-1); - }); - bonus.setWeightMQ(mq); - } - 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")); - } - }); - BAIT.put(key, bonus); - } - }); - } - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + BaitItem.size() + " baits"); - } - } - - public static void loadCompetitions(){ - - CompetitionsT.clear(); - CompetitionsC.clear(); - - YamlConfiguration config = getConfig("competition.yml"); - - Set keys = config.getKeys(false); - keys.forEach(key -> { - CompetitionConfig competitionConfig; - boolean enableBsb = config.getBoolean(key + ".bossbar.enable", false); - if (enableBsb){ - competitionConfig = new CompetitionConfig(true); - BossBarConfig bossBarConfig = new BossBarConfig( - config.getString(key + ".bossbar.text", "You forget to set text for bossbar"), - BossBar.Overlay.valueOf(config.getString(key + ".bossbar.overlay","SOLID").toUpperCase()), - BossBar.Color.valueOf(config.getString(key + ".bossbar.color","WHITE").toUpperCase()), - config.getInt(key + ".bossbar.refresh-rate",5) - ); - competitionConfig.setBossBarConfig(bossBarConfig); - } else competitionConfig = new CompetitionConfig(false); - - competitionConfig.setDuration(config.getInt(key + ".duration",600)); - competitionConfig.setGoal(Goal.valueOf(config.getString(key + ".goal", "RANDOM"))); - if (config.contains(key + ".broadcast.start")) - competitionConfig.setStartMessage(config.getStringList(key + ".broadcast.start")); - if (config.contains(key + ".broadcast.end")) - competitionConfig.setEndMessage(config.getStringList(key + ".broadcast.end")); - if (config.contains(key + ".command.join")) - competitionConfig.setJoinCommand(config.getStringList(key + ".command.join")); - if (config.contains(key + ".command.start")) - competitionConfig.setStartCommand(config.getStringList(key + ".command.start")); - if (config.contains(key + ".command.end")) - competitionConfig.setEndCommand(config.getStringList(key + ".command.end")); - if (config.contains(key + ".min-players")) - competitionConfig.setMinPlayers(config.getInt(key + ".min-players")); - if (config.contains(key + ".prize")){ - HashMap> rewardsMap = new HashMap<>(); - config.getConfigurationSection(key + ".prize").getKeys(false).forEach(rank -> { - List rewards = new ArrayList<>(); - if (config.contains(key + ".prize." + rank + ".messages")) - rewards.add(new MessageB(config.getStringList(key + ".prize." + rank + ".messages"))); - if (config.contains(key + ".prize." + rank + ".commands")) - rewards.add(new CommandB(config.getStringList(key + ".prize." + rank + ".commands"))); - rewardsMap.put(rank, rewards); - }); - competitionConfig.setRewards(rewardsMap); - } - if (config.contains(key + ".start-time")){ - config.getStringList(key + ".start-time").forEach(time -> CompetitionsT.put(time, competitionConfig)); - } - CompetitionsC.put(key, competitionConfig); - }); - } - - public static void tryEnableJedis(){ - YamlConfiguration configuration = ConfigReader.getConfig("redis.yml"); - useRedis = false; - if (configuration.getBoolean("redis.enable")){ - JedisUtil.initializeRedis(configuration); - useRedis = true; - } - } - - public static void loadBars(){ - LAYOUT.clear(); - YamlConfiguration config = ConfigReader.getConfig("bars.yml"); - Set keys = config.getKeys(false); - keys.forEach(key -> { - 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); - layout.setTitle(config.getString(key + ".title"," ")); - layout.setBar(config.getString(key + ".subtitle.bar","뀃")); - layout.setEnd(config.getString(key + ".subtitle.end","")); - layout.setStart(config.getString(key + ".subtitle.start","")); - layout.setPointer(config.getString(key + ".subtitle.pointer","뀄")); - layout.setPointerOffset(config.getString(key + ".subtitle.pointer_offset","뀂")); - layout.setOffset(config.getString(key + ".subtitle.offset","뀁")); - LAYOUT.put(key, layout); - }); - } - - public static void loadEnchants(){ - - ENCHANTS.clear(); - - YamlConfiguration config = ConfigReader.getConfig("enchant-bonus.yml"); - Set keys = config.getKeys(false); - keys.forEach(key -> { - HashMap levelBonus = new HashMap<>(); - config.getConfigurationSection(key).getKeys(false).forEach(level -> { - Bonus bonus = new Bonus(); - config.getConfigurationSection(key + "." + level).getKeys(false).forEach(modifier -> { - switch (modifier) { - case "weight-PM" -> { - HashMap pm = new HashMap<>(); - config.getConfigurationSection(key + "." + level + ".weight-PM").getValues(false).forEach((group, value) -> { - pm.put(group, (Integer) value); - }); - bonus.setWeightPM(pm); - } - case "weight-MQ" -> { - HashMap mq = new HashMap<>(); - config.getConfigurationSection(key + "." + level + ".weight-MQ").getValues(false).forEach((group, value) -> { - mq.put(group, Double.parseDouble(String.valueOf(value))-1); - }); - bonus.setWeightMQ(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")); - } - }); - levelBonus.put(Integer.parseInt(level), bonus); - }); - ENCHANTS.put(key, levelBonus); - }); - AdventureUtil.consoleMessage("[CustomFishing] Loaded " + ENCHANTS.size() + " enchantments"); - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/CustomFishing.java b/src/main/java/net/momirealms/customfishing/CustomFishing.java index 4f97549a..37254434 100644 --- a/src/main/java/net/momirealms/customfishing/CustomFishing.java +++ b/src/main/java/net/momirealms/customfishing/CustomFishing.java @@ -17,34 +17,54 @@ package net.momirealms.customfishing; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.ProtocolManager; import net.kyori.adventure.platform.bukkit.BukkitAudiences; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.momirealms.customfishing.command.Execute; -import net.momirealms.customfishing.command.TabComplete; +import net.momirealms.customfishing.commands.PluginCommand; import net.momirealms.customfishing.competition.CompetitionSchedule; -import net.momirealms.customfishing.competition.bossbar.BossBarManager; import net.momirealms.customfishing.helper.LibraryLoader; -import net.momirealms.customfishing.hook.Placeholders; -import net.momirealms.customfishing.hook.skill.JobsReborn; -import net.momirealms.customfishing.listener.*; -import net.momirealms.customfishing.utils.AdventureUtil; -import net.momirealms.customfishing.utils.ConfigUtil; +import net.momirealms.customfishing.manager.FishingManager; +import net.momirealms.customfishing.manager.IntegrationManager; +import net.momirealms.customfishing.manager.MessageManager; +import net.momirealms.customfishing.util.AdventureUtil; +import net.momirealms.customfishing.util.ConfigUtil; +import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; -import java.util.Objects; - public final class CustomFishing extends JavaPlugin { - public static JavaPlugin instance; + public static CustomFishing plugin; public static BukkitAudiences adventure; - public static MiniMessage miniMessage; + public static ProtocolManager protocolManager; + + private IntegrationManager integrationManager; + private FishingManager fishingManager; private CompetitionSchedule competitionSchedule; - public static Placeholders placeholders; + +// _ooOoo_ +// o8888888o +// 88" . "88 +// (| -_- |) +// O\ = /O +// ____/`---'\____ +// .' \\| |// `. +// / \\||| : |||// \ +// / _||||| -:- |||||_ \ +// | | \\\ - /'| | | +// | \_| `\`---'// |_/ | +// \ .-\__ `-. -'__/-. / +// ___`. .' /--.--\ `. .'___ +// ."" '< `.___\_<|>_/___.' _> \"". +// | | : `- \`. ;`. _/; .'/ / .' ; | +// \ \ `-. \_\_`. _.'_/_/ -' _.' / +// ================-.`___`-.__\ \___ /__.-'_.'_.-'================ +// `=--=-' +// 佛祖保佑 永无BUG 永不卡服 @Override - public void onLoad(){ - instance = this; + public void onLoad() { + plugin = this; LibraryLoader.load("redis.clients","jedis","4.2.3","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/"); @@ -52,60 +72,37 @@ public final class CustomFishing extends JavaPlugin { @Override public void onEnable() { - adventure = BukkitAudiences.create(this); - miniMessage = MiniMessage.miniMessage(); - Objects.requireNonNull(Bukkit.getPluginCommand("customfishing")).setExecutor(new Execute()); - Objects.requireNonNull(Bukkit.getPluginCommand("customfishing")).setTabCompleter(new TabComplete()); - Bukkit.getPluginManager().registerEvents(new FishListener(),this); + protocolManager = ProtocolLibrary.getProtocolManager(); + this.fishingManager = new FishingManager(); + this.integrationManager = new IntegrationManager(); + this.competitionSchedule = new CompetitionSchedule(); + ConfigUtil.reload(); - AdventureUtil.consoleMessage("[CustomFishing] Running on " + Bukkit.getVersion()); - - Bukkit.getScheduler().runTaskAsynchronously(this, ()-> { - - ConfigReader.Reload(); - - if (ConfigReader.Config.competition){ - competitionSchedule = new CompetitionSchedule(); - competitionSchedule.checkTime(); - Bukkit.getScheduler().runTask(this, () -> Bukkit.getPluginManager().registerEvents(new BossBarManager(), this)); - } - - if (ConfigReader.Config.papi){ - placeholders = new Placeholders(); - Bukkit.getScheduler().runTask(this, () -> { - placeholders.register(); - Bukkit.getPluginManager().registerEvents(new PapiUnregister(), this); - }); - } - - if (ConfigReader.Config.preventPick) - Bukkit.getScheduler().runTask(this, () -> Bukkit.getPluginManager().registerEvents(new PickUpListener(),this)); - if (!Objects.equals(ConfigReader.Config.version, "8")) - ConfigUtil.update(); - if (ConfigReader.Config.convertMMOItems) - Bukkit.getScheduler().runTask(this, () -> Bukkit.getPluginManager().registerEvents(new MMOItemsListener(), this)); - if (ConfigReader.Config.disableJobXp) - Bukkit.getScheduler().runTask(this, () -> Bukkit.getPluginManager().registerEvents(new JobsListener(), this)); - - ConfigReader.tryEnableJedis(); - - AdventureUtil.consoleMessage("[CustomFishing] Plugin Enabled!"); - }); + PluginCommand pluginCommand = new PluginCommand(); + Bukkit.getPluginCommand("customfishing").setExecutor(pluginCommand); + Bukkit.getPluginCommand("customfishing").setTabCompleter(pluginCommand); + AdventureUtil.consoleMessage("[CustomFishing] Plugin Enabled!"); + new Metrics(this, 16648); } @Override public void onDisable() { - if (competitionSchedule != null){ - competitionSchedule.stopCheck(); - competitionSchedule = null; - } if (adventure != null) { adventure.close(); adventure = null; } - if (instance != null){ - instance = null; - } + } + + public IntegrationManager getIntegrationManager() { + return integrationManager; + } + + public FishingManager getFishingManager() { + return fishingManager; + } + + public CompetitionSchedule getCompetitionSchedule() { + return competitionSchedule; } } diff --git a/src/main/java/net/momirealms/customfishing/Function.java b/src/main/java/net/momirealms/customfishing/Function.java new file mode 100644 index 00000000..2f4e6a59 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/Function.java @@ -0,0 +1,22 @@ +package net.momirealms.customfishing; + +import org.bukkit.entity.Player; + +public class Function { + + public void load() { + //empty + } + + public void unload() { + //empty + } + + public void onQuit(Player player) { + + } + + public void onJoin(Player player) { + + } +} diff --git a/src/main/java/net/momirealms/customfishing/api/CustomFishingAPI.java b/src/main/java/net/momirealms/customfishing/api/CustomFishingAPI.java index 8b71a94a..2d30e13f 100644 --- a/src/main/java/net/momirealms/customfishing/api/CustomFishingAPI.java +++ b/src/main/java/net/momirealms/customfishing/api/CustomFishingAPI.java @@ -1,13 +1,7 @@ package net.momirealms.customfishing.api; -import net.momirealms.customfishing.ConfigReader; -import net.momirealms.customfishing.object.loot.Loot; -import org.jetbrains.annotations.Nullable; - public class CustomFishingAPI { - @Nullable - public static Loot getLoot(String key){ - return ConfigReader.LOOT.get(key); - } + + } diff --git a/src/main/java/net/momirealms/customfishing/api/event/FishFinderEvent.java b/src/main/java/net/momirealms/customfishing/api/event/FishFinderEvent.java new file mode 100644 index 00000000..983467db --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/api/event/FishFinderEvent.java @@ -0,0 +1,43 @@ +package net.momirealms.customfishing.api.event; + +import net.momirealms.customfishing.object.loot.Loot; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class FishFinderEvent extends PlayerEvent implements Cancellable { + + private static final HandlerList handlerList = new HandlerList(); + + private boolean cancelled; + private final List loots; + + public FishFinderEvent(@NotNull Player who, List loots) { + super(who); + this.cancelled = false; + this.loots = loots; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlerList; + } + + public List getLoots() { + return loots; + } +} diff --git a/src/main/java/net/momirealms/customfishing/api/event/FishHookEvent.java b/src/main/java/net/momirealms/customfishing/api/event/FishHookEvent.java new file mode 100644 index 00000000..1ed042f9 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/api/event/FishHookEvent.java @@ -0,0 +1,40 @@ +package net.momirealms.customfishing.api.event; + +import net.momirealms.customfishing.object.Difficulty; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; +import org.jetbrains.annotations.NotNull; + +public class FishHookEvent extends PlayerEvent implements Cancellable { + + private boolean cancelled; + private final Difficulty difficulty; + private static final HandlerList handlerList = new HandlerList(); + + public FishHookEvent(@NotNull Player who, Difficulty difficulty) { + super(who); + this.cancelled = false; + this.difficulty = difficulty; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlerList; + } + + public Difficulty getDifficulty() { + return 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 new file mode 100644 index 00000000..efa93e6a --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/api/event/FishResultEvent.java @@ -0,0 +1,61 @@ +package net.momirealms.customfishing.api.event; + +import net.momirealms.customfishing.object.Difficulty; +import net.momirealms.customfishing.object.FishResult; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class FishResultEvent extends PlayerEvent implements Cancellable { + + private boolean cancelled; + private boolean isDouble; + private final FishResult result; + private final ItemStack loot; + private static final HandlerList handlerList = new HandlerList(); + + public FishResultEvent(@NotNull Player who, FishResult result, boolean isDouble, ItemStack loot) { + super(who); + this.cancelled = false; + this.result = result; + this.isDouble = isDouble; + this.loot = loot; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlerList; + } + + public boolean isDouble() { + return isDouble; + } + + @NotNull + public FishResult getResult() { + return result; + } + + @Nullable + public ItemStack getLoot() { + return loot; + } + + public void setDouble(boolean willDouble) { + isDouble = willDouble; + } +} diff --git a/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java b/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java new file mode 100644 index 00000000..44d63992 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java @@ -0,0 +1,40 @@ +package net.momirealms.customfishing.api.event; + +import net.momirealms.customfishing.object.Bonus; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; +import org.jetbrains.annotations.NotNull; + +public class RodCastEvent extends PlayerEvent implements Cancellable { + + private final Bonus bonus; + private boolean isCancelled; + private static final HandlerList handlerList = new HandlerList(); + + public RodCastEvent(@NotNull Player who, @NotNull Bonus bonus) { + super(who); + this.isCancelled = false; + this.bonus = bonus; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlerList; + } + + public Bonus getBonus() { + return bonus; + } +} diff --git a/src/main/java/net/momirealms/customfishing/api/event/TotemActivationEvent.java b/src/main/java/net/momirealms/customfishing/api/event/TotemActivationEvent.java new file mode 100644 index 00000000..2d350828 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/api/event/TotemActivationEvent.java @@ -0,0 +1,4 @@ +package net.momirealms.customfishing.api.event; + +public class TotemActivationEvent { +} diff --git a/src/main/java/net/momirealms/customfishing/command/Execute.java b/src/main/java/net/momirealms/customfishing/command/Execute.java deleted file mode 100644 index ef6048a1..00000000 --- a/src/main/java/net/momirealms/customfishing/command/Execute.java +++ /dev/null @@ -1,428 +0,0 @@ -package net.momirealms.customfishing.command; - -import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.competition.CompetitionSchedule; -import net.momirealms.customfishing.utils.AdventureUtil; -import net.momirealms.customfishing.ConfigReader; -import net.momirealms.customfishing.utils.ItemUtil; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import javax.print.DocFlavor; - -public class Execute implements CommandExecutor { - - @Override - public boolean onCommand(CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - - if (!(sender.hasPermission("customfishing.admin") || sender.isOp())) { - AdventureUtil.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.noPerm); - return true; - } - - if (args.length < 1){ - lackArgs(sender); - return true; - } - - if (args[0].equalsIgnoreCase("reload")) { - Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.instance, ()-> { - ConfigReader.Reload(); - if (sender instanceof Player){ - AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.reload); - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.reload); - } - }); - return true; - } - - if (args[0].equalsIgnoreCase("import")) { - if (args.length < 2){ - lackArgs(sender); - return true; - } - if (sender instanceof Player player){ - ItemUtil.saveToFile(player.getInventory().getItemInMainHand(), args[1]); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + "Done! File is saved to /CustomFishing/loots/" + args[1] + ".yml"); - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.noConsole); - } - return true; - } - - if (args[0].equalsIgnoreCase("competition")) { - //检验参数长度 [0]competition [1]start/end [2]key - if (args.length < 2){ - lackArgs(sender); - return true; - } - if (args[1].equalsIgnoreCase("start")){ - if (args.length < 3){ - lackArgs(sender); - return true; - } - if (CompetitionSchedule.startCompetition(args[2])){ - forceSuccess(sender); - }else { - forceFailure(sender); - } - }else if (args[1].equalsIgnoreCase("end")){ - CompetitionSchedule.endCompetition(); - forceEnd(sender); - }else if (args[1].equalsIgnoreCase("cancel")){ - CompetitionSchedule.cancelCompetition(); - forceCancel(sender); - } - return true; - } - - if (args[0].equalsIgnoreCase("items")) { - if (args.length < 4){ - lackArgs(sender); - return true; - } - if (args[1].equalsIgnoreCase("loot")) { - if (args[2].equalsIgnoreCase("get")) { - //检验参数长度 [0]items [1]loot [2]get [3]xxx [4](amount) - if (sender instanceof Player player){ - //是否存在于缓存中 - if (ConfigReader.LootItem.containsKey(args[3])){ - if (args.length == 4){ - ItemUtil.givePlayerLoot(player, args[3], 1); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", "1").replace("{Item}",args[3])); - }else { - if (Integer.parseInt(args[4]) < 1){ - wrongAmount(sender); - return true; - } - ItemUtil.givePlayerLoot(player, args[3], Integer.parseInt(args[4])); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3])); - } - }else if (ConfigReader.OTHERS.containsKey(args[3])){ - if (args.length == 4){ - player.getInventory().addItem(ItemUtil.getItemStackFromOtherPlugins(args[3])); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", "1").replace("{Item}",args[3])); - }else { - if (Integer.parseInt(args[4]) < 1){ - wrongAmount(sender); - return true; - } - ItemStack itemStack = ItemUtil.getItemStackFromOtherPlugins(args[3]); - itemStack.setAmount(Integer.parseInt(args[4])); - player.getInventory().addItem(itemStack); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3])); - } - }else { - noItem(sender); - return true; - } - - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.noConsole); - } - return true; - } - if (args[2].equalsIgnoreCase("give")) { - //检验参数长度 [0]items [1]loot [2]give [3]player [4]xxx [5](amount) - if (args.length < 5){ - lackArgs(sender); - return true; - } - Player player = Bukkit.getPlayer(args[3]); - //玩家是否在线 - if (player == null){ - notOnline(sender); - return true; - } - //是否存在于缓存中 - if (ConfigReader.LootItem.containsKey(args[4])){ - if (args.length == 5){ - ItemUtil.givePlayerLoot(player, args[4], 1); - giveItem(sender, args[3], args[4], 1); - return true; - } - else { - if (Integer.parseInt(args[5]) < 1){ - wrongAmount(sender); - return true; - } - ItemUtil.givePlayerLoot(player, args[4], Integer.parseInt(args[5])); - giveItem(sender, args[3], args[4], Integer.parseInt(args[5])); - } - }else if (ConfigReader.OTHERS.containsKey(args[4])){ - if (args.length == 5){ - player.getInventory().addItem(ItemUtil.getItemStackFromOtherPlugins(args[4])); - giveItem(sender, args[3], args[4], 1); - return true; - } - else { - if (Integer.parseInt(args[5]) < 1) { - wrongAmount(sender); - return true; - } - ItemStack itemStack = ItemUtil.getItemStackFromOtherPlugins(args[4]); - itemStack.setAmount(Integer.parseInt(args[5])); - player.getInventory().addItem(itemStack); - giveItem(sender, args[3], args[4], Integer.parseInt(args[5])); - } - }else { - noItem(sender); - return true; - } - return true; - } - } - /* - 给予实用物品 - */ - else if(args[1].equalsIgnoreCase("util")){ - if (args[2].equalsIgnoreCase("get")) { - //检验参数长度 [0]items [1]util [2]get [3]xxx [4](amount) - if (sender instanceof Player player){ - //是否存在于缓存中 - if (!ConfigReader.UtilItem.containsKey(args[3])){ - noItem(sender); - return true; - } - if (args.length == 4){ - ItemUtil.givePlayerUtil(player, args[3], 1); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", "1").replace("{Item}",args[3])); - }else { - if (Integer.parseInt(args[4]) < 1){ - wrongAmount(sender); - return true; - } - ItemUtil.givePlayerUtil(player, args[3], Integer.parseInt(args[4])); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3])); - } - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.noConsole); - } - return true; - } - if (args[2].equalsIgnoreCase("give")) { - //检验参数长度 [0]items [1]util [2]give [3]player [4]xxx [5](amount) - if (args.length < 5){ - lackArgs(sender); - return true; - } - Player player = Bukkit.getPlayer(args[3]); - //玩家是否在线 - if (player == null){ - notOnline(sender); - return true; - } - //是否存在于缓存中 - if (!ConfigReader.UtilItem.containsKey(args[4])){ - noItem(sender); - return true; - } - if (args.length == 5){ - ItemUtil.givePlayerUtil(player, args[4], 1); - giveItem(sender, args[3], args[4], 1); - }else { - if (Integer.parseInt(args[5]) < 1){ - wrongAmount(sender); - return true; - } - ItemUtil.givePlayerUtil(player, args[4], Integer.parseInt(args[5])); - giveItem(sender, args[3], args[4], Integer.parseInt(args[5])); - } - return true; - } - } - else if (args[1].equalsIgnoreCase("rod")){ - if (args[2].equalsIgnoreCase("get")) { - //检验参数长度 [0]items [1]rod [2]get [3]xxx [4](amount) - if (sender instanceof Player player){ - //是否存在于缓存中 - if (!ConfigReader.RodItem.containsKey(args[3])){ - noItem(sender); - return true; - } - if (args.length == 4){ - ItemUtil.givePlayerRod(player, args[3], 1); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", "1").replace("{Item}",args[3])); - }else { - if (Integer.parseInt(args[4]) < 1){ - wrongAmount(sender); - return true; - } - ItemUtil.givePlayerRod(player, args[3], Integer.parseInt(args[4])); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3])); - } - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.noConsole); - } - return true; - } - if (args[2].equalsIgnoreCase("give")) { - //检验参数长度 [0]items [1]rod [2]give [3]player [4]xxx [5](amount) - if (args.length < 5){ - lackArgs(sender); - return true; - } - Player player = Bukkit.getPlayer(args[3]); - //玩家是否在线 - if (player == null){ - notOnline(sender); - return true; - } - //是否存在于缓存中 - if (!ConfigReader.RodItem.containsKey(args[4])){ - noItem(sender); - return true; - } - if (args.length == 5){ - ItemUtil.givePlayerRod(player, args[4], 1); - giveItem(sender, args[3], args[4], 1); - }else { - if (Integer.parseInt(args[5]) < 1){ - wrongAmount(sender); - return true; - } - ItemUtil.givePlayerRod(player, args[4], Integer.parseInt(args[5])); - giveItem(sender, args[3], args[4], Integer.parseInt(args[5])); - } - return true; - } - } - else if (args[1].equalsIgnoreCase("bait")){ - if (args[2].equalsIgnoreCase("get")) { - //检验参数长度 [0]items [1]bait [2]get [3]xxx [4](amount) - if (sender instanceof Player player){ - //是否存在于缓存中 - if (!ConfigReader.BaitItem.containsKey(args[3])){ - noItem(sender); - return true; - } - if (args.length == 4){ - ItemUtil.givePlayerBait(player, args[3], 1); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", "1").replace("{Item}",args[3])); - }else { - if (Integer.parseInt(args[4]) < 1){ - wrongAmount(sender); - return true; - } - ItemUtil.givePlayerBait(player, args[3], Integer.parseInt(args[4])); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3])); - } - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.noConsole); - } - return true; - } - if (args[2].equalsIgnoreCase("give")) { - //检验参数长度 [0]items [1]bait [2]give [3]player [4]xxx [5](amount) - if (args.length < 5){ - lackArgs(sender); - return true; - } - Player player = Bukkit.getPlayer(args[3]); - //玩家是否在线 - if (player == null){ - notOnline(sender); - return true; - } - //是否存在于缓存中 - if (!ConfigReader.BaitItem.containsKey(args[4])){ - noItem(sender); - return true; - } - if (args.length == 5){ - ItemUtil.givePlayerBait(player, args[4], 1); - giveItem(sender, args[3], args[4], 1); - }else { - if (Integer.parseInt(args[5]) < 1){ - wrongAmount(sender); - return true; - } - ItemUtil.givePlayerBait(player, args[4], Integer.parseInt(args[5])); - giveItem(sender, args[3], args[4], Integer.parseInt(args[5])); - } - return true; - } - } - } - return true; - } - - private void lackArgs(CommandSender sender){ - if (sender instanceof Player){ - AdventureUtil.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.lackArgs); - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.lackArgs); - } - } - - private void notOnline(CommandSender sender){ - if (sender instanceof Player){ - AdventureUtil.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.notOnline); - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.notOnline); - } - } - - private void noItem(CommandSender sender){ - if (sender instanceof Player){ - AdventureUtil.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.notExist); - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.notExist); - } - } - - private void giveItem(CommandSender sender, String name, String item, int amount){ - String string = ConfigReader.Message.prefix + ConfigReader.Message.giveItem.replace("{Amount}", String.valueOf(amount)).replace("{Player}",name).replace("{Item}",item); - if (sender instanceof Player){ - AdventureUtil.playerMessage((Player) sender, string); - }else { - AdventureUtil.consoleMessage(string); - } - } - - private void wrongAmount(CommandSender sender){ - if (sender instanceof Player){ - AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.wrongAmount); - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.wrongAmount); - } - } - - private void forceSuccess(CommandSender sender){ - if (sender instanceof Player){ - AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.forceSuccess); - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.forceSuccess); - } - } - - private void forceFailure(CommandSender sender){ - if (sender instanceof Player){ - AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.forceFailure); - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.forceFailure); - } - } - - private void forceEnd(CommandSender sender){ - if (sender instanceof Player){ - AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.forceEnd); - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.forceEnd); - } - } - - private void forceCancel(CommandSender sender){ - if (sender instanceof Player){ - AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.forceCancel); - }else { - AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.forceCancel); - } - } -} diff --git a/src/main/java/net/momirealms/customfishing/command/TabComplete.java b/src/main/java/net/momirealms/customfishing/command/TabComplete.java deleted file mode 100644 index cc5bd1eb..00000000 --- a/src/main/java/net/momirealms/customfishing/command/TabComplete.java +++ /dev/null @@ -1,252 +0,0 @@ -package net.momirealms.customfishing.command; - -import net.momirealms.customfishing.ConfigReader; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class TabComplete implements TabCompleter { - @Override - public List onTabComplete(CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { - - if (!(sender.hasPermission("customfishing.admin") || sender.isOp())) { - return null; - } - if (args.length == 1){ - List arrayList = new ArrayList<>(); - for (String cmd : Arrays.asList("competition","reload", "items","import")) { - if (cmd.startsWith(args[0])) - arrayList.add(cmd); - } - return arrayList; - } - if (args.length == 2){ - if (args[0].equalsIgnoreCase("items")){ - List arrayList = new ArrayList<>(); - for (String cmd : Arrays.asList("loot","bait","rod","util")) { - if (cmd.startsWith(args[1])) - arrayList.add(cmd); - } - return arrayList; - } - if (args[0].equalsIgnoreCase("import")){ - return List.of("FileName"); - } - if (args[0].equalsIgnoreCase("competition")){ - List arrayList = new ArrayList<>(); - for (String cmd : List.of("start","end","cancel")) { - if (cmd.startsWith(args[1])) - arrayList.add(cmd); - } - return arrayList; - } - } - if (args.length == 3){ - if (args[0].equalsIgnoreCase("items")){ - if (args[1].equalsIgnoreCase("loot") || args[1].equalsIgnoreCase("util") || args[1].equalsIgnoreCase("rod") || args[1].equalsIgnoreCase("bait")){ - List arrayList = new ArrayList<>(); - for (String cmd : Arrays.asList("get","give")) { - if (cmd.startsWith(args[2])) - arrayList.add(cmd); - } - return arrayList; - } - } - if (args[0].equalsIgnoreCase("competition")){ - if (args[1].equalsIgnoreCase("start")){ - List arrayList = new ArrayList<>(); - for (String cmd : competitions()) { - if (cmd.startsWith(args[2])) - arrayList.add(cmd); - } - return arrayList; - } - } - } - if (args.length == 4){ - if (args[0].equalsIgnoreCase("items")){ - if (args[1].equalsIgnoreCase("loot")){ - if (args[2].equalsIgnoreCase("give")){ - List arrayList = new ArrayList<>(); - for (String cmd : online_players()) { - if (cmd.startsWith(args[3])) - arrayList.add(cmd); - } - return arrayList; - } - if (args[2].equalsIgnoreCase("get")){ - List arrayList = new ArrayList<>(); - for (String cmd : loots()) { - if (cmd.startsWith(args[3])) - arrayList.add(cmd); - } - return arrayList; - } - }else if (args[1].equalsIgnoreCase("util")){ - if (args[2].equalsIgnoreCase("give")){ - List arrayList = new ArrayList<>(); - for (String cmd : online_players()) { - if (cmd.startsWith(args[3])) - arrayList.add(cmd); - } - return arrayList; - } - if (args[2].equalsIgnoreCase("get")){ - List arrayList = new ArrayList<>(); - for (String cmd : utils()) { - if (cmd.startsWith(args[3])) - arrayList.add(cmd); - } - return arrayList; - } - }else if (args[1].equalsIgnoreCase("rod")){ - if (args[2].equalsIgnoreCase("give")){ - List arrayList = new ArrayList<>(); - for (String cmd : online_players()) { - if (cmd.startsWith(args[3])) - arrayList.add(cmd); - } - return arrayList; - } - if (args[2].equalsIgnoreCase("get")){ - List arrayList = new ArrayList<>(); - for (String cmd : rods()) { - if (cmd.startsWith(args[3])) - arrayList.add(cmd); - } - return arrayList; - } - }else if (args[1].equalsIgnoreCase("bait")){ - if (args[2].equalsIgnoreCase("give")){ - List arrayList = new ArrayList<>(); - for (String cmd : online_players()) { - if (cmd.startsWith(args[3])) - arrayList.add(cmd); - } - return arrayList; - } - if (args[2].equalsIgnoreCase("get")){ - List arrayList = new ArrayList<>(); - for (String cmd : baits()) { - if (cmd.startsWith(args[3])) - arrayList.add(cmd); - } - return arrayList; - } - } - } - } - if (args.length == 5){ - if (args[0].equalsIgnoreCase("items")){ - if (args[1].equalsIgnoreCase("loot")){ - if (args[2].equalsIgnoreCase("give")){ - List arrayList = new ArrayList<>(); - for (String cmd : loots()) { - if (cmd.startsWith(args[4])) - arrayList.add(cmd); - } - return arrayList; - } - if (args[2].equalsIgnoreCase("get")){ - return Arrays.asList("1","16","64"); - } - }else if (args[1].equalsIgnoreCase("util")){ - if (args[2].equalsIgnoreCase("give")){ - List arrayList = new ArrayList<>(); - for (String cmd : utils()) { - if (cmd.startsWith(args[4])) - arrayList.add(cmd); - } - return arrayList; - } - if (args[2].equalsIgnoreCase("get")){ - return Arrays.asList("1","16","64"); - } - }else if (args[1].equalsIgnoreCase("rod")){ - if (args[2].equalsIgnoreCase("give")){ - List arrayList = new ArrayList<>(); - for (String cmd : rods()) { - if (cmd.startsWith(args[4])) - arrayList.add(cmd); - } - return arrayList; - } - if (args[2].equalsIgnoreCase("get")){ - return Arrays.asList("1","16","64"); - } - } - else if (args[1].equalsIgnoreCase("bait")){ - if (args[2].equalsIgnoreCase("give")){ - List arrayList = new ArrayList<>(); - for (String cmd : baits()) { - if (cmd.startsWith(args[4])) - arrayList.add(cmd); - } - return arrayList; - } - if (args[2].equalsIgnoreCase("get")){ - return Arrays.asList("1","16","64"); - } - } - } - } - if (args.length == 6){ - if (args[0].equalsIgnoreCase("items")){ - if (args[1].equalsIgnoreCase("loot")){ - if (args[2].equalsIgnoreCase("give")){ - return Arrays.asList("1","16","64"); - } - }else if (args[1].equalsIgnoreCase("util")){ - if (args[2].equalsIgnoreCase("give")){ - return Arrays.asList("1","16","64"); - } - }else if (args[1].equalsIgnoreCase("rod")){ - if (args[2].equalsIgnoreCase("give")){ - return List.of("1"); - } - } - else if (args[1].equalsIgnoreCase("bait")){ - if (args[2].equalsIgnoreCase("give")){ - return Arrays.asList("1","16","64"); - } - } - } - } - return null; - } - - private List online_players(){ - List online = new ArrayList<>(); - Bukkit.getOnlinePlayers().forEach((player -> online.add(player.getName()))); - return online; - } - - private List loots(){ - ArrayList loots = new ArrayList<>(); - loots.addAll(ConfigReader.LootItem.keySet()); - loots.addAll(ConfigReader.OTHERS.keySet()); - return loots; - } - - private List utils(){ - return new ArrayList<>(ConfigReader.UtilItem.keySet()); - } - - private List rods() { - return new ArrayList<>(ConfigReader.RodItem.keySet()); - } - - private List baits() { - return new ArrayList<>(ConfigReader.BaitItem.keySet()); - } - - private List competitions() { - return new ArrayList<>(ConfigReader.CompetitionsC.keySet()); - } -} diff --git a/src/main/java/net/momirealms/customfishing/commands/AbstractSubCommand.java b/src/main/java/net/momirealms/customfishing/commands/AbstractSubCommand.java new file mode 100644 index 00000000..4e188a4a --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/AbstractSubCommand.java @@ -0,0 +1,102 @@ +/* + * 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.commands; + +import net.momirealms.customfishing.manager.MessageManager; +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public abstract class AbstractSubCommand implements SubCommand { + + private final String command; + private Map subCommandMap; + + public AbstractSubCommand(String command, Map subCommandMap) { + this.command = command; + this.subCommandMap = subCommandMap; + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + if (subCommandMap == null || args.size() < 1) { + return true; + } + SubCommand subCommand = subCommandMap.get(args.get(0)); + if (subCommand == null) { + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.unavailableArgs); + } else { + subCommand.onCommand(sender, args.subList(1, args.size())); + } + return true; + } + + @Override + public List onTabComplete(CommandSender sender, List args) { + if (subCommandMap == null) + return Collections.singletonList(""); + if (args.size() <= 1) { + List returnList = new ArrayList<>(subCommandMap.keySet()); + returnList.removeIf(str -> !str.startsWith(args.get(0))); + return returnList; + } + SubCommand subCmd = subCommandMap.get(args.get(0)); + if (subCmd != null) + return subCommandMap.get(args.get(0)).onTabComplete(sender, args.subList(1, args.size())); + return Collections.singletonList(""); + } + + @Override + public String getSubCommand() { + return command; + } + + @Override + public Map getSubCommands() { + return Collections.unmodifiableMap(subCommandMap); + } + + @Override + public void regSubCommand(SubCommand command) { + if (subCommandMap == null) { + subCommandMap = new ConcurrentHashMap<>(); + } + subCommandMap.put(command.getSubCommand(), command); + } + + public void setSubCommandMap(Map subCommandMap) { + this.subCommandMap = subCommandMap; + } + + protected void giveItem(CommandSender sender, String name, String item, int amount){ + String string = MessageManager.prefix + MessageManager.giveItem.replace("{Amount}", String.valueOf(amount)).replace("{Player}",name).replace("{Item}",item); + AdventureUtil.sendMessage(sender, string); + } + + protected List online_players() { + List online = new ArrayList<>(); + Bukkit.getOnlinePlayers().forEach((player -> online.add(player.getName()))); + return online; + } +} diff --git a/src/main/java/net/momirealms/customfishing/commands/PluginCommand.java b/src/main/java/net/momirealms/customfishing/commands/PluginCommand.java new file mode 100644 index 00000000..ecae9f5b --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/PluginCommand.java @@ -0,0 +1,89 @@ +/* + * 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.commands; + + +import net.momirealms.customfishing.commands.subcmd.CompetitionCommand; +import net.momirealms.customfishing.commands.subcmd.ImportCommand; +import net.momirealms.customfishing.commands.subcmd.ItemsCommand; +import net.momirealms.customfishing.commands.subcmd.ReloadCommand; +import net.momirealms.customfishing.manager.MessageManager; +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabExecutor; +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class PluginCommand implements TabExecutor { + + private final Map subCommandMap; + + public PluginCommand() { + subCommandMap = new ConcurrentHashMap<>(); + regDefaultSubCommands(); + } + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + List argList = Arrays.asList(args); + if (argList.size() < 1) { + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.nonArgs); + return true; + } + SubCommand subCommand = subCommandMap.get(argList.get(0)); + if (subCommand != null) + return subCommand.onCommand(sender, argList.subList(1, argList.size())); + else { + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.unavailableArgs); + return true; + } + } + + private void regDefaultSubCommands() { + regSubCommand(ReloadCommand.INSTANCE); + regSubCommand(ItemsCommand.INSTANCE); + regSubCommand(CompetitionCommand.INSTANCE); + regSubCommand(ImportCommand.INSTANCE); + } + + public void regSubCommand(SubCommand executor) { + subCommandMap.put(executor.getSubCommand(), executor); + } + + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + List argList = Arrays.asList(args); + if (argList.size() <= 1) { + List returnList = new ArrayList<>(subCommandMap.keySet()); + returnList.removeIf(str -> !str.startsWith(args[0])); + return returnList; + } + SubCommand subCommand = subCommandMap.get(argList.get(0)); + if (subCommand != null) + return subCommand.onTabComplete(sender, argList.subList(1, argList.size())); + else + return Collections.singletonList(""); + } + + public Map getSubCommandMap() { + return subCommandMap; + } +} diff --git a/src/main/java/net/momirealms/customfishing/commands/SubCommand.java b/src/main/java/net/momirealms/customfishing/commands/SubCommand.java new file mode 100644 index 00000000..8d016364 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/SubCommand.java @@ -0,0 +1,37 @@ +/* + * 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.commands; + +import org.bukkit.command.CommandSender; + +import java.util.List; +import java.util.Map; + +public interface SubCommand { + + boolean onCommand(CommandSender sender, List args); + + List onTabComplete(CommandSender sender, List args); + + String getSubCommand(); + + Map getSubCommands(); + + void regSubCommand(SubCommand subCommand); + +} diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/BaitCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/BaitCommand.java new file mode 100644 index 00000000..ea989ebe --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/BaitCommand.java @@ -0,0 +1,126 @@ +package net.momirealms.customfishing.commands.subcmd; + +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; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class BaitCommand extends AbstractSubCommand { + + public static final SubCommand INSTANCE = new BaitCommand(); + + public BaitCommand() { + super("bait", null); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + if (args.size() < 2) { + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); + } + else if (args.get(0).equalsIgnoreCase("get")) { + if (sender instanceof Player player){ + if (!BonusManager.BAITITEMS.containsKey(args.get(1))){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist); + return true; + } + if (args.size() == 2){ + ItemStackUtil.givePlayerBait(player, args.get(1), 1); + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", "1").replace("{Item}", args.get(1))); + } else { + if (Integer.parseInt(args.get(2)) < 1){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount); + return true; + } + ItemStackUtil.givePlayerBait(player, args.get(1), Integer.parseInt(args.get(2))); + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", args.get(2)).replace("{Item}", args.get(1))); + } + } else { + AdventureUtil.consoleMessage(MessageManager.prefix + MessageManager.noConsole); + } + } + else if (args.get(0).equalsIgnoreCase("give")) { + if (args.size() < 3){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); + return true; + } + Player player = Bukkit.getPlayer(args.get(1)); + if (player == null){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1))); + return true; + } + if (!BonusManager.BAITITEMS.containsKey(args.get(2))){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist); + return true; + } + if (args.size() == 3){ + ItemStackUtil.givePlayerBait(player, args.get(2), 1); + super.giveItem(sender, args.get(1), args.get(2), 1); + } else { + if (Integer.parseInt(args.get(3)) < 1){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount); + return true; + } + ItemStackUtil.givePlayerBait(player, args.get(2), Integer.parseInt(args.get(3))); + super.giveItem(sender, args.get(1), args.get(2), Integer.parseInt(args.get(3))); + } + } + return true; + } + + @Override + public List onTabComplete(CommandSender sender, List args) { + if (args.size() == 1) { + return List.of("get", "give"); + } + if (args.size() == 2) { + if (args.get(0).equals("get")) { + List arrayList = new ArrayList<>(); + for (String cmd : baits()) { + if (cmd.startsWith(args.get(1))) + arrayList.add(cmd); + } + return arrayList; + } + if (args.get(0).equals("give")) { + List arrayList = new ArrayList<>(); + for (String cmd : online_players()) { + if (cmd.startsWith(args.get(1))) + arrayList.add(cmd); + } + return arrayList; + } + } + if (args.size() == 3) { + if (args.get(0).equals("get")) { + return List.of("1","2","4","8","16","32","64"); + } + if (args.get(0).equals("give")) { + List arrayList = new ArrayList<>(); + for (String cmd : baits()) { + if (cmd.startsWith(args.get(2))) + arrayList.add(cmd); + } + return arrayList; + } + } + if (args.size() == 4) { + if (args.get(0).equals("give")) { + return List.of("1","2","4","8","16","32","64"); + } + } + return super.onTabComplete(sender, args); + } + + private List baits() { + return new ArrayList<>(BonusManager.BAITITEMS.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 new file mode 100644 index 00000000..7dea5030 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/CompetitionCommand.java @@ -0,0 +1,63 @@ +package net.momirealms.customfishing.commands.subcmd; + +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.manager.MessageManager; +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class CompetitionCommand extends AbstractSubCommand { + + public static final SubCommand INSTANCE = new CompetitionCommand(); + + public CompetitionCommand() { + super("competition", null); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + if (args.size() < 1){ + 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; + } + if (CompetitionSchedule.startCompetition(args.get(1))){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceSuccess); + } else { + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceFailure); + } + } 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.forceEnd); + } + return true; + } + + @Override + public List onTabComplete(CommandSender sender, List args) { + if (args.size() == 1) { + return List.of("start","end","cancel"); + } + if (args.size() == 2 && args.get(0).equals("start")) { + return competitions(); + } + return super.onTabComplete(sender, args); + } + + private List competitions() { + return new ArrayList<>(CompetitionManager.competitionsC.keySet()); + } +} diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/ImportCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/ImportCommand.java new file mode 100644 index 00000000..aaa8c28e --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/ImportCommand.java @@ -0,0 +1,44 @@ +package net.momirealms.customfishing.commands.subcmd; + +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.ItemStackUtil; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Collections; +import java.util.List; + +public class ImportCommand extends AbstractSubCommand { + + public static final SubCommand INSTANCE = new ImportCommand(); + + public ImportCommand() { + super("import", null); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + if (args.size() < 1){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); + return true; + } else if (sender instanceof Player player) { + if (ItemStackUtil.saveToFile(player.getInventory().getItemInMainHand(), args.get(0))) { + AdventureUtil.playerMessage(player, MessageManager.prefix + "Done! File is saved to /CustomFishing/loots/" + args.get(0) + ".yml"); + } + } else { + AdventureUtil.consoleMessage(MessageManager.prefix + MessageManager.noConsole); + } + return true; + } + + @Override + public List onTabComplete(CommandSender sender, List args) { + if (args.size() == 1) { + return Collections.singletonList("file_name"); + } + return super.onTabComplete(sender, args); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/ItemsCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/ItemsCommand.java new file mode 100644 index 00000000..68f5391e --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/ItemsCommand.java @@ -0,0 +1,30 @@ +package net.momirealms.customfishing.commands.subcmd; + +import net.momirealms.customfishing.commands.AbstractSubCommand; +import net.momirealms.customfishing.commands.SubCommand; +import org.bukkit.command.CommandSender; + +import java.util.List; + +public class ItemsCommand extends AbstractSubCommand { + + public static final SubCommand INSTANCE = new ItemsCommand(); + + public ItemsCommand() { + super("items", null); + regSubCommand(UtilCommand.INSTANCE); + regSubCommand(RodCommand.INSTANCE); + regSubCommand(BaitCommand.INSTANCE); + regSubCommand(LootCommand.INSTANCE); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + return super.onCommand(sender, args); + } + + @Override + public List onTabComplete(CommandSender sender, List args) { + return super.onTabComplete(sender, args); + } +} diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/LootCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/LootCommand.java new file mode 100644 index 00000000..472b39b4 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/LootCommand.java @@ -0,0 +1,141 @@ +package net.momirealms.customfishing.commands.subcmd; + +import net.momirealms.customfishing.commands.AbstractSubCommand; +import net.momirealms.customfishing.commands.SubCommand; +import net.momirealms.customfishing.manager.BonusManager; +import net.momirealms.customfishing.manager.LootManager; +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; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class LootCommand extends AbstractSubCommand { + + public static final SubCommand INSTANCE = new LootCommand(); + + public LootCommand() { + super("loot", null); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + if (args.size() < 2) { + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); + } + else if (args.get(0).equalsIgnoreCase("get")) { + if (sender instanceof Player player){ + if (!loots().contains(args.get(1))){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist); + return true; + } + if (args.size() == 2){ + ItemStackUtil.givePlayerLoot(player, args.get(1), 1); + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", "1").replace("{Item}", args.get(1))); + } else { + if (Integer.parseInt(args.get(2)) < 1){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount); + return true; + } + ItemStackUtil.givePlayerLoot(player, args.get(1), Integer.parseInt(args.get(2))); + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", args.get(2)).replace("{Item}", args.get(1))); + } + } else { + AdventureUtil.consoleMessage(MessageManager.prefix + MessageManager.noConsole); + } + } + else if (args.get(0).equalsIgnoreCase("give")) { + if (args.size() < 3){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); + return true; + } + Player player = Bukkit.getPlayer(args.get(1)); + if (player == null){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1))); + return true; + } + if (!loots().contains(args.get(2))){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist); + return true; + } + if (args.size() == 3){ + ItemStackUtil.givePlayerLoot(player, args.get(2), 1); + super.giveItem(sender, args.get(1), args.get(2), 1); + } else { + if (Integer.parseInt(args.get(3)) < 1){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount); + return true; + } + ItemStackUtil.givePlayerLoot(player, args.get(2), Integer.parseInt(args.get(3))); + super.giveItem(sender, args.get(1), args.get(2), Integer.parseInt(args.get(3))); + } + } + return true; + } + + @Override + public List onTabComplete(CommandSender sender, List args) { + if (args.size() == 1) { + return List.of("get", "give"); + } + if (args.size() == 2) { + if (args.get(0).equals("get")) { + List arrayList = new ArrayList<>(); + for (String cmd : loots()) { + if (cmd.startsWith(args.get(1))) + arrayList.add(cmd); + } + return arrayList; + } + if (args.get(0).equals("give")) { + List arrayList = new ArrayList<>(); + for (String cmd : online_players()) { + if (cmd.startsWith(args.get(1))) + arrayList.add(cmd); + } + return arrayList; + } + } + if (args.size() == 3) { + if (args.get(0).equals("get")) { + return List.of("1","2","4","8","16","32","64"); + } + if (args.get(0).equals("give")) { + List arrayList = new ArrayList<>(); + for (String cmd : loots()) { + if (cmd.startsWith(args.get(2))) + arrayList.add(cmd); + } + return arrayList; + } + } + if (args.size() == 4) { + if (args.get(0).equals("give")) { + return List.of("1","2","4","8","16","32","64"); + } + } + return super.onTabComplete(sender, args); + } + + private List loots() { + List loots = new ArrayList<>(); + for (Map.Entry en : LootManager.WATERLOOTS.entrySet()) { + if (en.getValue() instanceof DroppedItem) { + loots.add(en.getKey()); + } + } + for (Map.Entry en : LootManager.LAVALOOTS.entrySet()) { + if (en.getValue() instanceof DroppedItem) { + loots.add(en.getKey()); + } + } + return loots; + } +} diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/ReloadCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/ReloadCommand.java new file mode 100644 index 00000000..7ac6c70e --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/ReloadCommand.java @@ -0,0 +1,48 @@ +/* + * 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.commands.subcmd; + + +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; + +public final class ReloadCommand extends AbstractSubCommand { + + public static final SubCommand INSTANCE = new ReloadCommand(); + + private ReloadCommand() { + super("reload", null); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + if (args.size() < 1) { + long time1 = System.currentTimeMillis(); + ConfigUtil.reload(); + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.reload.replace("{time}", String.valueOf(System.currentTimeMillis() - time1))); + return true; + } + return super.onCommand(sender, args); + } +} diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/RodCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/RodCommand.java new file mode 100644 index 00000000..751eff6a --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/RodCommand.java @@ -0,0 +1,126 @@ +package net.momirealms.customfishing.commands.subcmd; + +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; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class RodCommand extends AbstractSubCommand { + + public static final SubCommand INSTANCE = new RodCommand(); + + public RodCommand() { + super("rod", null); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + if (args.size() < 2) { + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); + } + else if (args.get(0).equalsIgnoreCase("get")) { + if (sender instanceof Player player){ + if (!BonusManager.RODITEMS.containsKey(args.get(1))){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist); + return true; + } + if (args.size() == 2){ + ItemStackUtil.givePlayerRod(player, args.get(1), 1); + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", "1").replace("{Item}", args.get(1))); + } else { + if (Integer.parseInt(args.get(2)) < 1){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount); + return true; + } + ItemStackUtil.givePlayerRod(player, args.get(1), Integer.parseInt(args.get(2))); + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", args.get(2)).replace("{Item}", args.get(1))); + } + } else { + AdventureUtil.consoleMessage(MessageManager.prefix + MessageManager.noConsole); + } + } + else if (args.get(0).equalsIgnoreCase("give")) { + if (args.size() < 3){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); + return true; + } + Player player = Bukkit.getPlayer(args.get(1)); + if (player == null){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1))); + return true; + } + if (!BonusManager.RODITEMS.containsKey(args.get(2))){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist); + return true; + } + if (args.size() == 3){ + ItemStackUtil.givePlayerRod(player, args.get(2), 1); + super.giveItem(sender, args.get(1), args.get(2), 1); + } else { + if (Integer.parseInt(args.get(3)) < 1){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount); + return true; + } + ItemStackUtil.givePlayerRod(player, args.get(2), Integer.parseInt(args.get(3))); + super.giveItem(sender, args.get(1), args.get(2), Integer.parseInt(args.get(3))); + } + } + return true; + } + + @Override + public List onTabComplete(CommandSender sender, List args) { + if (args.size() == 1) { + return List.of("get", "give"); + } + if (args.size() == 2) { + if (args.get(0).equals("get")) { + List arrayList = new ArrayList<>(); + for (String cmd : rods()) { + if (cmd.startsWith(args.get(1))) + arrayList.add(cmd); + } + return arrayList; + } + if (args.get(0).equals("give")) { + List arrayList = new ArrayList<>(); + for (String cmd : online_players()) { + if (cmd.startsWith(args.get(1))) + arrayList.add(cmd); + } + return arrayList; + } + } + if (args.size() == 3) { + if (args.get(0).equals("get")) { + return List.of("1","2","4","8","16","32","64"); + } + if (args.get(0).equals("give")) { + List arrayList = new ArrayList<>(); + for (String cmd : rods()) { + if (cmd.startsWith(args.get(2))) + arrayList.add(cmd); + } + return arrayList; + } + } + if (args.size() == 4) { + if (args.get(0).equals("give")) { + return List.of("1","2","4","8","16","32","64"); + } + } + return super.onTabComplete(sender, args); + } + + private List rods() { + return new ArrayList<>(BonusManager.RODITEMS.keySet()); + } +} diff --git a/src/main/java/net/momirealms/customfishing/commands/subcmd/UtilCommand.java b/src/main/java/net/momirealms/customfishing/commands/subcmd/UtilCommand.java new file mode 100644 index 00000000..257a01e1 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/commands/subcmd/UtilCommand.java @@ -0,0 +1,126 @@ +package net.momirealms.customfishing.commands.subcmd; + +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; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class UtilCommand extends AbstractSubCommand { + + public static final SubCommand INSTANCE = new UtilCommand(); + + public UtilCommand() { + super("util", null); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + if (args.size() < 2) { + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); + } + else if (args.get(0).equalsIgnoreCase("get")) { + if (sender instanceof Player player){ + if (!BonusManager.UTILITEMS.containsKey(args.get(1))){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist); + return true; + } + if (args.size() == 2){ + ItemStackUtil.givePlayerUtil(player, args.get(1), 1); + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", "1").replace("{Item}", args.get(1))); + } else { + if (Integer.parseInt(args.get(2)) < 1){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount); + return true; + } + ItemStackUtil.givePlayerUtil(player, args.get(1), Integer.parseInt(args.get(2))); + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", args.get(2)).replace("{Item}", args.get(1))); + } + } else { + AdventureUtil.consoleMessage(MessageManager.prefix + MessageManager.noConsole); + } + } + else if (args.get(0).equalsIgnoreCase("give")) { + if (args.size() < 3){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs); + return true; + } + Player player = Bukkit.getPlayer(args.get(1)); + if (player == null){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1))); + return true; + } + if (!BonusManager.UTILITEMS.containsKey(args.get(2))){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist); + return true; + } + if (args.size() == 3){ + ItemStackUtil.givePlayerUtil(player, args.get(2), 1); + super.giveItem(sender, args.get(1), args.get(2), 1); + } else { + if (Integer.parseInt(args.get(3)) < 1){ + AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount); + return true; + } + ItemStackUtil.givePlayerUtil(player, args.get(2), Integer.parseInt(args.get(3))); + super.giveItem(sender, args.get(1), args.get(2), Integer.parseInt(args.get(3))); + } + } + return true; + } + + @Override + public List onTabComplete(CommandSender sender, List args) { + if (args.size() == 1) { + return List.of("get", "give"); + } + if (args.size() == 2) { + if (args.get(0).equals("get")) { + List arrayList = new ArrayList<>(); + for (String cmd : utils()) { + if (cmd.startsWith(args.get(1))) + arrayList.add(cmd); + } + return arrayList; + } + if (args.get(0).equals("give")) { + List arrayList = new ArrayList<>(); + for (String cmd : online_players()) { + if (cmd.startsWith(args.get(1))) + arrayList.add(cmd); + } + return arrayList; + } + } + if (args.size() == 3) { + if (args.get(0).equals("get")) { + return List.of("1","2","4","8","16","32","64"); + } + if (args.get(0).equals("give")) { + List arrayList = new ArrayList<>(); + for (String cmd : utils()) { + if (cmd.startsWith(args.get(2))) + arrayList.add(cmd); + } + return arrayList; + } + } + if (args.size() == 4) { + if (args.get(0).equals("give")) { + return List.of("1","2","4","8","16","32","64"); + } + } + return super.onTabComplete(sender, args); + } + + private List utils() { + return new ArrayList<>(BonusManager.UTILITEMS.keySet()); + } +} diff --git a/src/main/java/net/momirealms/customfishing/competition/Competition.java b/src/main/java/net/momirealms/customfishing/competition/Competition.java index bbf5bbf7..c491c561 100644 --- a/src/main/java/net/momirealms/customfishing/competition/Competition.java +++ b/src/main/java/net/momirealms/customfishing/competition/Competition.java @@ -1,106 +1,77 @@ -/* - * 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.competition; -import net.momirealms.customfishing.ConfigReader; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.competition.bossbar.BossBarConfig; import net.momirealms.customfishing.competition.bossbar.BossBarManager; -import net.momirealms.customfishing.competition.ranking.Ranking; -import net.momirealms.customfishing.competition.ranking.RankingImpl; +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.object.action.ActionB; -import net.momirealms.customfishing.utils.AdventureUtil; +import net.momirealms.customfishing.manager.CompetitionManager; +import net.momirealms.customfishing.manager.ConfigManager; +import net.momirealms.customfishing.manager.MessageManager; +import net.momirealms.customfishing.object.action.ActionInterface; +import net.momirealms.customfishing.util.AdventureUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import java.time.Instant; +import java.time.LocalTime; import java.util.*; public class Competition { - private Goal goal; - private final long duration; - private long startTime; - private final int minPlayers; - private boolean status; - private BukkitTask timerTask; - private Ranking ranking; - private final BossBarConfig bossBarConfig; - private final List startMessage; - private final List endMessage; - private final List endCommand; - private final List startCommand; - private final List joinCommand; - private final HashMap> rewardsMap; + public static Competition currentCompetition; - public static long remainingTime; - public static float progress; - public static CompetitionPlayer emptyPlayer = new CompetitionPlayer("XiaoMoMi",0); + private final CompetitionConfig competitionConfig; + private CompetitionGoal goal; + private BukkitTask timerTask; + private RankingInterface ranking; + private long startTime; + private long remainingTime; + private float progress; + + private BossBarManager bossBarManager; public Competition(CompetitionConfig competitionConfig) { - this.duration = competitionConfig.getDuration(); - this.goal = competitionConfig.getGoal(); - this.minPlayers = competitionConfig.getMinPlayers(); - this.bossBarConfig = competitionConfig.getBossBarConfig(); - this.startMessage = competitionConfig.getStartMessage(); - this.endMessage = competitionConfig.getEndMessage(); - this.rewardsMap = competitionConfig.getRewards(); - this.startCommand = competitionConfig.getStartCommand(); - this.endCommand = competitionConfig.getEndCommand(); - this.joinCommand = competitionConfig.getJoinCommand(); + this.competitionConfig = competitionConfig; } public void begin(boolean forceStart) { - if (goal == Goal.RANDOM) { - goal = getRandomGoal(); + if (this.goal == CompetitionGoal.RANDOM) { + this.goal = getRandomGoal(); } - remainingTime = this.duration; + this.remainingTime = this.competitionConfig.getDuration(); this.startTime = Instant.now().getEpochSecond(); Collection playerCollections = Bukkit.getOnlinePlayers(); - if (playerCollections.size() >= minPlayers || forceStart) { - status = true; - if (ConfigReader.useRedis){ + if (playerCollections.size() >= competitionConfig.getMinPlayers() || forceStart) { + + currentCompetition = this; + + if (ConfigManager.useRedis){ ranking = new RedisRankingImpl(); - }else { - ranking = new RankingImpl(); + } else { + ranking = new LocalRankingImpl(); } startTimer(); - if (startMessage != null){ - playerCollections.forEach(player -> { - startMessage.forEach(message -> { - AdventureUtil.playerMessage(player, message); - }); - }); + for (String startMsg : competitionConfig.getStartMessage()) { + for (Player player : playerCollections) { + AdventureUtil.playerMessage(player, startMsg); + } } - if (startCommand != null){ - startCommand.forEach(command -> { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); - }); + for (String startCmd : competitionConfig.getStartCommand()) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), startCmd); + } + if (competitionConfig.isEnableBossBar()) { + bossBarManager = new BossBarManager(this); + bossBarManager.load(); } } else { - playerCollections.forEach(player -> { - AdventureUtil.playerMessage(player, ConfigReader.Message.notEnoughPlayers); - }); + for (Player player : playerCollections) { + AdventureUtil.playerMessage(player, MessageManager.notEnoughPlayers); + } } } @@ -112,63 +83,59 @@ public class Competition { end(); } } - }.runTaskTimer(CustomFishing.instance, 0, 20); + }.runTaskTimer(CustomFishing.plugin, 0, 20); } - private boolean decreaseTime() { - - long tVac; - long current = Instant.now().getEpochSecond(); - - progress = (float) remainingTime / duration; - - remainingTime = duration - (current - startTime); - if ((tVac = (current - startTime) + 1) != duration - remainingTime) { - for (long i = duration - remainingTime; i < tVac; i++) { - if (remainingTime <= 0) return true; - remainingTime--; - } + public void cancel() { + if (this.bossBarManager != null) { + bossBarManager.unload(); } - return false; + ranking.clear(); + this.timerTask.cancel(); + currentCompetition = null; } public void end() { - BossBarManager.stopAllTimer(); + if (this.bossBarManager != null) { + bossBarManager.unload(); + } this.timerTask.cancel(); - status = false; givePrize(); - if (endMessage != null){ - List newMessage = new ArrayList<>(); - endMessage.forEach(message -> { - CompetitionPlayer[] competitionPlayers = ranking.getTop3Player(); - float first = Optional.ofNullable(competitionPlayers[0]).orElse(CompetitionPlayer.emptyPlayer).getScore(); - float second = Optional.ofNullable(competitionPlayers[1]).orElse(CompetitionPlayer.emptyPlayer).getScore(); - float third = Optional.ofNullable(competitionPlayers[2]).orElse(CompetitionPlayer.emptyPlayer).getScore(); - newMessage.add(message - .replace("{1st}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[0]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(ConfigReader.Message.noPlayer)) - .replace("{2nd}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[1]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(ConfigReader.Message.noPlayer)) - .replace("{3rd}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[2]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(ConfigReader.Message.noPlayer)) - .replace("{1st_points}", first < 0 ? ConfigReader.Message.noScore : String.format("%.1f",(first))) - .replace("{2nd_points}", second < 0 ? ConfigReader.Message.noScore : String.format("%.1f",(second))) - .replace("{3rd_points}", third < 0 ? ConfigReader.Message.noScore : String.format("%.1f",(third)))); - }); - Bukkit.getOnlinePlayers().forEach(player -> { - newMessage.forEach(message -> { - AdventureUtil.playerMessage(player, message); - }); - }); + + List newMessage = new ArrayList<>(); + for (String endMsg : competitionConfig.getEndMessage()) { + CompetitionPlayer[] competitionPlayers = ranking.getTop3Player(); + float first = Optional.ofNullable(competitionPlayers[0]).orElse(CompetitionPlayer.emptyPlayer).getScore(); + float second = Optional.ofNullable(competitionPlayers[1]).orElse(CompetitionPlayer.emptyPlayer).getScore(); + float third = Optional.ofNullable(competitionPlayers[2]).orElse(CompetitionPlayer.emptyPlayer).getScore(); + newMessage.add(endMsg + .replace("{1st}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[0]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(MessageManager.noPlayer)) + .replace("{2nd}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[1]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(MessageManager.noPlayer)) + .replace("{3rd}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[2]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(MessageManager.noPlayer)) + .replace("{1st_points}", first < 0 ? MessageManager.noScore : String.format("%.1f",(first))) + .replace("{2nd_points}", second < 0 ? MessageManager.noScore : String.format("%.1f",(second))) + .replace("{3rd_points}", third < 0 ? MessageManager.noScore : String.format("%.1f",(third)))); } - if (endCommand != null){ - endCommand.forEach(command -> { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); - }); + + for (Player player : Bukkit.getOnlinePlayers()) { + for (String msg : newMessage) { + AdventureUtil.playerMessage(player, msg); + } } - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.instance, ()-> { + + for (String endCmd : competitionConfig.getEndCommand()) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), endCmd); + } + + currentCompetition = null; + + Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.plugin, ()-> { ranking.clear(); - }, 300); + }, 100); } public void givePrize(){ + HashMap rewardsMap = competitionConfig.getRewards(); if (ranking.getSize() != 0 && rewardsMap != null) { Iterator iterator = ranking.getIterator(); int i = 1; @@ -177,19 +144,19 @@ public class Competition { String playerName = iterator.next(); Player player = Bukkit.getPlayer(playerName); if (player != null){ - for (ActionB action : rewardsMap.get(String.valueOf(i))) { + for (ActionInterface action : rewardsMap.get(String.valueOf(i))) { action.doOn(player); } } i++; } else { - List actions = rewardsMap.get("participation"); + ActionInterface[] actions = rewardsMap.get("participation"); if (actions != null) { iterator.forEachRemaining(playerName -> { Player player = Bukkit.getPlayer(playerName); if (player != null){ - for (ActionB action : actions) { + for (ActionInterface action : actions) { action.doOn(player); } } @@ -203,27 +170,59 @@ public class Competition { } } - public void cancel() { - BossBarManager.stopAllTimer(); - ranking.clear(); - this.timerTask.cancel(); - status = false; + 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++) { + if (remainingTime <= 0) return true; + remainingTime--; + } + } + return false; } - public void refreshRanking(String player, float score) { - if (this.goal != Goal.TOTAL_SCORE) score = 1.0f; - ranking.refreshData(player, score); + private CompetitionGoal getRandomGoal() { + return CompetitionGoal.values()[new Random().nextInt(CompetitionGoal.values().length - 1)]; } - private Goal getRandomGoal() { - int goal = new Random().nextInt(Goal.values().length-1); - return Goal.values()[goal]; + public static boolean hasCompetitionOn() { + return currentCompetition != null; } - public long getDuration() {return duration;} - public long getRemainingTime() {return remainingTime;} - public boolean isGoingOn() {return status;} - public BossBarConfig getBossBarConfig() {return bossBarConfig;} - public Ranking getRanking() {return ranking;} - public List getJoinCommand() {return joinCommand;} -} \ No newline at end of file + public float getProgress() { + return progress; + } + + public CompetitionConfig getCompetitionConfig() { + return competitionConfig; + } + + public String getPlayerRank(Player player) { + return Optional.ofNullable(ranking.getPlayerRank(player.getName())).orElse(MessageManager.noRank); + } + + public long getRemainingTime() { + return remainingTime; + } + + public double getScore(Player player) { + return Optional.ofNullable(ranking.getCompetitionPlayer(player.getName())).orElse(CompetitionPlayer.emptyPlayer).getScore(); + } + + public float getFirstScore() { + return ranking.getFirstScore(); + } + + public String getFirstPlayer() { + return ranking.getFirstPlayer(); + } + + +} diff --git a/src/main/java/net/momirealms/customfishing/competition/CompetitionConfig.java b/src/main/java/net/momirealms/customfishing/competition/CompetitionConfig.java index 9b2b8f0f..c9957ea2 100644 --- a/src/main/java/net/momirealms/customfishing/competition/CompetitionConfig.java +++ b/src/main/java/net/momirealms/customfishing/competition/CompetitionConfig.java @@ -1,64 +1,80 @@ -/* - * 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.competition; import net.momirealms.customfishing.competition.bossbar.BossBarConfig; -import net.momirealms.customfishing.object.action.ActionB; +import net.momirealms.customfishing.object.action.ActionInterface; import java.util.HashMap; import java.util.List; public class CompetitionConfig { - private int duration; - private int minPlayers; - private List startMessage; - private List endMessage; - private List startCommand; - private List endCommand; - private List joinCommand; - private Goal goal; - private BossBarConfig bossBarConfig; + private final int duration; + private final int minPlayers; + private final List startMessage; + private final List endMessage; + private final List startCommand; + private final List endCommand; + private final List joinCommand; + private final CompetitionGoal goal; + private final BossBarConfig bossBarConfig; private final boolean enableBossBar; - private HashMap> rewards; + private final HashMap rewards; - public CompetitionConfig(boolean enableBossBar){this.enableBossBar = enableBossBar;} + public CompetitionConfig(int duration, int minPlayers, List startMessage, List endMessage, List startCommand, List endCommand, List joinCommand, CompetitionGoal goal, BossBarConfig bossBarConfig, boolean enableBossBar, HashMap rewards) { + this.duration = duration; + this.minPlayers = minPlayers; + this.startMessage = startMessage; + this.endMessage = endMessage; + this.startCommand = startCommand; + this.endCommand = endCommand; + this.joinCommand = joinCommand; + this.goal = goal; + this.bossBarConfig = bossBarConfig; + this.enableBossBar = enableBossBar; + this.rewards = rewards; + } - public void setDuration(int duration) {this.duration = duration;} - public void setBossBarConfig(BossBarConfig bossBarConfig) {this.bossBarConfig = bossBarConfig;} - public void setGoal(Goal goal) {this.goal = goal;} - public void setEndMessage(List endMessage) {this.endMessage = endMessage;} - public void setStartMessage(List startMessage) {this.startMessage = startMessage;} - public void setStartCommand(List startCommand) {this.startCommand = startCommand;} - public void setEndCommand(List endCommand) {this.endCommand = endCommand;} - public void setJoinCommand(List joinCommand) {this.joinCommand = joinCommand;} - public void setMinPlayers(int minPlayers) {this.minPlayers = minPlayers;} - public HashMap> getRewards() {return rewards;} + public int getDuration() { + return duration; + } - public Goal getGoal() {return goal;} - public int getMinPlayers() {return minPlayers;} - public int getDuration() {return duration;} - public BossBarConfig getBossBarConfig() {return bossBarConfig;} - public boolean isEnableBossBar() {return enableBossBar;} - public List getEndMessage() {return endMessage;} - public List getStartMessage() {return startMessage;} - public void setRewards(HashMap> rewards) {this.rewards = rewards;} - public List getEndCommand() {return endCommand;} - public List getJoinCommand() {return joinCommand;} - public List getStartCommand() {return startCommand;} + public int getMinPlayers() { + return minPlayers; + } + + public List getStartMessage() { + return startMessage; + } + + public List getEndMessage() { + return endMessage; + } + + public List getStartCommand() { + return startCommand; + } + + public List getEndCommand() { + return endCommand; + } + + public List getJoinCommand() { + return joinCommand; + } + + public CompetitionGoal getGoal() { + return goal; + } + + public BossBarConfig getBossBarConfig() { + return bossBarConfig; + } + + public boolean isEnableBossBar() { + return enableBossBar; + } + + public HashMap getRewards() { + return rewards; + } } diff --git a/src/main/java/net/momirealms/customfishing/competition/CompetitionGoal.java b/src/main/java/net/momirealms/customfishing/competition/CompetitionGoal.java new file mode 100644 index 00000000..0d88baa2 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/competition/CompetitionGoal.java @@ -0,0 +1,9 @@ +package net.momirealms.customfishing.competition; + +public enum CompetitionGoal { + + CATCH_AMOUNT, + TOTAL_SCORE, + RANDOM + +} diff --git a/src/main/java/net/momirealms/customfishing/competition/CompetitionPlayer.java b/src/main/java/net/momirealms/customfishing/competition/CompetitionPlayer.java index 70984167..213a4371 100644 --- a/src/main/java/net/momirealms/customfishing/competition/CompetitionPlayer.java +++ b/src/main/java/net/momirealms/customfishing/competition/CompetitionPlayer.java @@ -1,20 +1,3 @@ -/* - * 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.competition; import org.jetbrains.annotations.NotNull; @@ -57,6 +40,10 @@ public class CompetitionPlayer implements Comparable{ @Override public String toString() { - return "CompetitionPlayer[player=" + this.player + ", score=" + this.score + ", catch-time=" + this.time + "]"; + return "CompetitionPlayer{" + + "time=" + time + + ", player='" + player + '\'' + + ", score=" + score + + '}'; } } diff --git a/src/main/java/net/momirealms/customfishing/competition/CompetitionSchedule.java b/src/main/java/net/momirealms/customfishing/competition/CompetitionSchedule.java index a21869cb..0380730f 100644 --- a/src/main/java/net/momirealms/customfishing/competition/CompetitionSchedule.java +++ b/src/main/java/net/momirealms/customfishing/competition/CompetitionSchedule.java @@ -1,90 +1,77 @@ -/* - * 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.competition; -import net.momirealms.customfishing.ConfigReader; import net.momirealms.customfishing.CustomFishing; -import org.bukkit.Bukkit; +import net.momirealms.customfishing.Function; +import net.momirealms.customfishing.manager.CompetitionManager; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import java.time.LocalTime; -public class CompetitionSchedule { +public class CompetitionSchedule extends Function { - public static Competition competition; - public static boolean hasBossBar; - private int doubleCheckTime; - private int checkTaskID; - - public CompetitionSchedule(){ - hasBossBar = false; + @Override + public void load() { + checkTime(); } - public static boolean startCompetition(String competitionName){ - CompetitionConfig competitionConfig = ConfigReader.CompetitionsC.get(competitionName); + @Override + public void unload() { + stopCheck(); + cancelCompetition(); + } + + private BukkitTask checkTimeTask; + private int doubleCheckTime; + + public static boolean startCompetition(String competitionName) { + CompetitionConfig competitionConfig = CompetitionManager.competitionsC.get(competitionName); if (competitionConfig == null) return false; - if (competition != null && competition.isGoingOn()){ - competition.end(); + if (Competition.currentCompetition != null) { + Competition.currentCompetition.end(); } - competition = new Competition(competitionConfig); - competition.begin(true); - hasBossBar = competitionConfig.isEnableBossBar(); + Competition.currentCompetition = new Competition(competitionConfig); + Competition.currentCompetition.begin(true); return true; } - public static void endCompetition(){ - if (competition != null){ - competition.end(); + public static void cancelCompetition() { + if (Competition.currentCompetition != null) { + Competition.currentCompetition.cancel(); } } - public static void cancelCompetition(){ - if (competition != null){ - competition.cancel(); + public static void endCompetition() { + if (Competition.currentCompetition != null) { + Competition.currentCompetition.end(); } } - public void startCompetition(CompetitionConfig competitionConfig){ - if (competition != null && competition.isGoingOn()){ - competition.end(); + public void startCompetition(CompetitionConfig competitionConfig) { + if (Competition.currentCompetition != null) { + Competition.currentCompetition.end(); } - competition = new Competition(competitionConfig); - competition.begin(false); - hasBossBar = competitionConfig.isEnableBossBar(); + Competition.currentCompetition = new Competition(competitionConfig); + Competition.currentCompetition.begin(false); } public void checkTime() { - BukkitTask checkTimeTask = new BukkitRunnable(){ - public void run(){ - if (isANewMinute()){ - CompetitionConfig competitionConfig = ConfigReader.CompetitionsT.get(getCurrentTime()); - if (competitionConfig != null){ + this.checkTimeTask = new BukkitRunnable() { + public void run() { + if (isANewMinute()) { + CompetitionConfig competitionConfig = CompetitionManager.competitionsT.get(getCurrentTime()); + if (competitionConfig != null) { startCompetition(competitionConfig); } } } - }.runTaskTimer(CustomFishing.instance, (60- LocalTime.now().getSecond())*20, 1200); - checkTaskID = checkTimeTask.getTaskId(); + }.runTaskTimer(CustomFishing.plugin, (60 - LocalTime.now().getSecond()) * 20, 1200); } - public void stopCheck(){ - Bukkit.getScheduler().cancelTask(checkTaskID); + public void stopCheck() { + if (this.checkTimeTask != null) { + checkTimeTask.cancel(); + } } public String getCurrentTime() { @@ -96,7 +83,7 @@ public class CompetitionSchedule { if (doubleCheckTime != minute) { doubleCheckTime = minute; return true; - }else { + } else { return false; } } diff --git a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarConfig.java b/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarConfig.java index 8087a965..f37b3304 100644 --- a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarConfig.java +++ b/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarConfig.java @@ -17,13 +17,41 @@ package net.momirealms.customfishing.competition.bossbar; -import net.kyori.adventure.bossbar.BossBar; +import org.bukkit.boss.BarColor; -public record BossBarConfig(String text, BossBar.Overlay overlay, - BossBar.Color color, int rate){ +public class BossBarConfig { - public BossBar.Color getColor() {return color;} - public int getRate() {return rate;} - public BossBar.Overlay getOverlay() {return overlay;} - public String getText() {return text;} + private final String[] text; + private final int interval; + private final Overlay overlay; + private final BarColor color; + private final int rate; + + public BossBarConfig(String[] text, Overlay overlay, BarColor color, int rate, int interval) { + this.text = text; + this.overlay = overlay; + this.color = color; + this.rate = rate; + this.interval = interval; + } + + public String[] getText() { + return text; + } + + public int getInterval() { + return interval; + } + + public Overlay getOverlay() { + return overlay; + } + + public BarColor getColor() { + return color; + } + + public int getRate() { + return rate; + } } diff --git a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarManager.java b/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarManager.java index 0f0e971a..5c91574b 100644 --- a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarManager.java +++ b/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarManager.java @@ -1,77 +1,34 @@ -/* - * 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.competition.bossbar; -import net.momirealms.customfishing.ConfigReader; -import net.momirealms.customfishing.competition.CompetitionSchedule; -import net.momirealms.customfishing.utils.AdventureUtil; -import org.bukkit.Bukkit; +import net.momirealms.customfishing.Function; +import net.momirealms.customfishing.competition.Competition; import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import java.util.HashMap; +public class BossBarManager extends Function { -public class BossBarManager implements Listener { + private final Competition competition; - public static HashMap cache = new HashMap<>(); - - @EventHandler - public void onJoin(PlayerJoinEvent event){ - Player player = event.getPlayer(); - if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()){ - if (CompetitionSchedule.competition.getRanking().getCompetitionPlayer(player.getName()) != null && cache.get(player) == null){ - BossBarTimer timerTask = new BossBarTimer(player, CompetitionSchedule.competition.getBossBarConfig()); - cache.put(player, timerTask); - }else { - AdventureUtil.playerMessage(player, ConfigReader.Message.competitionOn); - } - } + public BossBarManager(Competition competition) { + this.competition = competition; } - @EventHandler - public void onQuit(PlayerQuitEvent event){ - Player player = event.getPlayer(); - BossBarTimer timerTask = cache.get(player); - if (timerTask != null){ - timerTask.stopTimer(); - cache.remove(player); - } + @Override + public void load() { + super.load(); } - public static void stopAllTimer(){ - cache.forEach(((player, timerTask) -> { - timerTask.stopTimer(); - })); - cache.clear(); + @Override + public void unload() { + super.unload(); } - public static void joinCompetition(Player player){ - if (cache.get(player) == null) { - BossBarTimer timerTask = new BossBarTimer(player, CompetitionSchedule.competition.getBossBarConfig()); - cache.put(player, timerTask); - if (CompetitionSchedule.competition.getJoinCommand() != null){ - CompetitionSchedule.competition.getJoinCommand().forEach(command -> { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName())); - }); - } - } + @Override + public void onQuit(Player player) { + super.onQuit(player); } -} \ No newline at end of file + + @Override + public void onJoin(Player player) { + super.onJoin(player); + } +} diff --git a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarSender.java b/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarSender.java deleted file mode 100644 index 960767f2..00000000 --- a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarSender.java +++ /dev/null @@ -1,103 +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.competition.bossbar; - -import net.kyori.adventure.audience.Audience; -import net.kyori.adventure.bossbar.BossBar; -import net.momirealms.customfishing.ConfigReader; -import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.competition.Competition; -import net.momirealms.customfishing.competition.CompetitionSchedule; -import net.momirealms.customfishing.hook.PapiHook; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.Optional; - -public class BossBarSender extends BukkitRunnable { - - private final Player player; - private final Audience audience; - private BossBar bossBar; - private int timer; - private final BossBar.Color color; - private final BossBar.Overlay overlay; - private final String text; - private final int rate; - - public BossBarSender(Player player, BossBarConfig bossbarConfig){ - this.player = player; - this.audience = CustomFishing.adventure.player(player); - this.timer = 0; - this.color = bossbarConfig.getColor(); - this.overlay = bossbarConfig.getOverlay(); - this.text = bossbarConfig.getText(); - this.rate = bossbarConfig.getRate(); - } - - public void hideBossbar(){ - audience.hideBossBar(bossBar); - } - - public void showBossbar(){ - String newText = updateText(); - bossBar = BossBar.bossBar( - CustomFishing.miniMessage.deserialize(newText), - Competition.progress, - color, - overlay); - audience.showBossBar(bossBar); - } - - @Override - public void run() { - if (timer < rate){ - timer++; - }else { - updateText(); - String newText = updateText(); - bossBar.name(CustomFishing.miniMessage.deserialize(newText)); - bossBar.progress(Competition.progress); - timer = 0; - } - } - - private String updateText() { - String text; - if (ConfigReader.Config.papi){ - text = PapiHook.parse(player, this.text); - }else { - text = this.text; - } - String newText; - if (ConfigReader.Config.papi){ - newText = PapiHook.parse(player, text.replace("{time}", String.valueOf(Competition.remainingTime)) - .replace("{rank}", Optional.ofNullable(CompetitionSchedule.competition.getRanking().getPlayerRank(player.getName())).orElse(ConfigReader.Message.noRank)) - .replace("{minute}", String.format("%02d",Competition.remainingTime/60)) - .replace("{second}",String.format("%02d",Competition.remainingTime%60)) - .replace("{point}", String.format("%.1f",Optional.ofNullable(CompetitionSchedule.competition.getRanking().getCompetitionPlayer(player.getName())).orElse(Competition.emptyPlayer).getScore()))); - }else { - newText = text.replace("{time}", String.valueOf(Competition.remainingTime)) - .replace("{rank}", Optional.ofNullable(CompetitionSchedule.competition.getRanking().getPlayerRank(player.getName())).orElse(ConfigReader.Message.noRank)) - .replace("{minute}", String.format("%02d",Competition.remainingTime/60)) - .replace("{second}",String.format("%02d",Competition.remainingTime%60)) - .replace("{point}", String.format("%.1f",Optional.ofNullable(CompetitionSchedule.competition.getRanking().getCompetitionPlayer(player.getName())).orElse(Competition.emptyPlayer).getScore())); - } - return newText; - } -} diff --git a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarTimer.java b/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarTimer.java deleted file mode 100644 index f17b5881..00000000 --- a/src/main/java/net/momirealms/customfishing/competition/bossbar/BossBarTimer.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.competition.bossbar; - -import net.momirealms.customfishing.CustomFishing; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitTask; - -import java.util.HashMap; - -public class BossBarTimer { - - private HashMap bossbarCache = new HashMap<>(); - - public BossBarTimer(Player player, BossBarConfig bossBarConfig){ - - BossBarSender bossbar = new BossBarSender(player, bossBarConfig); - bossbar.showBossbar(); - BukkitTask task = bossbar.runTaskTimerAsynchronously(CustomFishing.instance, 0,1); - bossbarCache.put(task.getTaskId(), bossbar); - - } - - public void stopTimer(){ - bossbarCache.forEach((key,value)-> { - value.hideBossbar(); - Bukkit.getScheduler().cancelTask(key); - }); - bossbarCache = null; - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/competition/Goal.java b/src/main/java/net/momirealms/customfishing/competition/bossbar/Overlay.java similarity index 81% rename from src/main/java/net/momirealms/customfishing/competition/Goal.java rename to src/main/java/net/momirealms/customfishing/competition/bossbar/Overlay.java index 76a0f66e..f3941409 100644 --- a/src/main/java/net/momirealms/customfishing/competition/Goal.java +++ b/src/main/java/net/momirealms/customfishing/competition/bossbar/Overlay.java @@ -15,12 +15,12 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.competition; - -public enum Goal { - - TOTAL_SCORE, - CATCH_AMOUNT, - RANDOM +package net.momirealms.customfishing.competition.bossbar; +public enum Overlay { + NOTCHED_6, + NOTCHED_10, + NOTCHED_12, + NOTCHED_20, + PROGRESS } diff --git a/src/main/java/net/momirealms/customfishing/competition/bossbar/Sender.java b/src/main/java/net/momirealms/customfishing/competition/bossbar/Sender.java new file mode 100644 index 00000000..c51ebde2 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/competition/bossbar/Sender.java @@ -0,0 +1,164 @@ +/* + * 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.competition.bossbar; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.events.InternalStructure; +import com.comphenix.protocol.events.PacketContainer; +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.Reflection; +import net.momirealms.customfishing.object.TextCache; +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.boss.BarColor; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import java.lang.reflect.InvocationTargetException; +import java.util.Optional; +import java.util.UUID; + +public class Sender { + + private final Player player; + private int timer_1; + private int timer_2; + private int counter; + private final int size; + private final TextCache[] texts; + private TextCache text; + private BukkitTask bukkitTask; + private final UUID uuid; + private boolean force; + private final BossBarConfig config; + private boolean isShown; + private final BossBarManager bossBarManager; + + public void setText(int position) { + this.text = texts[position]; + this.force = true; + } + + public Sender(Player player, BossBarConfig config, BossBarManager bossBarManager){ + this.bossBarManager = bossBarManager; + String[] str = config.getText(); + this.size = str.length; + texts = new TextCache[str.length]; + for (int i = 0; i < str.length; i++) { + texts[i] = new TextCache(player, str[i]); + } + text = texts[0]; + this.player = player; + this.uuid = UUID.randomUUID(); + this.config = config; + this.isShown = false; + } + + public void show() { + this.isShown = true; + + try { + CustomFishing.protocolManager.sendServerPacket(player, getPacket()); + } catch (InvocationTargetException e){ + AdventureUtil.consoleMessage("[CustomFishing] Failed to display bossbar for " + player.getName()); + } + + this.bukkitTask = new BukkitRunnable() { + @Override + public void run() { + if (size != 1) { + timer_2++; + if (timer_2 > config.getInterval()) { + timer_2 = 0; + counter++; + if (counter == size) { + counter = 0; + } + setText(counter); + } + } + if (timer_1 < config.getRate()){ + timer_1++; + } + else { + timer_1 = 0; + if (text.update() || force) { + force = false; + try{ + CustomFishing.protocolManager.sendServerPacket(player, getPacket()); + } + catch (InvocationTargetException e){ + AdventureUtil.consoleMessage("[CustomFishing] Failed to update bossbar for " + player.getName()); + } + } + } + } + }.runTaskTimerAsynchronously(CustomFishing.plugin,1,1); + } + + private PacketContainer getPacket() { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.BOSS); + packet.getModifier().write(0, uuid); + InternalStructure internalStructure = packet.getStructures().read(1); + internalStructure.getChatComponents().write(0, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize( + text.getLatestValue() + .replace("{rank}", Competition.currentCompetition.getPlayerRank(player)) + .replace("{minute}", String.format("%02d", Competition.currentCompetition.getRemainingTime() / 60)) + .replace("{second}",String.format("%02d", Competition.currentCompetition.getRemainingTime() % 60)) + .replace("{point}", String.format("%.1f", Competition.currentCompetition.getScore(player)) + .replace("{1st_score}", String.format("%.1f", Competition.currentCompetition.getFirstScore())) + .replace("{1st_player}", Competition.currentCompetition.getFirstPlayer()) + ))))); + internalStructure.getFloat().write(0,1F); + internalStructure.getEnumModifier(BarColor.class, 2).write(0, config.getColor()); + internalStructure.getEnumModifier(Overlay.class, 3).write(0, config.getOverlay()); + internalStructure.getModifier().write(4, false); + internalStructure.getModifier().write(5, false); + internalStructure.getModifier().write(6, false); + return packet; + } + + public void hide() { + remove(); + if (bukkitTask != null) bukkitTask.cancel(); + this.isShown = false; + } + + private void remove() { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.BOSS); + packet.getModifier().write(0, uuid); + packet.getModifier().write(1, Reflection.removeBar); + try{ + CustomFishing.protocolManager.sendServerPacket(player, packet); + }catch (InvocationTargetException e){ + AdventureUtil.consoleMessage("[CustomFishing] Failed to remove bossbar for " + player.getName()); + } + } + + public boolean getStatus() { + return this.isShown; + } + + public BossBarConfig getConfig() { + return config; + } +} diff --git a/src/main/java/net/momirealms/customfishing/competition/ranking/RankingImpl.java b/src/main/java/net/momirealms/customfishing/competition/ranking/LocalRankingImpl.java similarity index 81% rename from src/main/java/net/momirealms/customfishing/competition/ranking/RankingImpl.java rename to src/main/java/net/momirealms/customfishing/competition/ranking/LocalRankingImpl.java index dc76c2fc..473623b4 100644 --- a/src/main/java/net/momirealms/customfishing/competition/ranking/RankingImpl.java +++ b/src/main/java/net/momirealms/customfishing/competition/ranking/LocalRankingImpl.java @@ -1,27 +1,11 @@ -/* - * 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.competition.ranking; import net.momirealms.customfishing.competition.CompetitionPlayer; +import net.momirealms.customfishing.manager.MessageManager; import java.util.*; -public class RankingImpl implements Ranking{ +public class LocalRankingImpl implements RankingInterface { private final Set competitionPlayers = Collections.synchronizedSet(new TreeSet<>()); @@ -107,7 +91,6 @@ public class RankingImpl implements Ranking{ return null; } - public float getScoreAt(int i) { int index = 1; for (CompetitionPlayer competitionPlayer : competitionPlayers) { @@ -116,7 +99,7 @@ public class RankingImpl implements Ranking{ } index++; } - return -1.0f; + return 0f; } @Override @@ -131,4 +114,14 @@ public class RankingImpl implements Ranking{ addPlayer(competitionPlayer); } } + + @Override + public float getFirstScore() { + return getScoreAt(1); + } + + @Override + public String getFirstPlayer() { + return Optional.ofNullable(getPlayerAt(1)).orElse(MessageManager.noPlayer); + } } diff --git a/src/main/java/net/momirealms/customfishing/competition/ranking/Ranking.java b/src/main/java/net/momirealms/customfishing/competition/ranking/Ranking.java deleted file mode 100644 index 5e6a1add..00000000 --- a/src/main/java/net/momirealms/customfishing/competition/ranking/Ranking.java +++ /dev/null @@ -1,32 +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.competition.ranking; - -import net.momirealms.customfishing.competition.CompetitionPlayer; - -import java.util.Iterator; - -public interface Ranking { - void clear(); - CompetitionPlayer getCompetitionPlayer(String player); - Iterator getIterator(); - int getSize(); - String getPlayerRank(String player); - CompetitionPlayer[] getTop3Player(); - void refreshData(String player, float score); -} diff --git a/src/main/java/net/momirealms/customfishing/competition/ranking/RankingInterface.java b/src/main/java/net/momirealms/customfishing/competition/ranking/RankingInterface.java new file mode 100644 index 00000000..02d68889 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/competition/ranking/RankingInterface.java @@ -0,0 +1,18 @@ +package net.momirealms.customfishing.competition.ranking; + +import net.momirealms.customfishing.competition.CompetitionPlayer; + +import java.util.Iterator; + +public interface RankingInterface { + + void clear(); + CompetitionPlayer getCompetitionPlayer(String player); + Iterator getIterator(); + int getSize(); + String getPlayerRank(String player); + CompetitionPlayer[] getTop3Player(); + void refreshData(String player, float score); + float getFirstScore(); + String getFirstPlayer(); +} diff --git a/src/main/java/net/momirealms/customfishing/competition/ranking/RedisRankingImpl.java b/src/main/java/net/momirealms/customfishing/competition/ranking/RedisRankingImpl.java index 7780831b..887083d8 100644 --- a/src/main/java/net/momirealms/customfishing/competition/ranking/RedisRankingImpl.java +++ b/src/main/java/net/momirealms/customfishing/competition/ranking/RedisRankingImpl.java @@ -1,31 +1,15 @@ -/* - * 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.competition.ranking; import net.momirealms.customfishing.competition.CompetitionPlayer; -import net.momirealms.customfishing.utils.JedisUtil; +import net.momirealms.customfishing.manager.MessageManager; +import net.momirealms.customfishing.util.JedisUtil; import redis.clients.jedis.Jedis; import redis.clients.jedis.resps.Tuple; import java.util.Iterator; import java.util.List; -public class RedisRankingImpl implements Ranking{ +public class RedisRankingImpl implements RankingInterface { public void addPlayer(CompetitionPlayer competitionPlayer) { Jedis jedis = JedisUtil.getJedis(); @@ -90,13 +74,13 @@ public class RedisRankingImpl implements Ranking{ jedis.close(); int index = 1; for (Tuple tuple : players){ - if (index == 1){ + if (index == 1) { competitionPlayers[0] = new CompetitionPlayer(tuple.getElement(), (float) tuple.getScore()); } - if (index == 2){ + if (index == 2) { competitionPlayers[1] = new CompetitionPlayer(tuple.getElement(), (float) tuple.getScore()); } - if (index == 3){ + if (index == 3) { competitionPlayers[2] = new CompetitionPlayer(tuple.getElement(), (float) tuple.getScore()); return competitionPlayers; } @@ -111,4 +95,23 @@ public class RedisRankingImpl implements Ranking{ jedis.zincrby("cf_competition", score, player); jedis.close(); } + + @Override + public float getFirstScore() { + Jedis jedis = JedisUtil.getJedis(); + List players = jedis.zrevrangeWithScores("cf_competition", 0, 0); + if (players == null) return 0; + if (players.size() == 0) return 0; + return (float) players.get(0).getScore(); + } + + @Override + public String getFirstPlayer() { + Jedis jedis = JedisUtil.getJedis(); + List player = jedis.zrevrange("cf_competition", 0,0); + jedis.close(); + if (player == null) return MessageManager.noPlayer; + if (player.size() == 0) return MessageManager.noPlayer; + return player.get(0); + } } diff --git a/src/main/java/net/momirealms/customfishing/helper/LibraryLoader.java b/src/main/java/net/momirealms/customfishing/helper/LibraryLoader.java index d268313f..23f2c81b 100644 --- a/src/main/java/net/momirealms/customfishing/helper/LibraryLoader.java +++ b/src/main/java/net/momirealms/customfishing/helper/LibraryLoader.java @@ -27,7 +27,6 @@ package net.momirealms.customfishing.helper; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; - import net.momirealms.customfishing.CustomFishing; import org.apache.commons.lang.StringUtils; @@ -46,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.instance.getClass().getClassLoader())); + private static final Supplier URL_INJECTOR = Suppliers.memoize(() -> URLClassLoaderAccess.create((URLClassLoader) CustomFishing.plugin.getClass().getClassLoader())); /** * Resolves all {@link MavenLibrary} annotations on the given object. @@ -78,7 +77,9 @@ public final class LibraryLoader { } public static void load(Dependency d) { + //Log.info(String.format("Loading dependency %s:%s:%s from %s", d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getRepoUrl())); String name = d.getArtifactId() + "-" + d.getVersion(); + File saveLocation = new File(getLibFolder(d), name + ".jar"); if (!saveLocation.exists()) { @@ -97,23 +98,28 @@ public final class LibraryLoader { } if (!saveLocation.exists()) { - throw new RuntimeException("Unable to download dependency: " + d); + throw new RuntimeException("Unable to download dependency: " + d.toString()); } try { URL_INJECTOR.get().addURL(saveLocation.toURI().toURL()); } catch (Exception e) { - throw new RuntimeException("Unable to load dependency: " + saveLocation, e); + throw new RuntimeException("Unable to load dependency: " + saveLocation.toString(), e); } } private static File getLibFolder(Dependency dependency) { - File pluginDataFolder = CustomFishing.instance.getDataFolder(); + File pluginDataFolder = CustomFishing.plugin.getDataFolder(); File serverDir = pluginDataFolder.getParentFile().getParentFile(); File helperDir = new File(serverDir, "libraries"); String[] split = StringUtils.split(dependency.getGroupId(), "."); - File jarDir = new File(helperDir, split[0] + File.separator + split[1] + File.separator + dependency.artifactId + File.separator + dependency.version ); + File jarDir; + if (split.length > 1){ + jarDir = new File(helperDir, split[0] + File.separator + split[1] + File.separator + dependency.artifactId + File.separator + dependency.version ); + }else { + jarDir = new File(helperDir, dependency.getGroupId() + File.separator + dependency.artifactId + File.separator + dependency.version ); + } jarDir.mkdirs(); return jarDir; } diff --git a/src/main/java/net/momirealms/customfishing/helper/Log.java b/src/main/java/net/momirealms/customfishing/helper/Log.java index 1de2eb0f..30ad817a 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.instance.getLogger().info(s); + CustomFishing.plugin.getLogger().info(s); } public static void warn(@NotNull String s) { - CustomFishing.instance.getLogger().warning(s); + CustomFishing.plugin.getLogger().warning(s); } public static void severe(@NotNull String s) { - CustomFishing.instance.getLogger().severe(s); + CustomFishing.plugin.getLogger().severe(s); } public static void warn(@NotNull String s, Throwable t) { - CustomFishing.instance.getLogger().log(Level.WARNING, s, t); + CustomFishing.plugin.getLogger().log(Level.WARNING, s, t); } public static void severe(@NotNull String s, Throwable t) { - CustomFishing.instance.getLogger().log(Level.SEVERE, s, t); + CustomFishing.plugin.getLogger().log(Level.SEVERE, s, t); } private Log() { diff --git a/src/main/java/net/momirealms/customfishing/helper/MavenLibraries.java b/src/main/java/net/momirealms/customfishing/helper/MavenLibraries.java index 63c08271..dae6f3cf 100644 --- a/src/main/java/net/momirealms/customfishing/helper/MavenLibraries.java +++ b/src/main/java/net/momirealms/customfishing/helper/MavenLibraries.java @@ -27,11 +27,7 @@ package net.momirealms.customfishing.helper; import org.jetbrains.annotations.NotNull; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; /** * Annotation to indicate the required libraries for a class. diff --git a/src/main/java/net/momirealms/customfishing/helper/MavenLibrary.java b/src/main/java/net/momirealms/customfishing/helper/MavenLibrary.java index 513a652e..7a979775 100644 --- a/src/main/java/net/momirealms/customfishing/helper/MavenLibrary.java +++ b/src/main/java/net/momirealms/customfishing/helper/MavenLibrary.java @@ -27,12 +27,7 @@ package net.momirealms.customfishing.helper; import org.jetbrains.annotations.NotNull; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Repeatable; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; /** * Annotation to indicate a required library for a class. diff --git a/src/main/java/net/momirealms/customfishing/helper/Repository.java b/src/main/java/net/momirealms/customfishing/helper/Repository.java index 2e1a92e8..03c3affc 100644 --- a/src/main/java/net/momirealms/customfishing/helper/Repository.java +++ b/src/main/java/net/momirealms/customfishing/helper/Repository.java @@ -25,13 +25,8 @@ package net.momirealms.customfishing.helper; -import org.jetbrains.annotations.NotNull; +import java.lang.annotation.*; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; /** * Represents a maven repository. */ @@ -45,7 +40,6 @@ public @interface Repository { * * @return the base url of the repository */ - @NotNull String url(); } diff --git a/src/main/java/net/momirealms/customfishing/hook/ItemsAdderItem.java b/src/main/java/net/momirealms/customfishing/hook/ItemsAdderItem.java deleted file mode 100644 index da094515..00000000 --- a/src/main/java/net/momirealms/customfishing/hook/ItemsAdderItem.java +++ /dev/null @@ -1,11 +0,0 @@ -package net.momirealms.customfishing.hook; - -import dev.lone.itemsadder.api.CustomStack; -import org.bukkit.inventory.ItemStack; - -public class ItemsAdderItem { - - public static ItemStack getItemStack(String namespacedID){ - return CustomStack.getInstance(namespacedID).getItemStack(); - } -} diff --git a/src/main/java/net/momirealms/customfishing/hook/MMOItemsHook.java b/src/main/java/net/momirealms/customfishing/hook/MMOItemsHook.java deleted file mode 100644 index 979f3b26..00000000 --- a/src/main/java/net/momirealms/customfishing/hook/MMOItemsHook.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.momirealms.customfishing.hook; - -import net.Indyuce.mmoitems.MMOItems; -import net.Indyuce.mmoitems.api.Type; -import org.apache.commons.lang.StringUtils; -import org.bukkit.inventory.ItemStack; - -public class MMOItemsHook { - - public static ItemStack getItemStack(String name){ - String[] split = StringUtils.split(name, ":"); - return MMOItems.plugin.getMMOItem(Type.get(split[0]), split[1]).newBuilder().getItemStack(); - } -} diff --git a/src/main/java/net/momirealms/customfishing/hook/MythicItems.java b/src/main/java/net/momirealms/customfishing/hook/MythicItems.java deleted file mode 100644 index 871750fa..00000000 --- a/src/main/java/net/momirealms/customfishing/hook/MythicItems.java +++ /dev/null @@ -1,11 +0,0 @@ -package net.momirealms.customfishing.hook; - -import io.lumine.mythic.bukkit.MythicBukkit; -import org.bukkit.inventory.ItemStack; - -public class MythicItems { - - public static ItemStack getItemStack(String name){ - return MythicBukkit.inst().getItemManager().getItemStack(name); - } -} diff --git a/src/main/java/net/momirealms/customfishing/hook/MythicMobsUtil.java b/src/main/java/net/momirealms/customfishing/hook/MythicMobsUtil.java deleted file mode 100644 index 3a1b19d0..00000000 --- a/src/main/java/net/momirealms/customfishing/hook/MythicMobsUtil.java +++ /dev/null @@ -1,50 +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.hook; - -import io.lumine.mythic.api.adapters.AbstractLocation; -import io.lumine.mythic.api.adapters.AbstractVector; -import io.lumine.mythic.api.mobs.MobManager; -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.object.MobVector; -import net.momirealms.customfishing.object.loot.Mob; -import org.bukkit.Location; -import org.bukkit.util.Vector; - -import java.util.Optional; - -public class MythicMobsUtil { - - public static void summonMM(Location pLocation, Location bLocation, Mob mob){ - MobManager mobManager = MythicBukkit.inst().getMobManager(); - Optional mythicMob = mobManager.getMythicMob(mob.getMmID()); - if (mythicMob.isPresent()) { - MythicMob theMob = mythicMob.get(); - Position position = Position.of(bLocation); - AbstractLocation abstractLocation = new AbstractLocation(position); - ActiveMob activeMob = theMob.spawn(abstractLocation, mob.getMmLevel()); - MobVector mobVector = mob.getMobVector(); - Vector vector = pLocation.subtract(bLocation).toVector().multiply((mobVector.getHorizontal())-1); - vector = vector.setY((vector.getY()+0.2)*mobVector.getVertical()); - activeMob.getEntity().setVelocity(new AbstractVector(vector.getX(),vector.getY(),vector.getZ())); - } - } -} diff --git a/src/main/java/net/momirealms/customfishing/hook/OraxenItem.java b/src/main/java/net/momirealms/customfishing/hook/OraxenItem.java deleted file mode 100644 index 307dbcc9..00000000 --- a/src/main/java/net/momirealms/customfishing/hook/OraxenItem.java +++ /dev/null @@ -1,11 +0,0 @@ -package net.momirealms.customfishing.hook; - -import io.th0rgal.oraxen.items.OraxenItems; -import org.bukkit.inventory.ItemStack; - -public class OraxenItem { - - public static ItemStack getItemStack(String namespacedID){ - return OraxenItems.getItemById(namespacedID).build(); - } -} diff --git a/src/main/java/net/momirealms/customfishing/hook/Placeholders.java b/src/main/java/net/momirealms/customfishing/hook/Placeholders.java deleted file mode 100644 index 91024853..00000000 --- a/src/main/java/net/momirealms/customfishing/hook/Placeholders.java +++ /dev/null @@ -1,63 +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.hook; - -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import net.momirealms.customfishing.ConfigReader; -import net.momirealms.customfishing.competition.Competition; -import net.momirealms.customfishing.competition.CompetitionSchedule; -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; - -import java.util.Optional; - -public class Placeholders extends PlaceholderExpansion { - @Override - public @NotNull String getIdentifier() { - return "competition"; - } - - @Override - public @NotNull String getAuthor() { - return "XiaoMoMi"; - } - - @Override - public @NotNull String getVersion() { - return "1.0"; - } - - @Override - public String onRequest(OfflinePlayer player, String params) { - if (params.equalsIgnoreCase("timeleft")){ - if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()){ - return String.valueOf(Competition.remainingTime); - }else { - return "0"; - } - } - if (params.equalsIgnoreCase("rank")){ - if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()){ - return Optional.ofNullable(CompetitionSchedule.competition.getRanking().getPlayerRank(player.getName())).orElse(ConfigReader.Message.noRank); - }else { - return ConfigReader.Message.noRank; - } - } - return null; - } -} diff --git a/src/main/java/net/momirealms/customfishing/hook/season/CustomCropsSeason.java b/src/main/java/net/momirealms/customfishing/hook/season/CustomCropsSeason.java deleted file mode 100644 index d6acaca9..00000000 --- a/src/main/java/net/momirealms/customfishing/hook/season/CustomCropsSeason.java +++ /dev/null @@ -1,10 +0,0 @@ -package net.momirealms.customfishing.hook.season; - -import net.momirealms.customcrops.api.CustomCropsAPI; -import org.bukkit.World; - -public class CustomCropsSeason implements SeasonInterface{ - public String getSeason(World world){ - return CustomCropsAPI.getSeason(world.getName()); - } -} diff --git a/src/main/java/net/momirealms/customfishing/hook/season/RealisticSeason.java b/src/main/java/net/momirealms/customfishing/hook/season/RealisticSeason.java deleted file mode 100644 index f76aa645..00000000 --- a/src/main/java/net/momirealms/customfishing/hook/season/RealisticSeason.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.momirealms.customfishing.hook.season; - -import me.casperge.realisticseasons.api.SeasonsAPI; -import org.bukkit.World; - -public class RealisticSeason implements SeasonInterface{ - public String getSeason(World world){ - SeasonsAPI seasonsapi = SeasonsAPI.getInstance(); - switch (seasonsapi.getSeason(world)){ - case SPRING -> { - return "spring"; - } - case SUMMER -> { - return "summer"; - } - case WINTER -> { - return "winter"; - } - case FALL -> { - return "autumn"; - } - } - return "null"; - } -} diff --git a/src/main/java/net/momirealms/customfishing/hook/skill/EcoSkill.java b/src/main/java/net/momirealms/customfishing/hook/skill/EcoSkill.java deleted file mode 100644 index b5b577fe..00000000 --- a/src/main/java/net/momirealms/customfishing/hook/skill/EcoSkill.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.momirealms.customfishing.hook.skill; - -import com.willfp.ecoskills.api.EcoSkillsAPI; -import com.willfp.ecoskills.skills.Skills; -import org.bukkit.entity.Player; - -public class EcoSkill implements SkillXP { - - @Override - public void addXp(Player player, double amount) { - EcoSkillsAPI.getInstance().giveSkillExperience(player, Skills.FISHING, amount); - } - - @Override - public int getLevel(Player player) { - return EcoSkillsAPI.getInstance().getSkillLevel(player, Skills.FISHING); - } -} diff --git a/src/main/java/net/momirealms/customfishing/hook/skill/JobsReborn.java b/src/main/java/net/momirealms/customfishing/hook/skill/JobsReborn.java deleted file mode 100644 index 9cc31eec..00000000 --- a/src/main/java/net/momirealms/customfishing/hook/skill/JobsReborn.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.momirealms.customfishing.hook.skill; - -import com.gamingmesh.jobs.Jobs; -import com.gamingmesh.jobs.container.Job; -import com.gamingmesh.jobs.container.JobProgression; -import com.gamingmesh.jobs.container.JobsPlayer; -import org.bukkit.entity.Player; - -import java.util.List; - -public class JobsReborn implements SkillXP{ - - @Override - public void addXp(Player player, double amount) { - JobsPlayer jobsPlayer = Jobs.getPlayerManager().getJobsPlayer(player); - - if (jobsPlayer != null) { - List jobs = jobsPlayer.getJobProgression(); - - Job job = Jobs.getJob("Fisherman"); - - for (JobProgression progression : jobs) - if (progression.getJob().equals(job)){ - progression.addExperience(amount); - } - } - } - - @Override - public int getLevel(Player player) { - JobsPlayer jobsPlayer = Jobs.getPlayerManager().getJobsPlayer(player); - - if (jobsPlayer != null) { - List jobs = jobsPlayer.getJobProgression(); - - Job job = Jobs.getJob("Fisherman"); - - for (JobProgression progression : jobs) - if (progression.getJob().equals(job)) - return progression.getLevel(); - } - return 0; - } -} diff --git a/src/main/java/net/momirealms/customfishing/integration/BlockInterface.java b/src/main/java/net/momirealms/customfishing/integration/BlockInterface.java new file mode 100644 index 00000000..052d2b50 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/BlockInterface.java @@ -0,0 +1,13 @@ +package net.momirealms.customfishing.integration; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.jetbrains.annotations.Nullable; + +public interface BlockInterface { + + void removeBlock(Block block); + void placeBlock(String id, Location location); + @Nullable + String getID(Block block); +} diff --git a/src/main/java/net/momirealms/customfishing/integration/ItemInterface.java b/src/main/java/net/momirealms/customfishing/integration/ItemInterface.java new file mode 100644 index 00000000..2dcf33f3 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/ItemInterface.java @@ -0,0 +1,11 @@ +package net.momirealms.customfishing.integration; + +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public interface ItemInterface { + + @Nullable + ItemStack build(String id); + +} diff --git a/src/main/java/net/momirealms/customfishing/integration/MobInterface.java b/src/main/java/net/momirealms/customfishing/integration/MobInterface.java new file mode 100644 index 00000000..e2fe1800 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/MobInterface.java @@ -0,0 +1,8 @@ +package net.momirealms.customfishing.integration; + +import net.momirealms.customfishing.object.loot.Mob; +import org.bukkit.Location; + +public interface MobInterface { + void summon(Location playerLoc, Location summonLoc, Mob mob); +} diff --git a/src/main/java/net/momirealms/customfishing/hook/season/SeasonInterface.java b/src/main/java/net/momirealms/customfishing/integration/SeasonInterface.java similarity index 64% rename from src/main/java/net/momirealms/customfishing/hook/season/SeasonInterface.java rename to src/main/java/net/momirealms/customfishing/integration/SeasonInterface.java index 033bfbf3..7b9c458d 100644 --- a/src/main/java/net/momirealms/customfishing/hook/season/SeasonInterface.java +++ b/src/main/java/net/momirealms/customfishing/integration/SeasonInterface.java @@ -1,7 +1,8 @@ -package net.momirealms.customfishing.hook.season; +package net.momirealms.customfishing.integration; import org.bukkit.World; public interface SeasonInterface { + String getSeason(World world); -} \ No newline at end of file +} diff --git a/src/main/java/net/momirealms/customfishing/integration/SkillInterface.java b/src/main/java/net/momirealms/customfishing/integration/SkillInterface.java new file mode 100644 index 00000000..5175d588 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/SkillInterface.java @@ -0,0 +1,9 @@ +package net.momirealms.customfishing.integration; + +import org.bukkit.entity.Player; + +public interface SkillInterface { + + void addXp(Player player, double amount); + int getLevel(Player player); +} diff --git a/src/main/java/net/momirealms/customfishing/integration/block/ItemsAdderBlockHook.java b/src/main/java/net/momirealms/customfishing/integration/block/ItemsAdderBlockHook.java new file mode 100644 index 00000000..6b94444f --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/block/ItemsAdderBlockHook.java @@ -0,0 +1,27 @@ +package net.momirealms.customfishing.integration.block; + +import dev.lone.itemsadder.api.CustomBlock; +import net.momirealms.customfishing.integration.BlockInterface; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.jetbrains.annotations.Nullable; + +public class ItemsAdderBlockHook implements BlockInterface { + + @Override + public void removeBlock(Block block) { + CustomBlock.remove(block.getLocation()); + } + + @Override + public void placeBlock(String id, Location location) { + CustomBlock.place(id, location); + } + + @Override + @Nullable + public String getID(Block block) { + CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); + return customBlock == null ? null : customBlock.getNamespacedID(); + } +} diff --git a/src/main/java/net/momirealms/customfishing/integration/block/OraxenBlockHook.java b/src/main/java/net/momirealms/customfishing/integration/block/OraxenBlockHook.java new file mode 100644 index 00000000..7c51960d --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/block/OraxenBlockHook.java @@ -0,0 +1,31 @@ +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.integration.BlockInterface; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.jetbrains.annotations.Nullable; + +public class OraxenBlockHook implements BlockInterface { + + @Override + public void removeBlock(Block block) { + block.setType(Material.AIR); + } + + @Override + public void placeBlock(String id, Location location) { + NoteBlockMechanicFactory.setBlockModel(location.getBlock(), id); + } + + @Nullable + @Override + public String getID(Block block) { + NoteBlockMechanic mechanic = NoteBlockMechanicListener.getNoteBlockMechanic(block); + if (mechanic == null) return null; + else return mechanic.getItemID(); + } +} diff --git a/src/main/java/net/momirealms/customfishing/integration/item/CustomFishingItemHook.java b/src/main/java/net/momirealms/customfishing/integration/item/CustomFishingItemHook.java new file mode 100644 index 00000000..49eacbdb --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/item/CustomFishingItemHook.java @@ -0,0 +1,16 @@ +package net.momirealms.customfishing.integration.item; + +import net.momirealms.customfishing.integration.ItemInterface; +import net.momirealms.customfishing.manager.LootManager; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class CustomFishingItemHook implements ItemInterface { + + @Override + @Nullable + public ItemStack build(String material) { + if (material.contains(":")) return null; + return LootManager.build(material); + } +} diff --git a/src/main/java/net/momirealms/customfishing/hook/EcoItemRegister.java b/src/main/java/net/momirealms/customfishing/integration/item/EcoItemHook.java similarity index 78% rename from src/main/java/net/momirealms/customfishing/hook/EcoItemRegister.java rename to src/main/java/net/momirealms/customfishing/integration/item/EcoItemHook.java index 3027cce6..4ca1889d 100644 --- a/src/main/java/net/momirealms/customfishing/hook/EcoItemRegister.java +++ b/src/main/java/net/momirealms/customfishing/integration/item/EcoItemHook.java @@ -1,22 +1,22 @@ -package net.momirealms.customfishing.hook; +package net.momirealms.customfishing.integration.item; import com.willfp.eco.core.items.CustomItem; import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTItem; -import net.momirealms.customfishing.ConfigReader; import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.manager.BonusManager; import org.bukkit.NamespacedKey; import org.bukkit.inventory.ItemStack; -import org.bukkit.persistence.PersistentDataType; import java.util.Map; -public class EcoItemRegister { +public class EcoItemHook { + public static void registerItems() { // Rods - for (Map.Entry entry : ConfigReader.RodItem.entrySet()) { + for (Map.Entry entry : BonusManager.RODITEMS.entrySet()) { new CustomItem( - new NamespacedKey(CustomFishing.instance, "rod_" + entry.getKey()), + new NamespacedKey(CustomFishing.plugin, "rod_" + entry.getKey()), itemStack -> { try { NBTItem nbtItem = new NBTItem(itemStack); @@ -32,9 +32,9 @@ public class EcoItemRegister { ).register(); } // Baits - for (Map.Entry entry : ConfigReader.BaitItem.entrySet()) { + for (Map.Entry entry : BonusManager.BAITITEMS.entrySet()) { new CustomItem( - new NamespacedKey(CustomFishing.instance, "bait_" + entry.getKey()), + new NamespacedKey(CustomFishing.plugin, "bait_" + entry.getKey()), itemStack -> { try { NBTItem nbtItem = new NBTItem(itemStack); @@ -50,9 +50,9 @@ public class EcoItemRegister { ).register(); } // Utils - for (Map.Entry entry : ConfigReader.UtilItem.entrySet()) { + for (Map.Entry entry : BonusManager.UTILITEMS.entrySet()) { new CustomItem( - new NamespacedKey(CustomFishing.instance, "util_" + entry.getKey()), + new NamespacedKey(CustomFishing.plugin, "util_" + entry.getKey()), itemStack -> { try { NBTItem nbtItem = new NBTItem(itemStack); diff --git a/src/main/java/net/momirealms/customfishing/integration/item/ItemsAdderItemHook.java b/src/main/java/net/momirealms/customfishing/integration/item/ItemsAdderItemHook.java new file mode 100644 index 00000000..d6f2f5f6 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/item/ItemsAdderItemHook.java @@ -0,0 +1,18 @@ +package net.momirealms.customfishing.integration.item; + +import dev.lone.itemsadder.api.CustomStack; +import net.momirealms.customfishing.integration.ItemInterface; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class ItemsAdderItemHook implements ItemInterface { + + @Override + @Nullable + public ItemStack build(String material) { + if (!material.startsWith("ItemsAdder:")) return null; + material = material.substring(11); + CustomStack customStack = CustomStack.getInstance(material); + return customStack == null ? null : customStack.getItemStack(); + } +} diff --git a/src/main/java/net/momirealms/customfishing/integration/item/MMOItemsItemHook.java b/src/main/java/net/momirealms/customfishing/integration/item/MMOItemsItemHook.java new file mode 100644 index 00000000..056a9232 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/item/MMOItemsItemHook.java @@ -0,0 +1,22 @@ +package net.momirealms.customfishing.integration.item; + +import net.Indyuce.mmoitems.MMOItems; +import net.Indyuce.mmoitems.api.Type; +import net.Indyuce.mmoitems.api.item.mmoitem.MMOItem; +import net.momirealms.customfishing.integration.ItemInterface; +import org.apache.commons.lang.StringUtils; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class MMOItemsItemHook implements ItemInterface { + + @Nullable + @Override + public ItemStack build(String material) { + if (!material.startsWith("MMOItems:")) return null; + material = material.substring(9); + String[] split = StringUtils.split(material, ":"); + MMOItem mmoItem = MMOItems.plugin.getMMOItem(Type.get(split[0]), split[1]); + return mmoItem == null ? null : mmoItem.newBuilder().getItemStack(); + } +} diff --git a/src/main/java/net/momirealms/customfishing/hook/McMMOTreasure.java b/src/main/java/net/momirealms/customfishing/integration/item/McMMOTreasure.java similarity index 96% rename from src/main/java/net/momirealms/customfishing/hook/McMMOTreasure.java rename to src/main/java/net/momirealms/customfishing/integration/item/McMMOTreasure.java index 089aa2fa..8cfc2ce5 100644 --- a/src/main/java/net/momirealms/customfishing/hook/McMMOTreasure.java +++ b/src/main/java/net/momirealms/customfishing/integration/item/McMMOTreasure.java @@ -1,4 +1,4 @@ -package net.momirealms.customfishing.hook; +package net.momirealms.customfishing.integration.item; import com.gmail.nossr50.config.treasure.FishingTreasureConfig; import com.gmail.nossr50.datatypes.skills.SubSkillType; @@ -20,14 +20,13 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class McMMOTreasure { - /* - these codes are partly from mcMMO, because of the cancelled event limitation - Plugin has to get the loot in a raw way - */ public static ItemStack getTreasure(Player player){ FishingManager fishingManager = UserManager.getPlayer(player).getFishingManager(); FishingTreasure treasure = getFishingTreasure(player, fishingManager.getLootTier()); @@ -65,97 +64,67 @@ public class McMMOTreasure { private static Map processMagicHunter(@NotNull ItemStack treasureDrop, int tier) { Map enchants = new HashMap<>(); List fishingEnchantments = null; - double diceRoll = Misc.getRandom().nextDouble() * 100; - for (Rarity rarity : Rarity.values()) { - double dropRate = FishingTreasureConfig.getInstance().getEnchantmentDropRate(tier, rarity); - if (diceRoll <= dropRate) { - if (treasureDrop.getType() == Material.ENCHANTED_BOOK) { diceRoll = dropRate + 1; continue; } - fishingEnchantments = FishingTreasureConfig.getInstance().fishingEnchantments.get(rarity); break; } - diceRoll -= dropRate; } - if (fishingEnchantments == null) { return enchants; } - Collections.shuffle(fishingEnchantments, Misc.getRandom()); - int specificChance = 1; - for (EnchantmentTreasure enchantmentTreasure : fishingEnchantments) { Enchantment possibleEnchantment = enchantmentTreasure.getEnchantment(); - if (treasureDrop.getItemMeta().hasConflictingEnchant(possibleEnchantment) || Misc.getRandom().nextInt(specificChance) != 0) { continue; } - enchants.put(possibleEnchantment, enchantmentTreasure.getLevel()); - specificChance *= 2; } - return enchants; } private static @Nullable FishingTreasure getFishingTreasure(Player player, int tier) { double diceRoll = Misc.getRandom().nextDouble() * 100; int luck; - if (player.getInventory().getItemInMainHand().getType() == Material.FISHING_ROD) { luck = player.getInventory().getItemInMainHand().getEnchantmentLevel(Enchantment.LUCK); } else { luck = player.getInventory().getItemInOffHand().getEnchantmentLevel(Enchantment.LUCK); } - diceRoll *= (1.0 - luck * mcMMO.p.getGeneralConfig().getFishingLureModifier() / 100); - FishingTreasure treasure = null; - for (Rarity rarity : Rarity.values()) { - double dropRate = FishingTreasureConfig.getInstance().getItemDropRate(tier, rarity); - if (diceRoll <= dropRate) { - List fishingTreasures = FishingTreasureConfig.getInstance().fishingRewards.get(rarity); - if (fishingTreasures.isEmpty()) { return null; } - treasure = fishingTreasures.get(Misc.getRandom().nextInt(fishingTreasures.size())); break; } - diceRoll -= dropRate; } - if (treasure == null) { return null; } - ItemStack treasureDrop = treasure.getDrop().clone(); short maxDurability = treasureDrop.getType().getMaxDurability(); - if (maxDurability > 0) { treasureDrop.setDurability((short) (Misc.getRandom().nextInt(maxDurability))); } - treasure.setDrop(treasureDrop); - return treasure; } } diff --git a/src/main/java/net/momirealms/customfishing/integration/item/MythicMobsItemHook.java b/src/main/java/net/momirealms/customfishing/integration/item/MythicMobsItemHook.java new file mode 100644 index 00000000..08f9f79f --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/item/MythicMobsItemHook.java @@ -0,0 +1,24 @@ +package net.momirealms.customfishing.integration.item; + +import io.lumine.mythic.bukkit.MythicBukkit; +import io.lumine.mythic.core.items.ItemExecutor; +import net.momirealms.customfishing.integration.ItemInterface; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class MythicMobsItemHook implements ItemInterface { + + private final ItemExecutor itemManager; + + public MythicMobsItemHook() { + this.itemManager = MythicBukkit.inst().getItemManager(); + } + + @Override + @Nullable + public ItemStack build(String material) { + if (!material.startsWith("MythicMobs:")) return null; + material = material.substring(11); + return itemManager.getItemStack(material); + } +} diff --git a/src/main/java/net/momirealms/customfishing/integration/item/OraxenItemHook.java b/src/main/java/net/momirealms/customfishing/integration/item/OraxenItemHook.java new file mode 100644 index 00000000..8bfb0297 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/item/OraxenItemHook.java @@ -0,0 +1,19 @@ +package net.momirealms.customfishing.integration.item; + +import io.th0rgal.oraxen.items.ItemBuilder; +import io.th0rgal.oraxen.items.OraxenItems; +import net.momirealms.customfishing.integration.ItemInterface; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class OraxenItemHook implements ItemInterface { + + @Override + @Nullable + public ItemStack build(String material) { + if (!material.startsWith("Oraxen:")) return null; + material = material.substring(7); + ItemBuilder itemBuilder = OraxenItems.getItemById(material); + return itemBuilder == null ? null : itemBuilder.build(); + } +} diff --git a/src/main/java/net/momirealms/customfishing/integration/mob/MythicMobsMobHook.java b/src/main/java/net/momirealms/customfishing/integration/mob/MythicMobsMobHook.java new file mode 100644 index 00000000..04263f47 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/mob/MythicMobsMobHook.java @@ -0,0 +1,40 @@ +package net.momirealms.customfishing.integration.mob; + +import io.lumine.mythic.api.adapters.AbstractLocation; +import io.lumine.mythic.api.adapters.AbstractVector; +import io.lumine.mythic.api.mobs.MobManager; +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.integration.MobInterface; +import net.momirealms.customfishing.object.MobVector; +import net.momirealms.customfishing.object.loot.Mob; +import org.bukkit.Location; +import org.bukkit.util.Vector; + +import java.util.Optional; + +public class MythicMobsMobHook implements MobInterface { + + private final MobManager mobManager; + + public MythicMobsMobHook() { + this.mobManager = MythicBukkit.inst().getMobManager(); + } + + @Override + public void summon(Location playerLoc, Location summonLoc, Mob mob){ + Optional mythicMob = mobManager.getMythicMob(mob.getMobID()); + if (mythicMob.isPresent()) { + MythicMob theMob = mythicMob.get(); + Position position = Position.of(summonLoc); + AbstractLocation abstractLocation = new AbstractLocation(position); + ActiveMob activeMob = theMob.spawn(abstractLocation, mob.getMobLevel()); + MobVector mobVector = mob.getMobVector(); + Vector vector = playerLoc.subtract(summonLoc).toVector().multiply((mobVector.horizontal()) - 1); + vector = vector.setY((vector.getY() + 0.2) * mobVector.vertical()); + activeMob.getEntity().setVelocity(new AbstractVector(vector.getX(), vector.getY(), vector.getZ())); + } + } +} diff --git a/src/main/java/net/momirealms/customfishing/integration/papi/CompetitionPapi.java b/src/main/java/net/momirealms/customfishing/integration/papi/CompetitionPapi.java new file mode 100644 index 00000000..8ccab6e1 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/papi/CompetitionPapi.java @@ -0,0 +1,34 @@ +package net.momirealms.customfishing.integration.papi; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class CompetitionPapi extends PlaceholderExpansion { + + @Override + public @NotNull String getIdentifier() { + return "competition"; + } + + @Override + public @NotNull String getAuthor() { + return "XiaoMoMi"; + } + + @Override + public @NotNull String getVersion() { + return "1.2"; + } + + @Override + public boolean persist() { + return true; + } + + @Override + public @Nullable String onPlaceholderRequest(Player player, @NotNull String params) { + return super.onPlaceholderRequest(player, params); + } +} diff --git a/src/main/java/net/momirealms/customfishing/integration/papi/PlaceholderManager.java b/src/main/java/net/momirealms/customfishing/integration/papi/PlaceholderManager.java new file mode 100644 index 00000000..74a589d6 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/papi/PlaceholderManager.java @@ -0,0 +1,49 @@ +package net.momirealms.customfishing.integration.papi; + +import me.clip.placeholderapi.PlaceholderAPI; +import net.momirealms.customfishing.Function; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PlaceholderManager extends Function { + + private final Pattern placeholderPattern = Pattern.compile("%([^%]*)%"); + private final CompetitionPapi competitionPapi; + + public PlaceholderManager() { + this.competitionPapi = new CompetitionPapi(); + load(); + } + + public String parse(Player player, String text) { + return PlaceholderAPI.setPlaceholders(player, text); + } + + public String parse(OfflinePlayer offlinePlayer, String text) { + return PlaceholderAPI.setPlaceholders(offlinePlayer, text); + } + + @Override + public void load() { + competitionPapi.register(); + } + + @Override + public void unload() { + if (this.competitionPapi != null) competitionPapi.unregister(); + } + + public List detectPlaceholders(String text){ + if (text == null || !text.contains("%")) return Collections.emptyList(); + List placeholders = new ArrayList<>(); + Matcher matcher = placeholderPattern.matcher(text); + while (matcher.find()) placeholders.add(matcher.group()); + return placeholders; + } +} diff --git a/src/main/java/net/momirealms/customfishing/integration/season/CustomCropsSeasonImpl.java b/src/main/java/net/momirealms/customfishing/integration/season/CustomCropsSeasonImpl.java new file mode 100644 index 00000000..434061fc --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/season/CustomCropsSeasonImpl.java @@ -0,0 +1,4 @@ +package net.momirealms.customfishing.integration.season; + +public class CustomCropsSeasonImpl { +} diff --git a/src/main/java/net/momirealms/customfishing/integration/season/RealisticSeasonsImpl.java b/src/main/java/net/momirealms/customfishing/integration/season/RealisticSeasonsImpl.java new file mode 100644 index 00000000..deee9690 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/season/RealisticSeasonsImpl.java @@ -0,0 +1,13 @@ +package net.momirealms.customfishing.integration.season; + +import me.casperge.realisticseasons.api.SeasonsAPI; +import net.momirealms.customfishing.integration.SeasonInterface; +import org.bukkit.World; + +public class RealisticSeasonsImpl implements SeasonInterface { + + @Override + public String getSeason(World world) { + return SeasonsAPI.getInstance().getSeason(world).toString(); + } +} diff --git a/src/main/java/net/momirealms/customfishing/hook/skill/Aurelium.java b/src/main/java/net/momirealms/customfishing/integration/skill/AureliumsHook.java similarity index 72% rename from src/main/java/net/momirealms/customfishing/hook/skill/Aurelium.java rename to src/main/java/net/momirealms/customfishing/integration/skill/AureliumsHook.java index 3d59a64f..53ca00e7 100644 --- a/src/main/java/net/momirealms/customfishing/hook/skill/Aurelium.java +++ b/src/main/java/net/momirealms/customfishing/integration/skill/AureliumsHook.java @@ -15,17 +15,23 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.hook.skill; +package net.momirealms.customfishing.integration.skill; import com.archyx.aureliumskills.api.AureliumAPI; import com.archyx.aureliumskills.leveler.Leveler; import com.archyx.aureliumskills.skills.Skill; +import net.momirealms.customfishing.integration.SkillInterface; import org.bukkit.entity.Player; -public class Aurelium implements SkillXP{ +public class AureliumsHook implements SkillInterface { - private static final Leveler leveler = AureliumAPI.getPlugin().getLeveler(); - private static final Skill skill = AureliumAPI.getPlugin().getSkillRegistry().getSkill("fishing"); + private final Leveler leveler; + private final Skill skill; + + public AureliumsHook() { + leveler = AureliumAPI.getPlugin().getLeveler(); + skill = AureliumAPI.getPlugin().getSkillRegistry().getSkill("fishing"); + } @Override public void addXp(Player player, double amount) { diff --git a/src/main/java/net/momirealms/customfishing/hook/skill/MMOCore.java b/src/main/java/net/momirealms/customfishing/integration/skill/EcoSkillsHook.java similarity index 61% rename from src/main/java/net/momirealms/customfishing/hook/skill/MMOCore.java rename to src/main/java/net/momirealms/customfishing/integration/skill/EcoSkillsHook.java index bd3df5a5..e7d363d7 100644 --- a/src/main/java/net/momirealms/customfishing/hook/skill/MMOCore.java +++ b/src/main/java/net/momirealms/customfishing/integration/skill/EcoSkillsHook.java @@ -15,22 +15,28 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.hook.skill; +package net.momirealms.customfishing.integration.skill; -import net.Indyuce.mmocore.experience.EXPSource; -import net.Indyuce.mmocore.experience.Profession; +import com.willfp.ecoskills.api.EcoSkillsAPI; +import com.willfp.ecoskills.skills.Skills; +import net.momirealms.customfishing.integration.SkillInterface; import org.bukkit.entity.Player; -public class MMOCore implements SkillXP{ +public class EcoSkillsHook implements SkillInterface { + + public EcoSkillsAPI ecoSkillsAPI; + + public EcoSkillsHook() { + ecoSkillsAPI = EcoSkillsAPI.getInstance(); + } @Override public void addXp(Player player, double amount) { - Profession profession = net.Indyuce.mmocore.MMOCore.plugin.professionManager.get("fishing"); - profession.giveExperience(net.Indyuce.mmocore.MMOCore.plugin.dataProvider.getDataManager().get(player), amount, null , EXPSource.OTHER); + ecoSkillsAPI.giveSkillExperience(player, Skills.FARMING, amount); } @Override public int getLevel(Player player) { - return net.Indyuce.mmocore.MMOCore.plugin.dataProvider.getDataManager().get(player).getLevel(); + return ecoSkillsAPI.getSkillLevel(player, Skills.FISHING); } } diff --git a/src/main/java/net/momirealms/customfishing/integration/skill/JobsRebornHook.java b/src/main/java/net/momirealms/customfishing/integration/skill/JobsRebornHook.java new file mode 100644 index 00000000..dd6c3fb3 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/skill/JobsRebornHook.java @@ -0,0 +1,62 @@ +/* + * 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.skill; + +import com.gamingmesh.jobs.Jobs; +import com.gamingmesh.jobs.PlayerManager; +import com.gamingmesh.jobs.container.Job; +import com.gamingmesh.jobs.container.JobProgression; +import com.gamingmesh.jobs.container.JobsPlayer; +import net.momirealms.customfishing.integration.SkillInterface; +import org.bukkit.entity.Player; + +import java.util.List; + +public class JobsRebornHook implements SkillInterface { + + private final PlayerManager playerManager; + + public JobsRebornHook() { + this.playerManager = Jobs.getPlayerManager(); + } + + @Override + public void addXp(Player player, double amount) { + JobsPlayer jobsPlayer = playerManager.getJobsPlayer(player); + if (jobsPlayer != null) { + List jobs = jobsPlayer.getJobProgression(); + Job job = Jobs.getJob("Fisherman"); + for (JobProgression progression : jobs) + if (progression.getJob().equals(job)) + progression.addExperience(amount); + } + } + + @Override + public int getLevel(Player player) { + JobsPlayer jobsPlayer = Jobs.getPlayerManager().getJobsPlayer(player); + if (jobsPlayer != null) { + List jobs = jobsPlayer.getJobProgression(); + Job job = Jobs.getJob("Fisherman"); + for (JobProgression progression : jobs) + if (progression.getJob().equals(job)) + return progression.getLevel(); + } + return 0; + } +} diff --git a/src/main/java/net/momirealms/customfishing/integration/skill/MMOCoreHook.java b/src/main/java/net/momirealms/customfishing/integration/skill/MMOCoreHook.java new file mode 100644 index 00000000..17031e74 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/integration/skill/MMOCoreHook.java @@ -0,0 +1,46 @@ +/* + * 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.skill; + +import net.Indyuce.mmocore.MMOCore; +import net.Indyuce.mmocore.experience.EXPSource; +import net.Indyuce.mmocore.experience.Profession; +import net.Indyuce.mmocore.manager.data.PlayerDataManager; +import net.momirealms.customfishing.integration.SkillInterface; +import org.bukkit.entity.Player; + +public class MMOCoreHook implements SkillInterface { + + private final Profession profession; + private final PlayerDataManager playerDataManager; + + public MMOCoreHook() { + profession = MMOCore.plugin.professionManager.get("fishing"); + playerDataManager = MMOCore.plugin.dataProvider.getDataManager(); + } + + @Override + public void addXp(Player player, double amount) { + profession.giveExperience(playerDataManager.get(player), amount, null ,EXPSource.OTHER); + } + + @Override + public int getLevel(Player player) { + return playerDataManager.get(player).getLevel(); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/hook/skill/mcMMO.java b/src/main/java/net/momirealms/customfishing/integration/skill/mcMMOHook.java similarity index 86% rename from src/main/java/net/momirealms/customfishing/hook/skill/mcMMO.java rename to src/main/java/net/momirealms/customfishing/integration/skill/mcMMOHook.java index f6a72063..457407eb 100644 --- a/src/main/java/net/momirealms/customfishing/hook/skill/mcMMO.java +++ b/src/main/java/net/momirealms/customfishing/integration/skill/mcMMOHook.java @@ -15,13 +15,14 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.hook.skill; +package net.momirealms.customfishing.integration.skill; import com.gmail.nossr50.api.ExperienceAPI; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import net.momirealms.customfishing.integration.SkillInterface; import org.bukkit.entity.Player; -public class mcMMO implements SkillXP{ +public class mcMMOHook implements SkillInterface { @Override public void addXp(Player player, double amount) { @@ -32,4 +33,4 @@ public class mcMMO implements SkillXP{ public int getLevel(Player player) { return ExperienceAPI.getLevel(player, PrimarySkillType.FISHING); } -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/listener/FishListener.java b/src/main/java/net/momirealms/customfishing/listener/FishListener.java deleted file mode 100644 index 154084e2..00000000 --- a/src/main/java/net/momirealms/customfishing/listener/FishListener.java +++ /dev/null @@ -1,1056 +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.listener; - -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTItem; -import net.kyori.adventure.key.Key; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.momirealms.customfishing.competition.CompetitionSchedule; -import net.momirealms.customfishing.competition.bossbar.BossBarManager; -import net.momirealms.customfishing.hook.*; -import net.momirealms.customfishing.object.*; -import net.momirealms.customfishing.object.Difficulty; -import net.momirealms.customfishing.object.action.ActionB; -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.utils.AdventureUtil; -import net.momirealms.customfishing.ConfigReader; -import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.requirements.FishingCondition; -import net.momirealms.customfishing.requirements.Requirement; -import net.momirealms.customfishing.titlebar.Timer; -import net.momirealms.customfishing.utils.ItemStackUtil; -import net.momirealms.customfishing.utils.ItemUtil; -import org.apache.commons.lang.StringUtils; -import org.bukkit.*; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.*; -import org.bukkit.entity.Item; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerFishEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -public class FishListener implements Listener { - - private final HashMap coolDown = new HashMap<>(); - private final HashMap nextLoot = new HashMap<>(); - private final HashMap modifiers = new HashMap<>(); - private final HashMap hooks = new HashMap<>(); - private final HashMap vanilla = new HashMap<>(); - public static ConcurrentHashMap fishingPlayers = new ConcurrentHashMap<>(); - - @EventHandler(priority = EventPriority.HIGHEST) - public void onFishHighest(PlayerFishEvent event){ - if (ConfigReader.Config.priority.equals("HIGHEST")){ - onFish(event); - } - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onFishNormal(PlayerFishEvent event){ - if (ConfigReader.Config.priority.equals("NORMAL")){ - onFish(event); - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onFishLowest(PlayerFishEvent event){ - if (ConfigReader.Config.priority.equals("LOWEST")){ - onFish(event); - } - } - - public void onFish(PlayerFishEvent event){ - - if (event.isCancelled()) return; - - PlayerFishEvent.State state = event.getState(); - Player player = event.getPlayer(); - - if (ConfigReader.Config.hasWhitelist){ - boolean isWhite = false; - for (World world : ConfigReader.Config.whitelistWorlds){ - if (world.equals(player.getWorld())){ - isWhite = true; - break; - } - } - if (!isWhite){ - return; - } - } - - switch (state){ - - case FISHING ->{ - - long time = System.currentTimeMillis(); - if (time - (coolDown.getOrDefault(player, time - 2000)) < 2000) { - return; - } - coolDown.put(player, time); - - hooks.put(player, event.getHook()); - - Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.instance, ()->{ - - PlayerInventory inventory = player.getInventory(); - - boolean noSpecialRod = true; - boolean noRod = true; - double timeModifier = 1; - double doubleLoot = 0; - double scoreModifier = 1; - int difficultyModifier = 0; - - HashMap pm = new HashMap<>(); - HashMap mq = new HashMap<>(); - - ItemStack mainHandItem = inventory.getItemInMainHand(); - - Material material1 = mainHandItem.getType(); - if (material1 != Material.AIR){ - if (material1 == Material.FISHING_ROD) { - noRod = false; - Map enchantments = mainHandItem.getEnchantments(); - Object[] enchantmentsArray = enchantments.keySet().toArray(); - for (Object o : enchantmentsArray) { - Enchantment enchantment = (Enchantment) o; - HashMap enchantMap = ConfigReader.ENCHANTS.get(enchantment.getKey().toString()); - if (enchantMap != null) { - Bonus enchantBonus = enchantMap.get(enchantments.get(enchantment)); - if (enchantBonus != null) { - HashMap weightPM = enchantBonus.getWeightPM(); - if (weightPM != null){ - Object[] bonus = weightPM.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - pm.put(group, Optional.ofNullable(pm.get(group)).orElse(0) + weightPM.get(group)); - } - } - HashMap weightMQ = enchantBonus.getWeightMQ(); - if (weightMQ != null){ - Object[] bonus = weightMQ.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - mq.put(group, Optional.ofNullable(mq.get(group)).orElse(1d) + weightMQ.get(group)); - } - } - if (enchantBonus.getTime() != 0) timeModifier *= enchantBonus.getTime(); - if (enchantBonus.getDoubleLoot() != 0) doubleLoot += enchantBonus.getDoubleLoot(); - if (enchantBonus.getDifficulty() != 0) difficultyModifier += enchantBonus.getDifficulty(); - if (enchantBonus.getScore() != 0) scoreModifier *= enchantBonus.getScore(); - } - } - } - } - NBTItem nbtItem = new NBTItem(inventory.getItemInMainHand()); - NBTCompound nbtCompound = nbtItem.getCompound("CustomFishing"); - if (nbtCompound != null){ - if (nbtCompound.getString("type").equals("rod")) { - String key = nbtCompound.getString("id"); - Bonus rod = ConfigReader.ROD.get(key); - if (rod != null){ - HashMap weightPM = rod.getWeightPM(); - if (weightPM != null){ - Object[] bonus = weightPM.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - pm.put(group, Optional.ofNullable(pm.get(group)).orElse(0) + weightPM.get(group)); - } - } - HashMap weightMQ = rod.getWeightMQ(); - if (weightMQ != null){ - Object[] bonus = weightMQ.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - mq.put(group, Optional.ofNullable(mq.get(group)).orElse(1d) + weightMQ.get(group)); - } - } - if (rod.getTime() != 0) timeModifier *= rod.getTime(); - if (rod.getDoubleLoot() != 0) doubleLoot += rod.getDoubleLoot(); - if (rod.getDifficulty() != 0) difficultyModifier += rod.getDifficulty(); - if (rod.getScore() != 0) scoreModifier *= rod.getScore(); - noSpecialRod = false; - } - } - else if (nbtCompound.getString("type").equals("bait")){ - String key = nbtCompound.getString("id"); - Bonus bait = ConfigReader.BAIT.get(key); - if (bait != null){ - HashMap weightPM = bait.getWeightPM(); - if (weightPM != null){ - Object[] bonus = weightPM.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - pm.put(group, Optional.ofNullable(pm.get(group)).orElse(0) + weightPM.get(group)); - } - } - HashMap weightMQ = bait.getWeightMQ(); - if (weightMQ != null){ - Object[] bonus = weightMQ.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - mq.put(group, Optional.ofNullable(mq.get(group)).orElse(1d) + weightMQ.get(group)); - } - } - if (bait.getTime() != 0) timeModifier *= bait.getTime(); - if (bait.getDoubleLoot() != 0) doubleLoot += bait.getDoubleLoot(); - if (bait.getDifficulty() != 0) difficultyModifier += bait.getDifficulty(); - if (bait.getScore() != 0) scoreModifier *= bait.getScore(); - mainHandItem.setAmount(mainHandItem.getAmount() - 1); - } - } - } - } - - ItemStack offHandItem = inventory.getItemInOffHand(); - Material material2 = offHandItem.getType(); - if (material2 != Material.AIR){ - if (noRod && material2 == Material.FISHING_ROD) { - Map enchantments = mainHandItem.getEnchantments(); - Object[] enchantmentsArray = enchantments.keySet().toArray(); - for (Object o : enchantmentsArray) { - Enchantment enchantment = (Enchantment) o; - HashMap enchantMap = ConfigReader.ENCHANTS.get(enchantment.getKey().toString()); - if (enchantMap != null) { - Bonus enchantBonus = enchantMap.get(enchantments.get(enchantment)); - if (enchantBonus != null) { - HashMap weightPM = enchantBonus.getWeightPM(); - if (weightPM != null){ - Object[] bonus = weightPM.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - pm.put(group, Optional.ofNullable(pm.get(group)).orElse(0) + weightPM.get(group)); - } - } - HashMap weightMQ = enchantBonus.getWeightMQ(); - if (weightMQ != null){ - Object[] bonus = weightMQ.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - mq.put(group, Optional.ofNullable(mq.get(group)).orElse(1d) + weightMQ.get(group)); - } - } - if (enchantBonus.getTime() != 0) timeModifier *= enchantBonus.getTime(); - if (enchantBonus.getDoubleLoot() != 0) doubleLoot += enchantBonus.getDoubleLoot(); - if (enchantBonus.getDifficulty() != 0) difficultyModifier += enchantBonus.getDifficulty(); - if (enchantBonus.getScore() != 0) scoreModifier *= enchantBonus.getScore(); - } - } - } - } - NBTItem offHand = new NBTItem(inventory.getItemInOffHand()); - NBTCompound offHandCompound = offHand.getCompound("CustomFishing"); - if (offHandCompound != null){ - if (offHandCompound.getString("type").equals("bait")) { - String key = offHandCompound.getString("id"); - Bonus bait = ConfigReader.BAIT.get(key); - if (bait != null){ - HashMap weightPM = bait.getWeightPM(); - if (weightPM != null){ - Object[] bonus = weightPM.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - pm.put(group, Optional.ofNullable(pm.get(group)).orElse(0) + weightPM.get(group)); - } - } - HashMap weightMQ = bait.getWeightMQ(); - if (weightMQ != null){ - Object[] bonus = weightMQ.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - mq.put(group, Optional.ofNullable(mq.get(group)).orElse(1d) + weightMQ.get(group)); - } - } - if (bait.getTime() != 0) timeModifier *= bait.getTime(); - if (bait.getDoubleLoot() != 0) doubleLoot += bait.getDoubleLoot(); - if (bait.getDifficulty() != 0) difficultyModifier += bait.getDifficulty(); - if (bait.getScore() != 0) scoreModifier *= bait.getScore(); - offHandItem.setAmount(offHandItem.getAmount() - 1); - } - } - else if (noSpecialRod && offHandCompound.getString("type").equals("rod")){ - String key = offHandCompound.getString("id"); - Bonus rod = ConfigReader.ROD.get(key); - if (rod != null){ - HashMap weightPM = rod.getWeightPM(); - if (weightPM != null){ - Object[] bonus = weightPM.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - pm.put(group, Optional.ofNullable(pm.get(group)).orElse(0) + weightPM.get(group)); - } - } - HashMap weightMQ = rod.getWeightMQ(); - if (weightMQ != null){ - Object[] bonus = weightMQ.keySet().toArray(); - for (Object value : bonus) { - String group = (String) value; - mq.put(group, Optional.ofNullable(mq.get(group)).orElse(1d) + weightMQ.get(group)); - } - } - if (rod.getTime() != 0) timeModifier *= rod.getTime(); - if (rod.getDoubleLoot() != 0) doubleLoot += rod.getDoubleLoot(); - if (rod.getDifficulty() != 0) difficultyModifier += rod.getDifficulty(); - if (rod.getScore() != 0) scoreModifier *= rod.getScore(); - noSpecialRod = false; - } - } - } - } - - FishHook hook = event.getHook(); - hook.setMaxWaitTime((int) (timeModifier * hook.getMaxWaitTime())); - hook.setMinWaitTime((int) (timeModifier * hook.getMinWaitTime())); - - List possibleLoots = getPossibleLootList(new FishingCondition(hook.getLocation(), player), false); - List availableLoots = new ArrayList<>(); - - Modifier modifier = new Modifier(); - modifier.setDifficulty(difficultyModifier); - modifier.setScore(scoreModifier); - modifier.setWillDouble(doubleLoot > Math.random()); - modifiers.put(player, modifier); - - if (possibleLoots.size() == 0){ - nextLoot.put(player, null); - return; - } - - if (ConfigReader.Config.needSpecialRod && noSpecialRod){ - if (!ConfigReader.Config.vanillaLoot) - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.noRod); - nextLoot.put(player, null); - } - - if (ConfigReader.Config.needRodFishing && noSpecialRod){ - nextLoot.put(player, new Loot("none")); - } - - if ((ConfigReader.Config.needSpecialRod || ConfigReader.Config.needRodFishing) && noSpecialRod) return; - - double[] weights = new double[possibleLoots.size()]; - int index = 0; - for (Loot loot : possibleLoots){ - double weight = loot.getWeight(); - String group = loot.getGroup(); - if (group != null){ - if (pm.get(group) != null){ - weight += pm.get(group); - } - if (mq.get(group) != null){ - weight *= mq.get(group); - } - } - if (weight <= 0) continue; - availableLoots.add(loot); - weights[index++] = weight; - } - - double total = Arrays.stream(weights).sum(); - double[] weightRatios = new double[index]; - for (int i = 0; i < index; i++){ - weightRatios[i] = weights[i]/total; - } - - double[] weightRange = new double[index]; - double startPos = 0; - for (int i = 0; i < index; i++) { - weightRange[i] = startPos + weightRatios[i]; - startPos += weightRatios[i]; - } - - double random = Math.random(); - int pos = Arrays.binarySearch(weightRange, random); - - if (pos < 0) { - pos = -pos - 1; - } else { - nextLoot.put(player, availableLoots.get(pos)); - return; - } - if (pos < weightRange.length && random < weightRange[pos]) { - nextLoot.put(player, availableLoots.get(pos)); - return; - } - nextLoot.put(player, null); - }); - } - case CAUGHT_FISH -> { - - if (ConfigReader.Config.needRodFishing && nextLoot.get(player) != null && nextLoot.get(player).getKey().equals("none")){ - return; - } - //是否需要两次拉杆 - if (ConfigReader.Config.doubleRealIn) { - - FishingPlayer fishingPlayer = fishingPlayers.remove(player); - - Entity entity = event.getCaught(); - - if (fishingPlayer == null){ - - if (entity instanceof Item item){ - //是否有原版战利品 - if (ConfigReader.Config.vanillaLoot) { - //不是原版战利品 - if (ConfigReader.Config.vanillaRatio < Math.random()) { - event.setCancelled(true); - if (nextLoot.get(player) != null){ - vanilla.remove(player); - }else { - vanilla.put(player, new VanillaLoot(item.getItemStack(), event.getExpToDrop())); - } - showPlayerBar(player); - } - //是原版战利品 - else { - //需要走力度条流程 - if (ConfigReader.Config.showBar){ - event.setCancelled(true); - vanilla.put(player, new VanillaLoot(item.getItemStack(), event.getExpToDrop())); - showPlayerBar(player); - } - } - } - //如果不许有原版战利品则清除 - else { - if (nextLoot.get(player) == null){ - item.remove(); - event.setExpToDrop(0); - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.noLoot); - } - else { - event.setCancelled(true); - showPlayerBar(player); - } - } - } - } - else { - - if (entity instanceof Item item){ - item.remove(); - event.setExpToDrop(0); - } - Loot loot = nextLoot.remove(player); - - VanillaLoot vanillaLoot = vanilla.remove(player); - Timer timer = fishingPlayer.getTimer(); - Layout layout = ConfigReader.LAYOUT.get(timer.getLayout()); - int last = (timer.getTimerTask().getProgress())/layout.getRange(); - - player.removePotionEffect(PotionEffectType.SLOW); - if (ConfigReader.Config.needOpenWater && !event.getHook().isInOpenWater()){ - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.notOpenWater); - return; - } - - if (Math.random() < layout.getSuccessRate()[last]){ - if (ConfigReader.Config.loseDurability) - loseDurability(player); - Location location = event.getHook().getLocation(); - if (loot instanceof Mob mob){ - summonMob(player, loot, location, mob); - } - else if (loot instanceof DroppedItem droppedItem){ - if (vanillaLoot != null) { - dropVanillaLoot(player, vanillaLoot, location); - } - else if (ConfigReader.Config.mcMMOLoot && Math.random() < ConfigReader.Config.mcMMOLootChance){ - if(dropMcMMOLoot(player, location)){ - dropMyLoot(player, loot, location, droppedItem); - } - } - else { - dropMyLoot(player, loot, location, droppedItem); - } - }else if (loot == null && vanillaLoot != null){ - dropVanillaLoot(player, vanillaLoot, location); - } - } - else { - fail(player, loot, vanillaLoot != null); - } - } - } - //不需要两次拉杆 - //除非设置否则肯定不会有原版掉落物 - else { - - Entity entity = event.getCaught(); - if (entity instanceof Item item){ - - //如果玩家正在钓鱼 - //那么拉杆的时候可能也会遇到上钩点,进行正常收杆判断 - FishingPlayer fishingPlayer = fishingPlayers.remove(player); - - if (fishingPlayer != null){ - - item.remove(); - event.setExpToDrop(0); - - Loot loot = nextLoot.get(player); - Timer timer = fishingPlayer.getTimer(); - Layout layout = ConfigReader.LAYOUT.get(timer.getLayout()); - int last = (timer.getTimerTask().getProgress())/layout.getRange(); - player.removePotionEffect(PotionEffectType.SLOW); - - if (ConfigReader.Config.needOpenWater && !event.getHook().isInOpenWater()){ - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.notOpenWater); - return; - } - - //捕鱼成功 - if (Math.random() < layout.getSuccessRate()[last]) { - Location location = event.getHook().getLocation(); - if (loot instanceof Mob mob){ - MythicMobsUtil.summonMM(player.getLocation(), location, mob); - } - else if (loot instanceof DroppedItem droppedItem){ - if (ConfigReader.Config.mcMMOLoot && ConfigReader.Config.mcMMOLootChance > Math.random()){ - if (dropMcMMOLoot(player, location)){ - dropLoot(player, location, droppedItem); - } - }else { - dropLoot(player, location, droppedItem); - } - } - for (ActionB action : loot.getSuccessActions()) - action.doOn(player); - if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()){ - float score = (float) (loot.getScore() * modifiers.get(player).getScore()); - CompetitionSchedule.competition.refreshRanking(player.getName(), score); - BossBarManager.joinCompetition(player); - } - AdventureUtil.playerTitle( - player, - ConfigReader.Title.success_title.get((int) (ConfigReader.Title.success_title.size()*Math.random())) - .replace("{loot}",loot.getNick()) - .replace("{player}", player.getName()), - ConfigReader.Title.success_subtitle.get((int) (ConfigReader.Title.success_subtitle.size()*Math.random())) - .replace("{loot}",loot.getNick()) - .replace("{player}", player.getName()), - ConfigReader.Title.success_in, - ConfigReader.Title.success_stay, - ConfigReader.Title.success_out - ); - if (ConfigReader.Config.loseDurability) - loseDurability(player); - } - //捕鱼失败 - else { - fail(player, loot, false); - } - } - else { - if (!ConfigReader.Config.vanillaLoot) { - item.remove(); - event.setExpToDrop(0); - } - } - } - } - } - case CAUGHT_ENTITY -> { - //理论是不存在实体的 - //说明在钓鱼的时候可能鱼钩勾上了鱿鱼之类的生物 - //直接按照失败处理 - if (fishingPlayers.remove(player) != null && event.getCaught() != null){ - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.hookOther); - } - } - case REEL_IN -> { - - FishingPlayer fishingPlayer = fishingPlayers.remove(player); - //首先得是钓鱼中的玩家 - if (fishingPlayer != null){ - - Loot loot = nextLoot.remove(player); - VanillaLoot vanillaLoot = vanilla.remove(player); - Timer timer = fishingPlayer.getTimer(); - Layout layout = ConfigReader.LAYOUT.get(timer.getLayout()); - int last = (timer.getTimerTask().getProgress())/layout.getRange(); - - player.removePotionEffect(PotionEffectType.SLOW); - if (ConfigReader.Config.needOpenWater && !event.getHook().isInOpenWater()){ - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.notOpenWater); - return; - } - - if (Math.random() < layout.getSuccessRate()[last]){ - //这里是普通收杆,需要减少耐久度 - if (ConfigReader.Config.loseDurability) - loseDurability(player); - Location location = event.getHook().getLocation(); - if (loot instanceof Mob mob){ - summonMob(player, loot, location, mob); - } - else if (loot instanceof DroppedItem droppedItem){ - if (vanillaLoot != null) { - dropVanillaLoot(player, vanillaLoot, location); - } - else if (ConfigReader.Config.mcMMOLoot && Math.random() < ConfigReader.Config.mcMMOLootChance){ - if (dropMcMMOLoot(player, location)){ - dropMyLoot(player, loot, location, droppedItem); - } - } - else { - dropMyLoot(player, loot, location, droppedItem); - } - }else if (loot == null && vanillaLoot != null){ - dropVanillaLoot(player, vanillaLoot, location); - } - } - else{ - fail(player, loot, vanillaLoot != null); - } - } - else { - //钓上来的是物品 - if (event.getCaught() instanceof Item item) { - //是否允许原版掉落物 - if (ConfigReader.Config.vanillaLoot) { - if (ConfigReader.Config.showBar){ - item.remove(); - event.setExpToDrop(0); - //event.setCancelled(true); - vanilla.put(player, new VanillaLoot(item.getItemStack(), event.getExpToDrop())); - showPlayerBar(player); - } -// else { -// //啥也不干 -// } - } - //不允许原版掉落物 - else { - item.remove(); - event.setExpToDrop(0); - //event.setCancelled(true); - } - } - } - } - case BITE -> { - - if (ConfigReader.Config.doubleRealIn) return; - - if (fishingPlayers.get(player) != null) return; - - Loot loot = nextLoot.get(player); - - if (loot == null) return; - - if (ConfigReader.Config.needRodFishing && loot.getKey().equals("none")){ - return; - } - - String layout; - if (loot.getLayout() != null){ - layout = loot.getLayout().get((int) (loot.getLayout().size() * Math.random())); - }else { - Object[] values = ConfigReader.LAYOUT.keySet().toArray(); - layout = (String) values[new Random().nextInt(values.length)]; - } - - int difficulty = loot.getDifficulty().getSpeed(); - difficulty += Objects.requireNonNullElse(modifiers.get(player).getDifficulty(), 0);; - if (difficulty < 1){ - difficulty = 1; - } - - Difficulty difficult = new Difficulty(loot.getDifficulty().getTimer(), difficulty); - fishingPlayers.put(player, - new FishingPlayer(System.currentTimeMillis() + loot.getTime(), - new Timer(player, difficult, layout) - ) - ); - - for (ActionB action : loot.getHookActions()){ - action.doOn(player); - } - - player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, loot.getTime()/50,3)); - } - } - } - - private void dropMyLoot(Player player, Loot loot, Location location, DroppedItem droppedItem) { - dropLoot(player, location, droppedItem); - if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()) { - float score = (float) (loot.getScore() * modifiers.get(player).getScore()); - CompetitionSchedule.competition.refreshRanking(player.getName(), score); - BossBarManager.joinCompetition(player); - } - for (ActionB action : loot.getSuccessActions()) - action.doOn(player); - AdventureUtil.playerTitle( - player, - ConfigReader.Title.success_title.get((int) (ConfigReader.Title.success_title.size()*Math.random())) - .replace("{loot}",loot.getNick()) - .replace("{player}", player.getName()), - ConfigReader.Title.success_subtitle.get((int) (ConfigReader.Title.success_subtitle.size()*Math.random())) - .replace("{loot}",loot.getNick()) - .replace("{player}", player.getName()), - ConfigReader.Title.success_in, - ConfigReader.Title.success_stay, - ConfigReader.Title.success_out - ); - } - - private void summonMob(Player player, Loot loot, Location location, Mob mob) { - MythicMobsUtil.summonMM(player.getLocation(), location, mob); - for (ActionB action : loot.getSuccessActions()) - action.doOn(player); - if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()) { - float score = (float) (loot.getScore() * modifiers.get(player).getScore()); - CompetitionSchedule.competition.refreshRanking(player.getName(), score); - BossBarManager.joinCompetition(player); - } - AdventureUtil.playerTitle( - player, - ConfigReader.Title.success_title.get((int) (ConfigReader.Title.success_title.size()*Math.random())) - .replace("{loot}",loot.getNick()) - .replace("{player}", player.getName()), - ConfigReader.Title.success_subtitle.get((int) (ConfigReader.Title.success_subtitle.size()*Math.random())) - .replace("{loot}",loot.getNick()) - .replace("{player}", player.getName()), - ConfigReader.Title.success_in, - ConfigReader.Title.success_stay, - ConfigReader.Title.success_out - ); - } - - private void dropVanillaLoot(Player player, VanillaLoot vanillaLoot, Location location) { - - ItemStack itemStack; - itemStack = vanillaLoot.getItemStack(); - - if (ConfigReader.Config.mcMMOLoot && ConfigReader.Config.mcMMOLootChance > Math.random()){ - ItemStack itemStack1 = McMMOTreasure.getTreasure(player); - if (itemStack1 != null){ - itemStack = itemStack1; - } - } - if (ConfigReader.Config.isSpigot) player.giveExp(vanillaLoot.getXp()); - else player.giveExp(vanillaLoot.getXp(), true); - AdventureUtil.playerSound(player, net.kyori.adventure.sound.Sound.Source.PLAYER, Key.key("minecraft:entity.experience_orb.pickup")); - Entity item = location.getWorld().dropItem(location, itemStack); - Vector vector = player.getLocation().subtract(location).toVector().multiply(0.1); - vector = vector.setY((vector.getY()+0.2)*1.2); - item.setVelocity(vector); - if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()) { - CompetitionSchedule.competition.refreshRanking(player.getName(), 0); - BossBarManager.joinCompetition(player); - } - if (modifiers.get(player).isWillDouble()) { - Entity item2 = location.getWorld().dropItem(location, itemStack); - item2.setVelocity(vector); - } - String title = ConfigReader.Title.success_title.get((int) (ConfigReader.Title.success_title.size()*Math.random())); - Component titleComponent = getTitleComponent(itemStack, title); - String subTitle = ConfigReader.Title.success_subtitle.get((int) (ConfigReader.Title.success_subtitle.size()*Math.random())); - Component subtitleComponent = getTitleComponent(itemStack, subTitle); - - AdventureUtil.playerTitle( - player, - titleComponent, - subtitleComponent, - ConfigReader.Title.success_in, - ConfigReader.Title.success_stay, - ConfigReader.Title.success_out - ); - } - - /* - 返回是否为mcmmo物品为空值 - */ - private boolean dropMcMMOLoot(Player player, Location location) { - ItemStack itemStack = McMMOTreasure.getTreasure(player); - - if (itemStack != null) { - if (ConfigReader.Config.preventPick) - ItemStackUtil.addOwner(itemStack, player.getName()); - Entity item = location.getWorld().dropItem(location, itemStack); - Vector vector = player.getLocation().subtract(location).toVector().multiply(0.1); - vector = vector.setY((vector.getY()+0.2)*1.2); - item.setVelocity(vector); - if (modifiers.get(player).isWillDouble()){ - Entity item2 = location.getWorld().dropItem(location, itemStack); - item2.setVelocity(vector); - } - } - else { - return true; - } - - if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()) { - CompetitionSchedule.competition.refreshRanking(player.getName(), 0); - BossBarManager.joinCompetition(player); - } - - String title = ConfigReader.Title.success_title.get((int) (ConfigReader.Title.success_title.size()*Math.random())); - Component titleComponent = getTitleComponent(itemStack, title); - String subTitle = ConfigReader.Title.success_subtitle.get((int) (ConfigReader.Title.success_subtitle.size()*Math.random())); - Component subtitleComponent = getTitleComponent(itemStack, subTitle); - - AdventureUtil.playerTitle( - player, - titleComponent, - subtitleComponent, - ConfigReader.Title.success_in, - ConfigReader.Title.success_stay, - ConfigReader.Title.success_out - ); - return false; - } - - @NotNull - private Component getTitleComponent(ItemStack itemStack, String text) { - Component subtitleComponent; - if (text.contains("{loot}")){ - text = text.replace("{loot}","|"); - if (text.startsWith("|")){ - subtitleComponent = ItemUtil.getDisplayName(itemStack).append(MiniMessage.miniMessage().deserialize(text.substring(1))); - } - else if (text.endsWith("|")){ - subtitleComponent = MiniMessage.miniMessage().deserialize(text.substring(0,text.length()-1)).append(ItemUtil.getDisplayName(itemStack)); - } - else { - String[] titleSplit = StringUtils.split(text, "|"); - subtitleComponent = MiniMessage.miniMessage().deserialize(titleSplit[0]).append(ItemUtil.getDisplayName(itemStack)).append(MiniMessage.miniMessage().deserialize(titleSplit[1])); - } - } - else { - subtitleComponent = MiniMessage.miniMessage().deserialize(text); - } - return subtitleComponent; - } - - private void dropLoot(Player player, Location location, DroppedItem droppedItem) { - ItemStack itemStack; - switch (droppedItem.getType()){ - case "ia" -> itemStack = ItemsAdderItem.getItemStack(droppedItem.getId()).clone(); - case "oraxen" -> itemStack = OraxenItem.getItemStack(droppedItem.getId()).clone(); - case "mm" -> itemStack = MythicItems.getItemStack(droppedItem.getId()).clone(); - case "mmoitems" -> itemStack = MMOItemsHook.getItemStack(droppedItem.getId()).clone(); - default -> itemStack = ConfigReader.LootItem.get(droppedItem.getKey()).clone(); - } - - if (itemStack.getType() != Material.AIR) { - if (droppedItem.getRandomEnchants() != null) - ItemStackUtil.addRandomEnchants(itemStack, droppedItem.getRandomEnchants()); - if (droppedItem.isRandomDurability()) - ItemStackUtil.addRandomDamage(itemStack); - if (ConfigReader.Config.preventPick) - ItemStackUtil.addOwner(itemStack, player.getName()); - Entity item = location.getWorld().dropItem(location, itemStack); - Vector vector = player.getLocation().subtract(location).toVector().multiply(0.1); - vector = vector.setY((vector.getY()+0.2)*1.2); - item.setVelocity(vector); - if (modifiers.get(player).isWillDouble()){ - Entity item2 = location.getWorld().dropItem(location, itemStack); - item2.setVelocity(vector); - } - } - } - - private void loseDurability(Player player) { - if (player.getGameMode() == GameMode.CREATIVE) return; - PlayerInventory inventory = player.getInventory(); - ItemStack mainHand = inventory.getItemInMainHand(); - if (mainHand.getType() == Material.FISHING_ROD){ - Damageable damageable = (Damageable) mainHand.getItemMeta(); - if (damageable.isUnbreakable()) return; - Enchantment enchantment = Enchantment.DURABILITY; - if (Math.random() < (1/(double) (damageable.getEnchantLevel(enchantment) + 1))){ - damageable.setDamage(damageable.getDamage() + 1); - Bukkit.getScheduler().runTaskLater(CustomFishing.instance, ()->{ - mainHand.setItemMeta(damageable); - },1); - } - } - else { - ItemStack offHand = inventory.getItemInOffHand(); - if (offHand.getType() == Material.FISHING_ROD){ - Damageable damageable = (Damageable) offHand.getItemMeta(); - if (damageable.isUnbreakable()) return; - Enchantment enchantment = Enchantment.DURABILITY; - if (Math.random() < (1/(double) (damageable.getEnchantLevel(enchantment) + 1))){ - damageable.setDamage(damageable.getDamage() + 1); - Bukkit.getScheduler().runTaskLater(CustomFishing.instance, ()->{ - offHand.setItemMeta(damageable); - },1); - } - } - } - } - - private void fail(Player player, Loot loot, boolean isVanilla) { - fishingPlayers.remove(player); - if (!isVanilla && loot != null){ - for (ActionB action : loot.getFailureActions()) - action.doOn(player); - } - AdventureUtil.playerTitle( - player, - ConfigReader.Title.failure_title.get((int) (ConfigReader.Title.failure_title.size()*Math.random())), - ConfigReader.Title.failure_subtitle.get((int) (ConfigReader.Title.failure_subtitle.size()*Math.random())), - ConfigReader.Title.failure_in, - ConfigReader.Title.failure_stay, - ConfigReader.Title.failure_out - ); - } - - @EventHandler - public void onQUit(PlayerQuitEvent event){ - Player player = event.getPlayer(); - player.removePotionEffect(PotionEffectType.SLOW); - if (hooks.get(player) != null){ - hooks.get(player).remove(); - } - hooks.remove(player); - coolDown.remove(player); - nextLoot.remove(player); - modifiers.remove(player); - fishingPlayers.remove(player); - vanilla.remove(player); - } - - @EventHandler - public void onInteract(PlayerInteractEvent event){ - if (!(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) return; - ItemStack itemStack = event.getItem(); - if (itemStack == null || itemStack.getType() == Material.AIR) return; - NBTItem nbtItem = new NBTItem(itemStack); - if (nbtItem.getCompound("CustomFishing") == null) return; - if (nbtItem.getCompound("CustomFishing").getString("type").equals("util") && nbtItem.getCompound("CustomFishing").getString("id").equals("fishfinder")){ - Player player = event.getPlayer(); - //设置冷却时间 - long time = System.currentTimeMillis(); - if (time - (coolDown.getOrDefault(player, time - ConfigReader.Config.fishFinderCoolDown)) < ConfigReader.Config.fishFinderCoolDown) { - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.coolDown); - return; - } - coolDown.put(player, time); - //获取玩家位置处可能的Loot实例列表 - List possibleLoots = getPossibleLootList(new FishingCondition(player.getLocation(), player), true); - if (possibleLoots.size() == 0){ - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.noLoot); - return; - } - StringBuilder stringBuilder = new StringBuilder(ConfigReader.Message.prefix + ConfigReader.Message.possibleLoots); - possibleLoots.forEach(loot -> stringBuilder.append(loot.getNick()).append(ConfigReader.Message.splitChar)); - AdventureUtil.playerMessage(player, stringBuilder.substring(0, stringBuilder.length()-ConfigReader.Message.splitChar.length())); - } - } - - /* - 获取可能的Loot列表 - */ - private List getPossibleLootList(FishingCondition fishingCondition, boolean finder) { - List available = new ArrayList<>(); - ConfigReader.LOOT.keySet().forEach(key -> { - Loot loot = ConfigReader.LOOT.get(key); - if (finder && !loot.isShowInFinder()) return; - List requirements = loot.getRequirements(); - if (requirements == null){ - available.add(loot); - }else { - boolean isMet = true; - for (Requirement requirement : requirements){ - if (!requirement.isConditionMet(fishingCondition)){ - isMet = false; - } - } - if (isMet){ - available.add(loot); - } - } - }); - return available; - } - - private void showPlayerBar(Player player){ - - Loot loot = nextLoot.get(player); - - String layout; - if (loot != null && loot.getLayout() != null){ - try { - layout = loot.getLayout().get((int) (loot.getLayout().size() * Math.random())); - } - catch (IndexOutOfBoundsException e){ - AdventureUtil.consoleMessage("[CustomFishing] Layouts should be in a list"); - return; - } - } - else { - Object[] values = ConfigReader.LAYOUT.keySet().toArray(); - layout = (String) values[new Random().nextInt(values.length)]; - } - - int difficulty = new Random().nextInt(5); - int timer = 1; - int time = 10000; - if (loot != null){ - difficulty = loot.getDifficulty().getSpeed(); - timer = loot.getDifficulty().getTimer(); - time = loot.getTime(); - } - - difficulty += Objects.requireNonNullElse(modifiers.get(player).getDifficulty(), 0); - - if (difficulty < 1){ - difficulty = 1; - } - - Difficulty difficult = new Difficulty(timer, difficulty); - fishingPlayers.put(player, - new FishingPlayer(System.currentTimeMillis() + time, - new Timer(player, difficult, layout) - ) - ); - - if (vanilla.get(player) == null && loot != null){ - for (ActionB action : loot.getHookActions()){ - action.doOn(player); - } - } - - player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, time/50,3)); - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/listener/InteractListener.java b/src/main/java/net/momirealms/customfishing/listener/InteractListener.java new file mode 100644 index 00000000..236eca42 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/listener/InteractListener.java @@ -0,0 +1,20 @@ +package net.momirealms.customfishing.listener; + +import net.momirealms.customfishing.manager.FishingManager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; + +public class InteractListener implements Listener { + + private final FishingManager fishingManager; + + public InteractListener(FishingManager fishingManager) { + this.fishingManager = fishingManager; + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + fishingManager.onInteract(event); + } +} diff --git a/src/main/java/net/momirealms/customfishing/listener/JobsListener.java b/src/main/java/net/momirealms/customfishing/listener/JobsRebornXPListener.java similarity index 78% rename from src/main/java/net/momirealms/customfishing/listener/JobsListener.java rename to src/main/java/net/momirealms/customfishing/listener/JobsRebornXPListener.java index a7e59331..8357422f 100644 --- a/src/main/java/net/momirealms/customfishing/listener/JobsListener.java +++ b/src/main/java/net/momirealms/customfishing/listener/JobsRebornXPListener.java @@ -6,13 +6,13 @@ import com.gamingmesh.jobs.container.Job; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -public class JobsListener implements Listener { +public class JobsRebornXPListener implements Listener { @EventHandler - public void onExpAdd(JobsExpGainEvent event){ + public void onXpGain(JobsExpGainEvent event) { Job job = Jobs.getJob("Fisherman"); if (event.getJob().equals(job)){ event.setExp(0); } } -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/listener/MMOItemsConverter.java b/src/main/java/net/momirealms/customfishing/listener/MMOItemsConverter.java deleted file mode 100644 index ee55f3cd..00000000 --- a/src/main/java/net/momirealms/customfishing/listener/MMOItemsConverter.java +++ /dev/null @@ -1,84 +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.listener; - -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTItem; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerFishEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; - -import java.util.HashMap; - -public class MMOItemsConverter implements Listener { - - private final HashMap coolDown = new HashMap<>(); - - @EventHandler - public void onFish(PlayerFishEvent event){ - - if (event.getState() == PlayerFishEvent.State.FISHING){ - - Player player = event.getPlayer(); - - long time = System.currentTimeMillis(); - if (time - (coolDown.getOrDefault(player, time - 5000)) < 5000) { - return; - } - coolDown.put(player, time); - - PlayerInventory inventory = player.getInventory(); - - ItemStack mainHand = inventory.getItemInMainHand(); - if(mainHand.getType() == Material.FISHING_ROD){ - NBTItem nbtItem = new NBTItem(mainHand); - if (nbtItem.getCompound("CustomFishing") == null) { - if (!nbtItem.getString("MMOITEMS_ITEM_ID").equals("")){ - NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing"); - nbtCompound.setString("type","rod"); - nbtCompound.setString("id",nbtItem.getString("MMOITEMS_ITEM_ID")); - mainHand.setItemMeta(nbtItem.getItem().getItemMeta()); - } - } - } - - ItemStack offHand = inventory.getItemInOffHand(); - if(offHand.getType() == Material.FISHING_ROD){ - NBTItem nbtItem = new NBTItem(offHand); - if (nbtItem.getCompound("CustomFishing") == null) { - if (!nbtItem.getString("MMOITEMS_ITEM_ID").equals("")){ - NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing"); - nbtCompound.setString("type", "rod"); - nbtCompound.setString("id", nbtItem.getString("MMOITEMS_ITEM_ID")); - offHand.setItemMeta(nbtItem.getItem().getItemMeta()); - } - } - } - } - } - - @EventHandler - public void onQuit(PlayerQuitEvent event){ - coolDown.remove(event.getPlayer()); - } -} diff --git a/src/main/java/net/momirealms/customfishing/listener/MMOItemsListener.java b/src/main/java/net/momirealms/customfishing/listener/MMOItemsListener.java index ea88c302..1cfa5c93 100644 --- a/src/main/java/net/momirealms/customfishing/listener/MMOItemsListener.java +++ b/src/main/java/net/momirealms/customfishing/listener/MMOItemsListener.java @@ -1,84 +1,15 @@ -/* - * 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.listener; -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTItem; -import org.bukkit.Material; -import org.bukkit.entity.Player; +import net.momirealms.customfishing.manager.FishingManager; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerFishEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import java.util.HashMap; - -public class MMOItemsListener implements Listener { - - private final HashMap coolDown = new HashMap<>(); +public record MMOItemsListener(FishingManager manager) implements Listener { @EventHandler - public void onFish(PlayerFishEvent event){ - - if (event.getState() == PlayerFishEvent.State.FISHING){ - - Player player = event.getPlayer(); - - long time = System.currentTimeMillis(); - if (time - (coolDown.getOrDefault(player, time - 5000)) < 5000) { - return; - } - coolDown.put(player, time); - - PlayerInventory inventory = player.getInventory(); - - ItemStack mainHand = inventory.getItemInMainHand(); - if(mainHand.getType() == Material.FISHING_ROD){ - NBTItem nbtItem = new NBTItem(mainHand); - if (nbtItem.getCompound("CustomFishing") == null) { - if (!nbtItem.getString("MMOITEMS_ITEM_ID").equals("")){ - NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing"); - nbtCompound.setString("type","rod"); - nbtCompound.setString("id",nbtItem.getString("MMOITEMS_ITEM_ID")); - mainHand.setItemMeta(nbtItem.getItem().getItemMeta()); - } - } - } - - ItemStack offHand = inventory.getItemInOffHand(); - if(offHand.getType() == Material.FISHING_ROD){ - NBTItem nbtItem = new NBTItem(offHand); - if (nbtItem.getCompound("CustomFishing") == null) { - if (!nbtItem.getString("MMOITEMS_ITEM_ID").equals("")){ - NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing"); - nbtCompound.setString("type", "rod"); - nbtCompound.setString("id", nbtItem.getString("MMOITEMS_ITEM_ID")); - offHand.setItemMeta(nbtItem.getItem().getItemMeta()); - } - } - } - } - } - - @EventHandler - public void onQuit(PlayerQuitEvent event){ - coolDown.remove(event.getPlayer()); + public void onFish(PlayerFishEvent event) { + if (event.getState() != PlayerFishEvent.State.FISHING) return; + manager.onMMOItemsRodCast(event); } } diff --git a/src/main/java/net/momirealms/customfishing/listener/PapiUnregister.java b/src/main/java/net/momirealms/customfishing/listener/PapiUnregister.java deleted file mode 100644 index 7e3e83dc..00000000 --- a/src/main/java/net/momirealms/customfishing/listener/PapiUnregister.java +++ /dev/null @@ -1,17 +0,0 @@ -package net.momirealms.customfishing.listener; - -import net.momirealms.customfishing.CustomFishing; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -public class PapiUnregister implements Listener { - - @EventHandler - public void onReload(me.clip.placeholderapi.events.ExpansionUnregisterEvent event){ - if (CustomFishing.placeholders != null){ - if (event.getExpansion().equals(CustomFishing.placeholders)){ - CustomFishing.placeholders.register(); - } - } - } -} diff --git a/src/main/java/net/momirealms/customfishing/listener/PickUpListener.java b/src/main/java/net/momirealms/customfishing/listener/PickUpListener.java index fba6e804..4dd356c7 100644 --- a/src/main/java/net/momirealms/customfishing/listener/PickUpListener.java +++ b/src/main/java/net/momirealms/customfishing/listener/PickUpListener.java @@ -15,14 +15,13 @@ public class PickUpListener implements Listener { public void onPickUp(PlayerAttemptPickupItemEvent event){ ItemStack itemStack = event.getItem().getItemStack(); NBTItem nbtItem = new NBTItem(itemStack); - if (nbtItem.hasKey("M_Owner")){ - if (!Objects.equals(nbtItem.getString("M_Owner"), event.getPlayer().getName())){ - event.setCancelled(true); - } - else { - nbtItem.removeKey("M_Owner"); - itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); - } + if (!nbtItem.hasKey("M_Owner")) return; + if (!Objects.equals(nbtItem.getString("M_Owner"), event.getPlayer().getName())){ + event.setCancelled(true); + } + else { + nbtItem.removeKey("M_Owner"); + itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); } } @@ -30,9 +29,8 @@ public class PickUpListener implements Listener { public void onMove(InventoryPickupItemEvent event){ ItemStack itemStack = event.getItem().getItemStack(); NBTItem nbtItem = new NBTItem(itemStack); - if (nbtItem.hasKey("M_Owner")){ - nbtItem.removeKey("M_Owner"); - itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); - } + if (!nbtItem.hasKey("M_Owner")) return; + nbtItem.removeKey("M_Owner"); + itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); } -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/listener/PlayerFishListener.java b/src/main/java/net/momirealms/customfishing/listener/PlayerFishListener.java new file mode 100644 index 00000000..1ad2540e --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/listener/PlayerFishListener.java @@ -0,0 +1,62 @@ +package net.momirealms.customfishing.listener; + +import net.momirealms.customfishing.manager.ConfigManager; +import net.momirealms.customfishing.manager.FishingManager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerFishEvent; + +public record PlayerFishListener( + FishingManager manager) implements Listener { + + @EventHandler(priority = EventPriority.MONITOR) + public void onFishMONITOR(PlayerFishEvent event) { + if (!ConfigManager.priority.equals("MONITOR")) return; + selectState(event); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onFishHIGHEST(PlayerFishEvent event) { + if (!ConfigManager.priority.equals("HIGHEST")) return; + selectState(event); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onFishHIGH(PlayerFishEvent event) { + if (!ConfigManager.priority.equals("HIGH")) return; + selectState(event); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onFishNORMAL(PlayerFishEvent event) { + if (!ConfigManager.priority.equals("NORMAL")) return; + selectState(event); + } + + @EventHandler(priority = EventPriority.LOW) + public void onFishLOW(PlayerFishEvent event) { + if (!ConfigManager.priority.equals("LOW")) return; + selectState(event); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onFishLOWEST(PlayerFishEvent event) { + if (!ConfigManager.priority.equals("LOWEST")) return; + selectState(event); + } + + public void selectState(PlayerFishEvent event) { + if (event.isCancelled()) return; + if (!ConfigManager.getWorldsList().contains(event.getHook().getLocation().getWorld())) return; + switch (event.getState()) { + case FISHING -> manager.onFishing(event); + case REEL_IN -> manager.onReelIn(event); + case CAUGHT_ENTITY -> manager.onCaughtEntity(event); + case CAUGHT_FISH -> manager.onCaughtFish(event); + case FAILED_ATTEMPT -> manager.onFailedAttempt(event); + case BITE -> manager.onBite(event); + case IN_GROUND -> manager.onInGround(event); + } + } +} diff --git a/src/main/java/net/momirealms/customfishing/listener/SimpleListener.java b/src/main/java/net/momirealms/customfishing/listener/SimpleListener.java new file mode 100644 index 00000000..ffcee539 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/listener/SimpleListener.java @@ -0,0 +1,20 @@ +package net.momirealms.customfishing.listener; + +import net.momirealms.customfishing.Function; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +public record SimpleListener(Function function) implements Listener { + + @EventHandler + public void onJoin(PlayerJoinEvent event) { + function.onJoin(event.getPlayer()); + } + + @EventHandler + public void onQuit(PlayerQuitEvent event) { + function.onQuit(event.getPlayer()); + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/BonusManager.java b/src/main/java/net/momirealms/customfishing/manager/BonusManager.java new file mode 100644 index 00000000..210d42f3 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/BonusManager.java @@ -0,0 +1,201 @@ +package net.momirealms.customfishing.manager; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.object.Bonus; +import net.momirealms.customfishing.object.Item; +import net.momirealms.customfishing.object.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.file.YamlConfiguration; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; + +import java.io.File; +import java.util.*; + +public class BonusManager { + + 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; + + public static void load() { + BAIT = new HashMap<>(); + BAITITEMS = new HashMap<>(); + ROD = new HashMap<>(); + RODITEMS = new HashMap<>(); + ENCHANTS = new HashMap<>(); + loadRod(); + loadBait(); + loadEnchant(); + loadUtil(); + } + + private static 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); + } + 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())); + setItemProperties(config, key, item); + UTILITEMS.put(key, ItemStackUtil.addIdentifier(ItemStackUtil.getFromItem(item), "util", key)); + } + } + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + UTILITEMS.size() + " utils"); + } + + private static 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")); + } + }); + ENCHANTS.put(key + ":" + level, bonus); + }); + } + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + ENCHANTS.size() + " enchantments"); + } + + private static 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) { + 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())); + 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"); + } + + private 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")); + } + }); + return bonus; + } + + private static 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) { + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + Set keys = config.getKeys(false); + for (String key : keys) { + Item item = new Item(Material.FISHING_ROD); + 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(YamlConfiguration 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); + } + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/CompetitionManager.java b/src/main/java/net/momirealms/customfishing/manager/CompetitionManager.java new file mode 100644 index 00000000..efc61aa1 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/CompetitionManager.java @@ -0,0 +1,77 @@ +package net.momirealms.customfishing.manager; + +import net.momirealms.customfishing.Function; +import net.momirealms.customfishing.competition.CompetitionConfig; +import net.momirealms.customfishing.competition.CompetitionGoal; +import net.momirealms.customfishing.competition.bossbar.BossBarConfig; +import net.momirealms.customfishing.competition.bossbar.Overlay; +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.util.ConfigUtil; +import org.bukkit.boss.BarColor; +import org.bukkit.configuration.file.YamlConfiguration; +import org.checkerframework.checker.units.qual.C; + +import java.util.*; + +public class CompetitionManager extends Function { + + public static HashMap competitionsT; + public static HashMap competitionsC; + + @Override + public void load() { + competitionsC = new HashMap<>(); + competitionsT = new HashMap<>(); + if (ConfigManager.enableCompetition) loadCompetitions(); + } + + @Override + public void unload() { + if (competitionsC != null) competitionsC.clear(); + if (competitionsT != null) competitionsT.clear(); + } + + public void loadCompetitions(){ + YamlConfiguration config = ConfigUtil.getConfig("competition.yml"); + Set keys = config.getKeys(false); + keys.forEach(key -> { + boolean enableBsb = config.getBoolean(key + ".bossbar.enable", false); + BossBarConfig bossBarConfig = new BossBarConfig( + config.getStringList(key + ".bossbar.text").toArray(new String[0]), + Overlay.valueOf(config.getString(key + ".bossbar.overlay","SOLID").toUpperCase()), + BarColor.valueOf(config.getString(key + ".bossbar.color","WHITE").toUpperCase()), + config.getInt(key + ".bossbar.refresh-rate",10), + config.getInt(key + ".bossbar.switch-interval", 15) + ); + + HashMap rewardsMap = new HashMap<>(); + Objects.requireNonNull(config.getConfigurationSection(key + ".prize")).getKeys(false).forEach(rank -> { + List rewards = new ArrayList<>(); + if (config.contains(key + ".prize." + rank + ".messages")) + rewards.add(new MessageActionImpl(config.getStringList(key + ".prize." + rank + ".messages").toArray(new String[0]), null)); + if (config.contains(key + ".prize." + rank + ".commands")) + rewards.add(new CommandActionImpl(config.getStringList(key + ".prize." + rank + ".commands").toArray(new String[0]), null)); + rewardsMap.put(rank, rewards.toArray(new ActionInterface[0])); + }); + + CompetitionConfig competitionConfig = new CompetitionConfig( + config.getInt(key + ".duration",600), + config.getInt(key + ".min-players",1), + config.getStringList(key + ".broadcast.start"), + config.getStringList(key + ".broadcast.end"), + config.getStringList(key + ".command.start"), + config.getStringList(key + ".command.end"), + config.getStringList(key + ".command.join"), + CompetitionGoal.valueOf(config.getString(key + ".goal", "RANDOM")), + bossBarConfig, + enableBsb, + rewardsMap + ); + + config.getStringList(key + ".start-time").forEach(time -> competitionsT.put(time, competitionConfig)); + competitionsC.put(key, competitionConfig); + }); + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/ConfigManager.java b/src/main/java/net/momirealms/customfishing/manager/ConfigManager.java new file mode 100644 index 00000000..90e59539 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/ConfigManager.java @@ -0,0 +1,123 @@ +package net.momirealms.customfishing.manager; + +import com.gamingmesh.jobs.CMILib.ConfigReader; +import net.momirealms.customfishing.util.AdventureUtil; +import net.momirealms.customfishing.util.ConfigUtil; +import net.momirealms.customfishing.util.JedisUtil; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.util.ArrayList; +import java.util.List; + +public class ConfigManager { + + public static World[] worlds; + public static List worldList; + public static boolean whiteOrBlack; + public static String priority; + public static String lang; + public static boolean otherLootBar; + public static boolean enableVanillaLoot; + public static boolean enableMcMMOLoot; + public static double vanillaLootRatio; + public static double mcMMOLootChance; + public static boolean needOpenWater; + public static boolean needRodForLoots; + public static boolean needRodToFish; + public static boolean rodLoseDurability; + public static int fishFinderCoolDown; + public static boolean enableCompetition; + public static boolean disableJobsXp; + public static boolean convertMMOItems; + public static boolean preventPickUp; + public static boolean enableFishingBag; + public static boolean alwaysFishingBar; + + public static String[] successTitle; + public static String[] successSubTitle; + public static int successFadeIn; + public static int successFadeStay; + public static int successFadeOut; + + public static String[] failureTitle; + public static String[] failureSubTitle; + public static int failureFadeIn; + public static int failureFadeStay; + public static int failureFadeOut; + public static boolean useRedis; + + public static void load() { + ConfigUtil.update("config.yml"); + YamlConfiguration config = ConfigUtil.getConfig("config.yml"); + + lang = config.getString("lang","english"); + + 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]); + + alwaysFishingBar = config.getBoolean("mechanics.other-loots.fishing-bar", true); + otherLootBar = config.getBoolean("mechanics.other-loots.fishing-bar", true); + enableVanillaLoot = config.getBoolean("mechanics.other-loots.vanilla.enable", true); + vanillaLootRatio = config.getDouble("mechanics.other-loots.vanilla.ratio", 0.4); + enableMcMMOLoot = config.getBoolean("mechanics.other-loots.mcMMO.enable", false); + mcMMOLootChance = config.getDouble("mechanics.other-loots.mcMMO.chance", 0.5); + needOpenWater = config.getBoolean("mechanics.need-open-water", true); + needRodForLoots = config.getBoolean("mechanics.need-special-rod.for-loots", false); + needRodToFish = config.getBoolean("mechanics.need-special-rod.to-fish", false); + rodLoseDurability = config.getBoolean("mechanics.rod-lose-durability", true); + fishFinderCoolDown = config.getInt("mechanics.fishfinder-cooldown", 3000); + enableCompetition = config.getBoolean("mechanics.fishing-competition", true); + + 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); + + 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; + + tryEnableJedis(); + } + public static List getWorldsList() { + if (whiteOrBlack) { + return worldList; + } + else { + List worldList = new ArrayList<>(Bukkit.getWorlds()); + worldList.removeAll(ConfigManager.worldList); + return worldList; + } + } + + public static void tryEnableJedis(){ + YamlConfiguration configuration = ConfigUtil.getConfig("redis.yml"); + useRedis = false; + if (configuration.getBoolean("redis.enable")){ + JedisUtil.initializeRedis(configuration); + useRedis = true; + } + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/FishingManager.java b/src/main/java/net/momirealms/customfishing/manager/FishingManager.java new file mode 100644 index 00000000..2ab60f40 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/FishingManager.java @@ -0,0 +1,757 @@ +package net.momirealms.customfishing.manager; + +import de.tr7zw.changeme.nbtapi.NBTCompound; +import de.tr7zw.changeme.nbtapi.NBTItem; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.Function; +import net.momirealms.customfishing.api.event.FishFinderEvent; +import net.momirealms.customfishing.api.event.FishHookEvent; +import net.momirealms.customfishing.api.event.FishResultEvent; +import net.momirealms.customfishing.api.event.RodCastEvent; +import net.momirealms.customfishing.integration.MobInterface; +import net.momirealms.customfishing.integration.item.McMMOTreasure; +import net.momirealms.customfishing.listener.*; +import net.momirealms.customfishing.object.*; +import net.momirealms.customfishing.object.action.ActionInterface; +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.util.AdventureUtil; +import net.momirealms.customfishing.util.ItemStackUtil; +import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.FishHook; +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class FishingManager extends Function { + + private final PlayerFishListener playerFishListener; + private final InteractListener interactListener; + private PickUpListener pickUpListener; + private MMOItemsListener mmoItemsListener; + private JobsRebornXPListener jobsRebornXPListener; + private final HashMap coolDown; + private final HashMap hooksCache; + private final HashMap nextLoot; + private final HashMap nextBonus; + private final HashMap vanillaLoot; + private final ConcurrentHashMap fishingPlayerCache; + + public FishingManager() { + this.playerFishListener = new PlayerFishListener(this); + this.interactListener = new InteractListener(this); + this.coolDown = new HashMap<>(); + this.hooksCache = new HashMap<>(); + this.nextLoot = new HashMap<>(); + this.nextBonus = new HashMap<>(); + this.vanillaLoot = new HashMap<>(); + this.fishingPlayerCache = new ConcurrentHashMap<>(); + load(); + } + + @Override + public void load() { + Bukkit.getPluginManager().registerEvents(this.playerFishListener, CustomFishing.plugin); + Bukkit.getPluginManager().registerEvents(this.interactListener, CustomFishing.plugin); + if (ConfigManager.preventPickUp) { + this.pickUpListener = new PickUpListener(); + Bukkit.getPluginManager().registerEvents(this.pickUpListener, CustomFishing.plugin); + } + if (ConfigManager.convertMMOItems) { + this.mmoItemsListener = new MMOItemsListener(this); + Bukkit.getPluginManager().registerEvents(this.mmoItemsListener, CustomFishing.plugin); + } + if (ConfigManager.disableJobsXp) { + this.jobsRebornXPListener = new JobsRebornXPListener(); + Bukkit.getPluginManager().registerEvents(this.jobsRebornXPListener, CustomFishing.plugin); + } + } + + @Override + public void unload() { + HandlerList.unregisterAll(this.playerFishListener); + HandlerList.unregisterAll(this.interactListener); + if (this.pickUpListener != null) HandlerList.unregisterAll(this.pickUpListener); + if (this.mmoItemsListener != null) HandlerList.unregisterAll(this.mmoItemsListener); + if (this.jobsRebornXPListener != null) HandlerList.unregisterAll(this.jobsRebornXPListener); + } + + public void onFishing(PlayerFishEvent event) { + + final Player player = event.getPlayer(); + final FishHook fishHook = event.getHook(); + + hooksCache.put(player, fishHook); + if (isCoolDown(player, 2000)) return; + + Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.plugin, () -> { + + PlayerInventory inventory = player.getInventory(); + + boolean noSpecialRod = true; + boolean noRod = true; + boolean noBait = true; + + Bonus initialBonus = new Bonus(); + initialBonus.setDifficulty(0); + initialBonus.setDoubleLoot(0); + initialBonus.setTime(1); + initialBonus.setScore(1); + initialBonus.setWeightMD(new HashMap<>()); + initialBonus.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); + } + 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); + noSpecialRod = false; + } + } + else if (nbtCompound.getString("type").equals("bait")) { + Bonus baitBonus = BonusManager.BAIT.get(nbtCompound.getString("id")); + if (baitBonus != null) { + initialBonus.addBonus(baitBonus); + mainHandItem.setAmount(mainHandItem.getAmount() - 1); + noBait = false; + } + } + } + } + + ItemStack offHandItem = inventory.getItemInOffHand(); + Material offHandItemType = offHandItem.getType(); + if (offHandItemType != Material.AIR){ + if (noRod && offHandItemType == Material.FISHING_ROD) { + enchantBonus(initialBonus, offHandItem); + } + 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); + offHandItem.setAmount(offHandItem.getAmount() - 1); + noBait = false; + } + } + else if (noSpecialRod && nbtCompound.getString("type").equals("rod")) { + Bonus rodBonus = BonusManager.ROD.get(nbtCompound.getString("id")); + if (rodBonus != null) { + initialBonus.addBonus(rodBonus); + noSpecialRod = false; + } + } + } + } + + if (ConfigManager.enableFishingBag && noBait) { + //育儿袋 + } + + RodCastEvent rodCastEvent = new RodCastEvent(player, initialBonus); + if (rodCastEvent.isCancelled()) { + event.setCancelled(true); + return; + } + + nextBonus.put(player, initialBonus); + + List possibleLoots = getPossibleLootList(new FishingCondition(fishHook.getLocation(), player), false); + List availableLoots = new ArrayList<>(); + if (possibleLoots.size() == 0){ + nextLoot.put(player, null); + return; + } + if (ConfigManager.needRodForLoots && noSpecialRod){ + if (!ConfigManager.enableVanillaLoot) AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.noRod); + nextLoot.put(player, null); + } + if (ConfigManager.needRodToFish && noSpecialRod){ + nextLoot.put(player, Loot.EMPTY); + } + if ((ConfigManager.needRodForLoots || ConfigManager.needRodToFish) && noSpecialRod) return; + + HashMap as = initialBonus.getWeightAS(); + HashMap md = initialBonus.getWeightMD(); + + double[] weights = new double[possibleLoots.size()]; + int index = 0; + for (Loot loot : possibleLoots){ + double weight = loot.getWeight(); + String group = loot.getGroup(); + if (group != null){ + if (as.get(group) != null){ + weight += as.get(group); + } + if (md.get(group) != null){ + weight *= md.get(group); + } + } + if (weight <= 0) continue; + availableLoots.add(loot); + weights[index++] = weight; + } + + double total = Arrays.stream(weights).sum(); + double[] weightRatios = new double[index]; + for (int i = 0; i < index; i++){ + weightRatios[i] = weights[i]/total; + } + + double[] weightRange = new double[index]; + double startPos = 0; + for (int i = 0; i < index; i++) { + weightRange[i] = startPos + weightRatios[i]; + startPos += weightRatios[i]; + } + + double random = Math.random(); + int pos = Arrays.binarySearch(weightRange, random); + + if (pos < 0) { + pos = -pos - 1; + } + if (pos < weightRange.length && random < weightRange[pos]) { + nextLoot.put(player, availableLoots.get(pos)); + return; + } + nextLoot.put(player, null); + }); + } + + public void onCaughtFish(PlayerFishEvent event) { + final Player player = event.getPlayer(); + if (!(event.getCaught() instanceof Item item)) return; + + FishingPlayer fishingPlayer = fishingPlayerCache.remove(player); + if (fishingPlayer == null) { + if (ConfigManager.enableVanillaLoot) { + // Not a vanilla loot + if (ConfigManager.vanillaLootRatio < Math.random()) { + event.setCancelled(true); + Loot loot = nextLoot.get(player); + if (loot != null) { + vanillaLoot.remove(player); + } + else { + vanillaLoot.put(player, new VanillaLoot(item.getItemStack(), event.getExpToDrop())); + } + showPlayerBar(player, loot); + } + // Is vanilla loot + else { + if (ConfigManager.alwaysFishingBar) { + event.setCancelled(true); + vanillaLoot.put(player, new VanillaLoot(item.getItemStack(), event.getExpToDrop())); + showPlayerBar(player, null); + } + //else vanilla fishing mechanic + } + } + else { + // No custom loot + Loot loot = nextLoot.get(player); + if (loot == null) { + item.remove(); + event.setExpToDrop(0); + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.noLoot); + } + else { + event.setCancelled(true); + showPlayerBar(player, loot); + } + } + } + else { + item.remove(); + event.setExpToDrop(0); + proceedReelIn(event, player, fishingPlayer); + } + } + + private void proceedReelIn(PlayerFishEvent event, Player player, FishingPlayer fishingPlayer) { + fishingPlayer.cancel(); + Loot loot = nextLoot.remove(player); + VanillaLoot vanilla = vanillaLoot.remove(player); + player.removePotionEffect(PotionEffectType.SLOW); + + if (ConfigManager.needOpenWater && !event.getHook().isInOpenWater()){ + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.notOpenWater); + return; + } + + if (fishingPlayer.isSuccess()) { + if (ConfigManager.rodLoseDurability) loseDurability(player); + Location location = event.getHook().getLocation(); + if (vanilla != null) { + dropVanillaLoot(player, vanilla, location, fishingPlayer.isDouble()); + return; + } + if (loot instanceof Mob mob) { + summonMob(player, loot, location, mob); + return; + } + if (loot instanceof DroppedItem droppedItem){ + if (ConfigManager.enableMcMMOLoot && Math.random() < ConfigManager.mcMMOLootChance){ + if (dropMcMMOLoot(player, location, fishingPlayer.isDouble())){ + return; + } + } + dropCustomFishingLoot(player, location, droppedItem, fishingPlayer.isDouble()); + } + } + else { + fail(player, loot, vanilla != null); + } + } + + public void onReelIn(PlayerFishEvent event) { + final Player player = event.getPlayer(); + FishingPlayer fishingPlayer = fishingPlayerCache.remove(player); + if (fishingPlayer == null) return; + proceedReelIn(event, player, fishingPlayer); + } + + private void dropCustomFishingLoot(Player player, Location location, DroppedItem droppedItem, boolean isDouble) { + ItemStack drop = getCustomFishingLootItemStack(droppedItem, player); + FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_LOOT, isDouble, drop); + Bukkit.getPluginManager().callEvent(fishResultEvent); + if (fishResultEvent.isCancelled()) { + return; + } + + dropItem(player, location, fishResultEvent.isDouble(), drop); + for (ActionInterface action : droppedItem.getSuccessActions()) + action.doOn(player); + sendSuccessTitle(player, droppedItem.getNick()); + } + + private ItemStack getCustomFishingLootItemStack(DroppedItem droppedItem, Player player) { + String key = droppedItem.getMaterial(); + ItemStack drop = CustomFishing.plugin.getIntegrationManager().build(key); + + if (drop.getType() != Material.AIR) { + if (droppedItem.getRandomEnchants() != null) + ItemStackUtil.addRandomEnchants(drop, droppedItem.getRandomEnchants()); + if (droppedItem.isRandomDurability()) + ItemStackUtil.addRandomDamage(drop); + if (ConfigManager.preventPickUp) + ItemStackUtil.addOwner(drop, player.getName()); + } + return drop; + } + + private boolean dropMcMMOLoot(Player player, Location location, boolean isDouble) { + ItemStack itemStack = McMMOTreasure.getTreasure(player); + if (itemStack == null) return false; + + FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_VANILLA, isDouble, itemStack); + Bukkit.getPluginManager().callEvent(fishResultEvent); + if (fishResultEvent.isCancelled()) { + return true; + } + + player.giveExp(new Random().nextInt(24), true); + dropItem(player, location, fishResultEvent.isDouble(), itemStack); + sendSuccessTitle(player, itemStack); + return true; + } + + private void dropItem(Player player, Location location, boolean isDouble, ItemStack itemStack) { + if (itemStack.getType() == Material.AIR) return; + Entity item = location.getWorld().dropItem(location, itemStack); + Vector vector = player.getLocation().subtract(location).toVector().multiply(0.1); + vector = vector.setY((vector.getY()+0.2) * 1.2); + item.setVelocity(vector); + if (isDouble){ + Entity item2 = location.getWorld().dropItem(location, itemStack); + item2.setVelocity(vector); + } + } + + private void dropVanillaLoot(Player player, VanillaLoot vanillaLoot, Location location, boolean isDouble) { + + ItemStack itemStack; + itemStack = vanillaLoot.getItemStack(); + + if (ConfigManager.enableMcMMOLoot && Math.random() < ConfigManager.mcMMOLootChance){ + ItemStack mcMMOItemStack = McMMOTreasure.getTreasure(player); + if (mcMMOItemStack != null){ + itemStack = mcMMOItemStack; + } + } + + FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_VANILLA, isDouble, itemStack); + Bukkit.getPluginManager().callEvent(fishResultEvent); + if (fishResultEvent.isCancelled()) { + return; + } + + player.giveExp(vanillaLoot.getXp(), true); + AdventureUtil.playerSound(player, Sound.Source.PLAYER, Key.key("minecraft:entity.experience_orb.pickup"), 1, 1); + dropItem(player, location, isDouble, itemStack); + sendSuccessTitle(player, itemStack); + } + + private void summonMob(Player player, Loot loot, Location location, Mob mob) { + MobInterface mobInterface = CustomFishing.plugin.getIntegrationManager().getMobInterface(); + if (mobInterface == null) return; + + FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_MOB, false, null); + if (fishResultEvent.isCancelled()) { + return; + } + + mobInterface.summon(player.getLocation(), location, mob); + for (ActionInterface action : loot.getSuccessActions()) + action.doOn(player); + sendSuccessTitle(player, loot.getNick()); + } + + @NotNull + private Component getTitleComponent(ItemStack itemStack, String text) { + Component component; + if (text.contains("{loot}")){ + text = text.replace("{loot}","|"); + if (text.startsWith("|")){ + component = getDisplayName(itemStack).append(MiniMessage.miniMessage().deserialize(text.substring(1))); + } + else if (text.endsWith("|")){ + component = MiniMessage.miniMessage().deserialize(text.substring(0,text.length() - 1)).append(getDisplayName(itemStack)); + } + else { + String[] titleSplit = StringUtils.split(text, "|"); + component = MiniMessage.miniMessage().deserialize(titleSplit[0]).append(getDisplayName(itemStack)).append(MiniMessage.miniMessage().deserialize(titleSplit[1])); + } + } + else { + component = MiniMessage.miniMessage().deserialize(text); + } + return component; + } + + private void sendSuccessTitle(Player player, String loot) { + AdventureUtil.playerTitle( + player, + ConfigManager.successTitle[new Random().nextInt(ConfigManager.successTitle.length)] + .replace("{loot}", loot) + .replace("{player}", player.getName()), + ConfigManager.successSubTitle[new Random().nextInt(ConfigManager.successSubTitle.length)] + .replace("{loot}", loot) + .replace("{player}", player.getName()), + ConfigManager.successFadeIn, + ConfigManager.successFadeStay, + ConfigManager.successFadeOut + ); + } + + private void sendSuccessTitle(Player player, ItemStack itemStack) { + String title = ConfigManager.successTitle[new Random().nextInt(ConfigManager.successTitle.length)]; + 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 + ); + } + + private void loseDurability(Player player) { + if (player.getGameMode() == GameMode.CREATIVE) return; + PlayerInventory inventory = player.getInventory(); + ItemStack mainHand = inventory.getItemInMainHand(); + if (mainHand.getType() == Material.FISHING_ROD){ + setDurability(mainHand); + } + else { + ItemStack offHand = inventory.getItemInOffHand(); + if (offHand.getType() == Material.FISHING_ROD){ + setDurability(offHand); + } + } + } + + private void setDurability(ItemStack rod) { + Damageable damageable = (Damageable) rod.getItemMeta(); + if (damageable.isUnbreakable()) return; + Enchantment enchantment = Enchantment.DURABILITY; + if (Math.random() < (1 / (double) (damageable.getEnchantLevel(enchantment) + 1))){ + damageable.setDamage(damageable.getDamage() + 1); + Bukkit.getScheduler().runTaskLater(CustomFishing.plugin, () -> rod.setItemMeta(damageable),1); + } + } + + private void fail(Player player, Loot loot, boolean isVanilla) { + + FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.FAILURE, false, null); + Bukkit.getServer().getPluginManager().callEvent(fishResultEvent); + if (fishResultEvent.isCancelled()) { + return; + } + + if (!isVanilla && loot != null){ + for (ActionInterface action : loot.getFailureActions()) + action.doOn(player); + } + + 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 + ); + } + + public void onCaughtEntity(PlayerFishEvent event) { + final Player player = event.getPlayer(); + if (fishingPlayerCache.remove(player) != null && event.getCaught() != null){ + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.hookOther); + } + } + + public void onFailedAttempt(PlayerFishEvent event) { + //Empty + } + + public void onBite(PlayerFishEvent event) { + //Empty + } + + public void onInGround(PlayerFishEvent event) { + FishHook fishHook = event.getHook(); + + Block belowBlock = fishHook.getLocation().clone().subtract(0,1,0).getBlock(); + Block inBlock = fishHook.getLocation().getBlock(); + if (inBlock.getType() == Material.AIR && belowBlock.getType() == Material.ICE) { + + } + else if (inBlock.getType() == Material.LAVA) { + + } + } + + public void onMMOItemsRodCast(PlayerFishEvent event) { + final Player player = event.getPlayer(); + if (isCoolDown(player, 5000)) return; + PlayerInventory inventory = player.getInventory(); + setCustomTag(inventory.getItemInMainHand()); + setCustomTag(inventory.getItemInOffHand()); + } + + private void setCustomTag(ItemStack itemStack) { + if(itemStack.getType() != Material.FISHING_ROD) return; + NBTItem nbtItem = new NBTItem(itemStack); + if (nbtItem.getCompound("CustomFishing") != null) return; + if (!nbtItem.hasKey("MMOITEMS_ITEM_ID")) return; + ItemStackUtil.addIdentifier(itemStack, "rod", nbtItem.getString("MMOITEMS_ITEM_ID")); + } + + public boolean isCoolDown(Player player, long delay) { + long time = System.currentTimeMillis(); + if (time - (coolDown.getOrDefault(player, time - delay)) < delay) return true; + coolDown.put(player, time); + return false; + } + + private void enchantBonus(Bonus initialBonus, ItemStack mainHandItem) { + Map enchantments = mainHandItem.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); + } + } + } + + private List getPossibleLootList(FishingCondition fishingCondition, boolean finder) { + List available = new ArrayList<>(); + outer: + for (Loot loot : LootManager.WATERLOOTS.values()) { + if (finder && !loot.isShowInFinder()) continue; + RequirementInterface[] requirements = loot.getRequirements(); + if (requirements == null){ + available.add(loot); + } + else { + for (RequirementInterface requirement : requirements){ + if (!requirement.isConditionMet(fishingCondition)){ + continue outer; + } + } + available.add(loot); + } + } + return available; + } + + public void onInteract(PlayerInteractEvent event) { + ItemStack itemStack = event.getItem(); + if (itemStack == null || itemStack.getType() == Material.AIR) return; + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound cfCompound = nbtItem.getCompound("CustomFishing"); + if (cfCompound != null && cfCompound.getString("type").equals("util") && cfCompound.getString("id").equals("fishfinder")) { + useFinder(event.getPlayer()); + return; + } + Block block = event.getClickedBlock(); + if (block == null) return; + String totemID = nbtItem.getString("totem"); + if (totemID.equals("")) return; + if (!TotemManager.TOTEMS.containsKey(totemID)) return; + + } + + private void useFinder(Player player) { + if (isCoolDown(player, ConfigManager.fishFinderCoolDown)) return; + List possibleLoots = getPossibleLootList(new FishingCondition(player.getLocation(), player), true); + + FishFinderEvent fishFinderEvent = new FishFinderEvent(player, possibleLoots); + Bukkit.getPluginManager().callEvent(fishFinderEvent); + if (fishFinderEvent.isCancelled()) { + return; + } + + if (possibleLoots.size() == 0) { + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.noLoot); + return; + } + StringBuilder stringBuilder = new StringBuilder(MessageManager.prefix + MessageManager.possibleLoots); + possibleLoots.forEach(loot -> stringBuilder.append(loot.getNick()).append(MessageManager.splitChar)); + AdventureUtil.playerMessage(player, stringBuilder.substring(0, stringBuilder.length() - MessageManager.splitChar.length())); + } + + 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)]; + } + else { + //Not null + layout = LayoutManager.LAYOUTS.values().stream().findAny().get(); + } + + int speed; + int timer; + int time; + if (loot != null){ + speed = loot.getDifficulty().speed(); + timer = loot.getDifficulty().timer(); + time = loot.getTime(); + } + else { + speed = new Random().nextInt(5); + time = 10000; + timer = 1; + } + + Bonus bonus = nextBonus.get(player); + boolean isDouble =false; + if (bonus != null) { + speed += bonus.getDifficulty(); + isDouble = Math.random() < bonus.getDoubleLoot(); + } + + 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; + } + + FishingPlayer fishingPlayer = new FishingPlayer(System.currentTimeMillis() + time, player, layout, difficult, this, isDouble); + fishingPlayer.runTaskTimerAsynchronously(CustomFishing.plugin, 0, 1); + fishingPlayerCache.put(player, fishingPlayer); + + if (vanillaLoot.get(player) == null && loot != null){ + for (ActionInterface action : loot.getHookActions()) { + action.doOn(player); + } + } + + player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, time/50,3)); + } + + @Override + public void onQuit(Player player) { + coolDown.remove(player); + nextLoot.remove(player); + nextBonus.remove(player); + vanillaLoot.remove(player); + // prevent bar duplication + FishHook fishHook = hooksCache.remove(player); + if (fishHook != null) fishHook.remove(); + } + + @Nullable + public FishingPlayer getFishingPlayer(Player player) { + return fishingPlayerCache.get(player); + } + + public void removeFishingPlayer(Player player) { + fishingPlayerCache.remove(player); + } + + private Component getDisplayName(ItemStack itemStack){ + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound nbtCompound = nbtItem.getCompound("display"); + if (nbtCompound != null){ + String name = nbtCompound.getString("Name"); + if (!name.equals("")){ + return GsonComponentSerializer.gson().deserialize(name); + } + } + String type = itemStack.getType().toString().toLowerCase(); + if (itemStack.getType().isBlock()) return GsonComponentSerializer.gson().deserialize("{\"translate\":\"block.minecraft." + type + "\"}"); + else return GsonComponentSerializer.gson().deserialize("{\"translate\":\"item.minecraft." + type + "\"}"); + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/IntegrationManager.java b/src/main/java/net/momirealms/customfishing/manager/IntegrationManager.java new file mode 100644 index 00000000..289bbf1c --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/IntegrationManager.java @@ -0,0 +1,144 @@ +package net.momirealms.customfishing.manager; + +import net.momirealms.customfishing.Function; +import net.momirealms.customfishing.integration.ItemInterface; +import net.momirealms.customfishing.integration.MobInterface; +import net.momirealms.customfishing.integration.SeasonInterface; +import net.momirealms.customfishing.integration.SkillInterface; +import net.momirealms.customfishing.integration.item.*; +import net.momirealms.customfishing.integration.mob.MythicMobsMobHook; +import net.momirealms.customfishing.integration.papi.PlaceholderManager; +import net.momirealms.customfishing.integration.season.RealisticSeasonsImpl; +import net.momirealms.customfishing.integration.skill.*; +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.inventory.ItemStack; +import org.bukkit.plugin.PluginManager; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; + +public class IntegrationManager extends Function { + + private SeasonInterface seasonInterface; + private SkillInterface skillInterface; + private ItemInterface[] itemInterfaces; + private MobInterface mobInterface; + private PlaceholderManager placeholderManager; + + public IntegrationManager() { + load(); + } + + @Override + public void load() { + + PluginManager pluginManager = Bukkit.getPluginManager(); + + if (this.placeholderManager != null) { + this.placeholderManager.unload(); + } + if (pluginManager.getPlugin("PlaceholderAPI") != null) { + this.placeholderManager = new PlaceholderManager(); + } + + List itemInterfaceList = new ArrayList<>(); + itemInterfaceList.add(new CustomFishingItemHook()); + if (pluginManager.getPlugin("ItemsAdder") != null) itemInterfaceList.add(new ItemsAdderItemHook()); + if (pluginManager.getPlugin("Oraxen") != null) itemInterfaceList.add(new OraxenItemHook()); + if (pluginManager.getPlugin("MMOItems") != null) itemInterfaceList.add(new MMOItemsItemHook()); + if (pluginManager.getPlugin("MythicMobs") != null) { + itemInterfaceList.add(new MythicMobsItemHook()); + this.mobInterface = new MythicMobsMobHook(); + } + this.itemInterfaces = itemInterfaceList.toArray(new ItemInterface[0]); + + + if (pluginManager.getPlugin("eco") != null) { + EcoItemHook.registerItems(); + } + + YamlConfiguration config = ConfigUtil.getConfig("config.yml"); + if (config.getBoolean("integration.RealisticSeasons", false) && pluginManager.getPlugin("RealisticSeasons") != null) { + this.seasonInterface = new RealisticSeasonsImpl(); + hookMessage("RealisticSeasons"); + } else if (config.getBoolean("integration.CustomCrops", false) && pluginManager.getPlugin("CustomCrops") != null) { + //TODO + this.seasonInterface = null; + hookMessage("CustomCrops"); + } + if (config.getBoolean("integration.mcMMO", false) && Bukkit.getPluginManager().getPlugin("mcMMO") != null) { + this.skillInterface = new mcMMOHook(); + hookMessage("mcMMO"); + } else if (config.getBoolean("integration.MMOCore", false) && Bukkit.getPluginManager().getPlugin("MMOCore") != null) { + this.skillInterface = new MMOCoreHook(); + hookMessage("MMOCore"); + } else if (config.getBoolean("integration.AureliumSkills", false) && Bukkit.getPluginManager().getPlugin("AureliumSkills") != null) { + this.skillInterface = new AureliumsHook(); + hookMessage("AureliumSkills"); + } else if (config.getBoolean("integration.EcoSkills", false) && Bukkit.getPluginManager().getPlugin("EcoSkills") != null) { + this.skillInterface = new EcoSkillsHook(); + hookMessage("EcoSkills"); + } else if (config.getBoolean("integration.JobsReborn", false) && Bukkit.getPluginManager().getPlugin("Jobs") != null) { + this.skillInterface = new JobsRebornHook(); + hookMessage("JobsReborn"); + } + } + + @Override + public void unload() { + this.seasonInterface = null; + this.skillInterface = null; + this.itemInterfaces = null; + this.mobInterface = null; + if (this.placeholderManager != null) { + this.placeholderManager.unload(); + this.placeholderManager = null; + } + } + + @Nullable + public SeasonInterface getSeasonInterface() { + return seasonInterface; + } + + @Nullable + public SkillInterface getSkillInterface() { + return skillInterface; + } + + @NotNull + public ItemInterface[] getItemInterfaces() { + return itemInterfaces; + } + + @Nullable + public MobInterface getMobInterface() { + return mobInterface; + } + + @Nullable + public PlaceholderManager getPlaceholderManager() { + return placeholderManager; + } + + @NotNull + public ItemStack build(String key) { + for (ItemInterface itemInterface : itemInterfaces) { + ItemStack itemStack = itemInterface.build(key); + if (itemStack != null) { + return itemStack; + } + } + return new ItemStack(Material.AIR); + } + + private void hookMessage(String plugin){ + AdventureUtil.consoleMessage("[CustomFishing] " + plugin + " Hooked!"); + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/LayoutManager.java b/src/main/java/net/momirealms/customfishing/manager/LayoutManager.java new file mode 100644 index 00000000..c86690af --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/LayoutManager.java @@ -0,0 +1,41 @@ +package net.momirealms.customfishing.manager; + +import net.momirealms.customfishing.object.Layout; +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 { + + public static HashMap LAYOUTS; + + public static 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); + } + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/LootManager.java b/src/main/java/net/momirealms/customfishing/manager/LootManager.java new file mode 100644 index 00000000..27595195 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/LootManager.java @@ -0,0 +1,215 @@ +package net.momirealms.customfishing.manager; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.object.*; +import net.momirealms.customfishing.object.action.*; +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.*; +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.MemorySection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.util.*; + +public class LootManager { + + public static HashMap WATERLOOTS; + public static HashMap LAVALOOTS; + public static HashMap LOOTITEMS; + + @Nullable + public static Loot getLoot(String key) { + return WATERLOOTS.get(key); + } + + @Nullable + public static ItemStack build(String key) { + ItemStack itemStack = LOOTITEMS.get(key); + return itemStack == null ? null : itemStack.clone(); + } + + public static void load() { + WATERLOOTS = new HashMap<>(); + LAVALOOTS = new HashMap<>(); + LOOTITEMS = new HashMap<>(); + loadItems(); + loadMobs(); + AdventureUtil.consoleMessage("[CustomFishing] Loaded " + (LAVALOOTS.size() + WATERLOOTS.size()) + " loots"); + } + + private static void loadMobs() { + if (Bukkit.getPluginManager().getPlugin("MythicMobs") == null) return; + File mob_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "mobs"); + if (!mob_file.exists()) { + if (!mob_file.mkdir()) return; + CustomFishing.plugin.saveResource("mobs" + File.separator + "example.yml", false); + } + File[] files = mob_file.listFiles(); + if (files == null) return; + for (File file : files) { + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + Set keys = config.getKeys(false); + for (String key : keys) { + if (!config.getBoolean(key + ".enable", true)) continue; + // Bar mechanic + String[] diff = StringUtils.split(config.getString(key + ".difficulty", "1-1"),"-"); + Difficulty difficulty = new Difficulty(Integer.parseInt(diff[0]), Integer.parseInt(diff[1])); + int weight = config.getInt(key + ".weight",10); + int time = config.getInt(key + ".time",10000); + Mob loot = new Mob( + key, + difficulty, + time, + weight, + config.getString(key + ".mythicmobsID", key), + config.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 + ".mythicmobsID", key))); + setActionsAndRequirements(config, loot, key); + WATERLOOTS.put(key, loot); + } + } + } + + private static void loadItems() { + File loot_file = new File(CustomFishing.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); + } + File[] files = loot_file.listFiles(); + if (files == null) return; + for (File file : files) { + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + Set keys = config.getKeys(false); + for (String key : keys) { + if (!config.getBoolean(key + ".enable", true)) continue; + + String material = config.getString(key + ".material","COD"); + // Bar mechanic + String[] diff = StringUtils.split(config.getString(key + ".difficulty", "1-1"),"-"); + Difficulty difficulty = new Difficulty(Integer.parseInt(diff[0]), Integer.parseInt(diff[1])); + int weight = config.getInt(key + ".weight",10); + int time = config.getInt(key + ".time",10000); + DroppedItem loot = new DroppedItem( + key, + difficulty, + 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 + ".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); + } + }); + 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())); + BonusManager.setItemProperties(config, key, item); + if (item.getMaterial() == Material.AIR) LOOTITEMS.put(key, new ItemStack(Material.AIR)); + else LOOTITEMS.put(key, ItemStackUtil.getFromItem(item)); + } + } + } + + private static void setActionsAndRequirements(YamlConfiguration config, Loot loot, String key) { + + 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; + } + 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)); + + 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))); + } + }); + loot.setRequirements(requirements.toArray(new RequirementInterface[0])); + } + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/MessageManager.java b/src/main/java/net/momirealms/customfishing/manager/MessageManager.java new file mode 100644 index 00000000..f3e8b93c --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/MessageManager.java @@ -0,0 +1,72 @@ +package net.momirealms.customfishing.manager; + +import net.momirealms.customfishing.util.ConfigUtil; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; + +public class MessageManager { + + public static String prefix; + public static String reload; + public static String nonArgs; + public static String unavailableArgs; + public static String escape; + public static String noPerm; + public static String notExist; + public static String noConsole; + public static String wrongAmount; + public static String lackArgs; + public static String notOnline; + public static String giveItem; + public static String getItem; + public static String coolDown; + public static String possibleLoots; + public static String splitChar; + public static String noLoot; + public static String notOpenWater; + public static String competitionOn; + public static String notEnoughPlayers; + public static String noRank; + public static String forceSuccess; + public static String forceFailure; + public static String forceEnd; + public static String forceCancel; + public static String noPlayer; + public static String noScore; + public static String noRod; + public static String hookOther; + + public static void load() { + YamlConfiguration config = ConfigUtil.getConfig("messages" + File.separator + "messages_" + ConfigManager.lang +".yml"); + prefix = config.getString("messages.prefix", "messages.prefix is missing"); + reload = config.getString("messages.reload", "messages.reload is missing"); + nonArgs = config.getString("messages.none-args", "messages.none-args is missing"); + unavailableArgs = config.getString("messages.none-args", "messages.invalid-args is missing"); + escape = config.getString("messages.escape", "messages.escape is missing"); + noPerm = config.getString("messages.no-perm", "messages.no-perm is missing"); + notExist = config.getString("messages.not-exist", "messages.not-exist is missing"); + noConsole = config.getString("messages.no-console", "messages.no-console is missing"); + wrongAmount = config.getString("messages.wrong-amount", "messages.wrong-amount is missing"); + lackArgs = config.getString("messages.lack-args", "messages.lack-args is missing"); + notOnline = config.getString("messages.not-online", "messages.not-online is missing"); + giveItem = config.getString("messages.give-item", "messages.give-item is missing"); + getItem = config.getString("messages.get-item", "messages.get-item is missing"); + coolDown = config.getString("messages.cooldown", "messages.cooldown is missing"); + possibleLoots = config.getString("messages.possible-loots", "messages.possible-loots is missing"); + splitChar = config.getString("messages.split-char", "messages.split-char is missing"); + noLoot = config.getString("messages.no-loot", "messages.no-loot is missing"); + notOpenWater = config.getString("messages.not-open-water", "messages.not-open-water is missing"); + competitionOn = config.getString("messages.competition-ongoing", "messages.competition-ongoing is missing"); + notEnoughPlayers = config.getString("messages.players-not-enough", "messages.players-not-enough is missing"); + noRank = config.getString("messages.no-rank", "messages.no-rank is missing"); + forceSuccess = config.getString("messages.force-competition-success", "messages.force-competition-success is missing"); + forceFailure = config.getString("messages.force-competition-failure", "messages.force-competition-failure is missing"); + forceEnd = config.getString("messages.force-competition-end", "messages.force-competition-end is missing"); + forceCancel = config.getString("messages.force-competition-cancel","messages.force-competition-cancel is messing"); + noPlayer = config.getString("messages.no-player", "messages.no-player is missing"); + noScore = config.getString("messages.no-score", "messages.no-score is missing"); + noRod = config.getString("messages.no-rod", "messages.no-rod is missing"); + hookOther = config.getString("messages.hook-other-entity","messages.hook-other-entity is missing"); + } +} diff --git a/src/main/java/net/momirealms/customfishing/manager/TotemManager.java b/src/main/java/net/momirealms/customfishing/manager/TotemManager.java new file mode 100644 index 00000000..a96f9c90 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/manager/TotemManager.java @@ -0,0 +1,9 @@ +package net.momirealms.customfishing.manager; + +import java.util.HashMap; + +public class TotemManager { + + public static HashMap TOTEMS; + +} diff --git a/src/main/java/net/momirealms/customfishing/object/Bonus.java b/src/main/java/net/momirealms/customfishing/object/Bonus.java index 445ff36b..30818021 100644 --- a/src/main/java/net/momirealms/customfishing/object/Bonus.java +++ b/src/main/java/net/momirealms/customfishing/object/Bonus.java @@ -1,30 +1,32 @@ package net.momirealms.customfishing.object; import java.util.HashMap; +import java.util.Map; +import java.util.Optional; public class Bonus { - private HashMap weightMQ; - private HashMap weightPM; + private HashMap weightMD; + private HashMap weightAS; private double time; private double score; private int difficulty; private double doubleLoot; - public HashMap getWeightMQ() { - return weightMQ; + public HashMap getWeightMD() { + return weightMD; } - public void setWeightMQ(HashMap weightMQ) { - this.weightMQ = weightMQ; + public void setWeightMD(HashMap weightMD) { + this.weightMD = weightMD; } - public HashMap getWeightPM() { - return weightPM; + public HashMap getWeightAS() { + return weightAS; } - public void setWeightPM(HashMap weightPM) { - this.weightPM = weightPM; + public void setWeightAS(HashMap weightAS) { + this.weightAS = weightAS; } public double getTime() { @@ -58,4 +60,25 @@ public class Bonus { public void setDoubleLoot(double doubleLoot) { this.doubleLoot = doubleLoot; } -} + + public void addBonus(Bonus anotherBonus) { + HashMap weightAS = anotherBonus.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(); + 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(); + if (anotherBonus.getDoubleLoot() != 0) this.doubleLoot += anotherBonus.getDoubleLoot(); + if (anotherBonus.getDifficulty() != 0) this.difficulty += anotherBonus.getDifficulty(); + if (anotherBonus.getScore() != 0) this.score *= anotherBonus.getScore(); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/object/Difficulty.java b/src/main/java/net/momirealms/customfishing/object/Difficulty.java index 103b77c6..a2becbe0 100644 --- a/src/main/java/net/momirealms/customfishing/object/Difficulty.java +++ b/src/main/java/net/momirealms/customfishing/object/Difficulty.java @@ -19,11 +19,13 @@ package net.momirealms.customfishing.object; public record Difficulty(int timer, int speed) { - public int getTimer() { - return this.timer; + @Override + public int timer() { + return timer; } - public int getSpeed() { - return this.speed; + @Override + public int speed() { + return speed; } } diff --git a/src/main/java/net/momirealms/customfishing/object/FishResult.java b/src/main/java/net/momirealms/customfishing/object/FishResult.java new file mode 100644 index 00000000..aa0a4cbe --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/FishResult.java @@ -0,0 +1,9 @@ +package net.momirealms.customfishing.object; + +public enum FishResult { + + FAILURE, + CAUGHT_MOB, + CAUGHT_LOOT, + CAUGHT_VANILLA +} diff --git a/src/main/java/net/momirealms/customfishing/requirements/FishingCondition.java b/src/main/java/net/momirealms/customfishing/object/FishingCondition.java similarity index 74% rename from src/main/java/net/momirealms/customfishing/requirements/FishingCondition.java rename to src/main/java/net/momirealms/customfishing/object/FishingCondition.java index 0757ff31..8111fcab 100644 --- a/src/main/java/net/momirealms/customfishing/requirements/FishingCondition.java +++ b/src/main/java/net/momirealms/customfishing/object/FishingCondition.java @@ -15,10 +15,11 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.requirements; +package net.momirealms.customfishing.object; -import net.momirealms.customfishing.ConfigReader; -import net.momirealms.customfishing.hook.PapiHook; +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.integration.papi.PlaceholderManager; +import net.momirealms.customfishing.object.requirements.CustomPapi; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -33,11 +34,12 @@ public class FishingCondition{ public FishingCondition(Location location, Player player) { this.location = location; this.player = player; - if (ConfigReader.Config.papi){ + PlaceholderManager placeholderManager = CustomFishing.plugin.getIntegrationManager().getPlaceholderManager(); + if (placeholderManager != null) { this.papiMap = new HashMap<>(); - CustomPapi.allPapi.forEach(papi -> { - this.papiMap.put(papi, PapiHook.parse(player, papi)); - }); + for (String papi : CustomPapi.allPapi) { + this.papiMap.put(papi, placeholderManager.parse(player, papi)); + } } } diff --git a/src/main/java/net/momirealms/customfishing/object/FishingPlayer.java b/src/main/java/net/momirealms/customfishing/object/FishingPlayer.java index 2c94c15a..faa7afb1 100644 --- a/src/main/java/net/momirealms/customfishing/object/FishingPlayer.java +++ b/src/main/java/net/momirealms/customfishing/object/FishingPlayer.java @@ -1,31 +1,109 @@ -/* - * 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; -import net.momirealms.customfishing.titlebar.Timer; +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 record FishingPlayer(Long fishingTime, Timer timer) { +public class FishingPlayer extends BukkitRunnable { - public Long getFishingTime() { - return this.fishingTime; + 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; + + public FishingPlayer(long deadline, Player player, Layout layout, Difficulty difficulty, FishingManager fishingManager, boolean isDouble) { + 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; } - public Timer getTimer() { - return this.timer; + @Override + public void run() { + + if (System.currentTimeMillis() > deadline) { + AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.escape); + fishingManager.removeFishingPlayer(player); + cancel(); + return; + } + + int timer = difficulty.timer() - 1; + int speed = difficulty.speed(); + if (progress <= speed - 1) { + face = true; + } else if (progress >= size - speed + 1) { + face = false; + } + if (internalTimer < timer) { + internalTimer++; + return; + } else { + if (face) { + internalTimer -= timer; + progress += speed; + } else { + internalTimer -= timer; + progress -= speed; + } + } + 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)); + } } -} \ No newline at end of file + + public boolean isSuccess() { + int last = progress / range; + return (Math.random() < successRate[last]); + } + + public boolean isDouble() { + return isDouble; + } +} diff --git a/src/main/java/net/momirealms/customfishing/object/Item.java b/src/main/java/net/momirealms/customfishing/object/Item.java index 04cabe1d..e9a834a7 100644 --- a/src/main/java/net/momirealms/customfishing/object/Item.java +++ b/src/main/java/net/momirealms/customfishing/object/Item.java @@ -1,5 +1,6 @@ package net.momirealms.customfishing.object; +import org.bukkit.Material; import org.bukkit.inventory.ItemFlag; import java.util.List; @@ -7,7 +8,7 @@ import java.util.Map; public class Item { - private final String material; + private final Material material; private String name; private List lore; private List itemFlags; @@ -16,19 +17,11 @@ public class Item { private List enchantment; private Map nbt; - public Item(String material) { + public Item(Material material) { this.material = material; } - public Map getNbt() { - return nbt; - } - - public void setNbt(Map nbt) { - this.nbt = nbt; - } - - public String getMaterial() { + public Material getMaterial() { return material; } @@ -79,4 +72,12 @@ public class Item { public void setEnchantment(List enchantment) { this.enchantment = enchantment; } -} + + public Map getNbt() { + return nbt; + } + + public void setNbt(Map nbt) { + this.nbt = nbt; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/object/Layout.java b/src/main/java/net/momirealms/customfishing/object/Layout.java index 654e6a20..47346c4f 100644 --- a/src/main/java/net/momirealms/customfishing/object/Layout.java +++ b/src/main/java/net/momirealms/customfishing/object/Layout.java @@ -22,37 +22,64 @@ 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; - private String start; - private String bar; - private String pointer; - private String offset; - private String end; - private String pointerOffset; - private String title; - - public Layout(int range, double[] successRate, int size){ + 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 void setBar(String bar) {this.bar = bar;} - public void setEnd(String end) {this.end = end;} - public void setOffset(String offset) {this.offset = offset;} - public void setPointer(String pointer) {this.pointer = pointer;} - public void setPointerOffset(String pointerOffset) {this.pointerOffset = pointerOffset;} - public void setStart(String start) {this.start = start;} - public void setTitle(String title) {this.title = title;} + public int getRange() { + return range; + } - public int getRange(){return this.range;} - public double[] getSuccessRate(){return this.successRate;} - public int getSize(){return this.size;} - public String getBar() {return bar;} - public String getEnd() {return end;} - public String getOffset() {return offset;} - public String getPointer() {return pointer;} - public String getPointerOffset() {return pointerOffset;} - public String getStart() {return start;} - public String getTitle() {return title;} + 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/LeveledEnchantment.java b/src/main/java/net/momirealms/customfishing/object/LeveledEnchantment.java index abd9340f..474dc42b 100644 --- a/src/main/java/net/momirealms/customfishing/object/LeveledEnchantment.java +++ b/src/main/java/net/momirealms/customfishing/object/LeveledEnchantment.java @@ -30,19 +30,9 @@ public class LeveledEnchantment { this.level = level; } - public void setChance(double chance) { - this.chance = chance; - } + public void setChance(double chance) {this.chance = chance;} - public int getLevel() { - return level; - } - - public NamespacedKey getKey() { - return key; - } - - public double getChance() { - return chance; - } + public int getLevel() {return level;} + public NamespacedKey getKey() {return key;} + public double getChance() {return chance;} } diff --git a/src/main/java/net/momirealms/customfishing/object/MobVector.java b/src/main/java/net/momirealms/customfishing/object/MobVector.java index 59abf6d5..0a3675d5 100644 --- a/src/main/java/net/momirealms/customfishing/object/MobVector.java +++ b/src/main/java/net/momirealms/customfishing/object/MobVector.java @@ -19,11 +19,13 @@ package net.momirealms.customfishing.object; public record MobVector(double horizontal, double vertical) { - public double getHorizontal() { - return this.horizontal; + @Override + public double horizontal() { + return horizontal; } - public double getVertical() { - return this.vertical; + @Override + public double vertical() { + return vertical; } } diff --git a/src/main/java/net/momirealms/customfishing/object/Modifier.java b/src/main/java/net/momirealms/customfishing/object/Modifier.java index e88d2b3c..a1af59c0 100644 --- a/src/main/java/net/momirealms/customfishing/object/Modifier.java +++ b/src/main/java/net/momirealms/customfishing/object/Modifier.java @@ -22,37 +22,28 @@ public class Modifier { private int difficulty; private double score; private boolean willDouble; - private boolean isVanilla; - - public int getDifficulty() { - return difficulty; - } public void setDifficulty(int difficulty) { this.difficulty = difficulty; } - public double getScore() { - return score; - } - public void setScore(double score) { this.score = score; } - public boolean isWillDouble() { - return willDouble; - } - public void setWillDouble(boolean willDouble) { this.willDouble = willDouble; } - public boolean isVanilla() { - return isVanilla; + public int getDifficulty() { + return difficulty; } - public void setVanilla(boolean vanilla) { - isVanilla = vanilla; + 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/Reflection.java b/src/main/java/net/momirealms/customfishing/object/Reflection.java new file mode 100644 index 00000000..0622e3b6 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/Reflection.java @@ -0,0 +1,32 @@ +/* + * 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; + +import java.lang.reflect.Field; + +public class Reflection { + + public static Object removeBar; + + public static void load() throws Exception{ + Class bar = Class.forName("net.minecraft.network.protocol.game.PacketPlayOutBoss"); + Field remove = bar.getDeclaredField("f"); + remove.setAccessible(true); + removeBar = remove.get(null); + } +} diff --git a/src/main/java/net/momirealms/customfishing/object/TextCache.java b/src/main/java/net/momirealms/customfishing/object/TextCache.java new file mode 100644 index 00000000..0ed3f820 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/TextCache.java @@ -0,0 +1,94 @@ +/* + * 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; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.integration.papi.PlaceholderManager; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class TextCache { + + //所属玩家 + private final Player owner; + //初始值 + private final String rawValue; + //原始文字加工后的值 + private String originalValue; + //最近一次替换值 + private String latestValue; + //持有者占位符 + private String[] ownerPlaceholders; + + public TextCache(Player owner, String rawValue) { + this.owner = owner; + this.rawValue = rawValue; + analyze(this.rawValue); + } + + private void analyze(String value) { + List placeholdersOwner = new ArrayList<>(CustomFishing.plugin.getIntegrationManager().getPlaceholderManager().detectPlaceholders(value)); + String origin = value; + for (String placeholder : placeholdersOwner) { + origin = origin.replace(placeholder, "%s"); + } + originalValue = origin; + ownerPlaceholders = placeholdersOwner.toArray(new String[0]); + latestValue = originalValue; + update(); + } + + public String getRawValue() { + return rawValue; + } + + public String updateAndGet() { + update(); + return getLatestValue(); + } + + public String getLatestValue() { + return latestValue; + } + + //返回更新结果是否不一致 + public boolean update() { + if (ownerPlaceholders.length == 0) return false; + PlaceholderManager placeholderManager = CustomFishing.plugin.getIntegrationManager().getPlaceholderManager(); + if (placeholderManager == null) return false; + String string; + if ("%s".equals(originalValue)) { + string = placeholderManager.parse(owner, ownerPlaceholders[0]); + } + else { + Object[] values = new String[ownerPlaceholders.length]; + for (int i = 0; i < ownerPlaceholders.length; i++) { + values[i] = placeholderManager.parse(owner, ownerPlaceholders[i]); + } + string = String.format(originalValue, values); + } + if (!latestValue.equals(string)) { + latestValue = string; + return true; + } + return false; + } + +} diff --git a/src/main/java/net/momirealms/customfishing/object/action/ActionB.java b/src/main/java/net/momirealms/customfishing/object/action/ActionInterface.java similarity index 76% rename from src/main/java/net/momirealms/customfishing/object/action/ActionB.java rename to src/main/java/net/momirealms/customfishing/object/action/ActionInterface.java index e4174825..327025c6 100644 --- a/src/main/java/net/momirealms/customfishing/object/action/ActionB.java +++ b/src/main/java/net/momirealms/customfishing/object/action/ActionInterface.java @@ -2,6 +2,8 @@ package net.momirealms.customfishing.object.action; import org.bukkit.entity.Player; -public interface ActionB { +public interface ActionInterface { + void doOn(Player player); + } diff --git a/src/main/java/net/momirealms/customfishing/object/action/CommandA.java b/src/main/java/net/momirealms/customfishing/object/action/CommandA.java deleted file mode 100644 index 7c976424..00000000 --- a/src/main/java/net/momirealms/customfishing/object/action/CommandA.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.momirealms.customfishing.object.action; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.util.List; - -public record CommandA(List commands, String nick) implements ActionB { - @Override - public void doOn(Player player) { - commands.forEach(command -> { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), - command. - replaceAll("\\{x}", String.valueOf(Math.round(player.getLocation().getX()))). - replaceAll("\\{y}", String.valueOf(Math.round(player.getLocation().getY()))). - replaceAll("\\{z}", String.valueOf(Math.round(player.getLocation().getZ()))). - replaceAll("\\{player}", player.getName()). - replaceAll("\\{world}", player.getWorld().getName()). - replaceAll("\\{loot}", nick) - ); - }); - } -} diff --git a/src/main/java/net/momirealms/customfishing/object/action/CommandActionImpl.java b/src/main/java/net/momirealms/customfishing/object/action/CommandActionImpl.java new file mode 100644 index 00000000..ef498a75 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/action/CommandActionImpl.java @@ -0,0 +1,28 @@ +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; + +public record CommandActionImpl(String[] commands, String nick) implements ActionInterface { + + public CommandActionImpl(String[] commands, @Nullable String nick) { + this.commands = commands; + this.nick = nick == null ? "" : nick; + } + + @Override + public void doOn(Player player) { + for (String command : commands) { + CustomFishing.plugin.getServer().dispatchCommand(Bukkit.getConsoleSender(), + command.replace("{player}", player.getName()) + .replace("{x}", String.valueOf(player.getLocation().getBlockX())) + .replace("{y}", String.valueOf(player.getLocation().getBlockY())) + .replace("{z}", String.valueOf(player.getLocation().getBlockZ())) + .replace("{loot}", nick) + .replace("{world}", player.getWorld().getName()) + ); + } + } +} diff --git a/src/main/java/net/momirealms/customfishing/object/action/CommandB.java b/src/main/java/net/momirealms/customfishing/object/action/CommandB.java deleted file mode 100644 index 98c4f16c..00000000 --- a/src/main/java/net/momirealms/customfishing/object/action/CommandB.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.momirealms.customfishing.object.action; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.util.List; - -public record CommandB(List commands) implements ActionB{ - - @Override - public void doOn(Player player) { - commands.forEach(command -> { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), - command. - replaceAll("\\{x}", String.valueOf(Math.round(player.getLocation().getX()))). - replaceAll("\\{y}", String.valueOf(Math.round(player.getLocation().getY()))). - replaceAll("\\{z}", String.valueOf(Math.round(player.getLocation().getZ()))). - replaceAll("\\{player}", player.getName()). - replaceAll("\\{world}", player.getWorld().getName()) - ); - }); - } -} diff --git a/src/main/java/net/momirealms/customfishing/object/action/FishingXPB.java b/src/main/java/net/momirealms/customfishing/object/action/FishingXPB.java deleted file mode 100644 index 5d5ced72..00000000 --- a/src/main/java/net/momirealms/customfishing/object/action/FishingXPB.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.momirealms.customfishing.object.action; - -import net.momirealms.customfishing.ConfigReader; -import org.bukkit.entity.Player; - -public record FishingXPB(int amount) implements ActionB { - - @Override - public void doOn(Player player) { - if (ConfigReader.Config.skillXP != null){ - ConfigReader.Config.skillXP.addXp(player, amount); - } - } -} diff --git a/src/main/java/net/momirealms/customfishing/object/action/MessageA.java b/src/main/java/net/momirealms/customfishing/object/action/MessageA.java deleted file mode 100644 index fdb5196d..00000000 --- a/src/main/java/net/momirealms/customfishing/object/action/MessageA.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.momirealms.customfishing.object.action; - -import net.momirealms.customfishing.utils.AdventureUtil; -import org.bukkit.entity.Player; - -import java.util.List; - -public record MessageA(List messages, String loot) implements ActionB{ - - @Override - public void doOn(Player player) { - messages.forEach(message -> { - AdventureUtil.playerMessage(player, message.replace("{loot}", loot)); - }); - } -} diff --git a/src/main/java/net/momirealms/customfishing/object/action/MessageActionImpl.java b/src/main/java/net/momirealms/customfishing/object/action/MessageActionImpl.java new file mode 100644 index 00000000..34c58880 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/action/MessageActionImpl.java @@ -0,0 +1,25 @@ +package net.momirealms.customfishing.object.action; + +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.entity.Player; + +public record MessageActionImpl(String[] messages, String nick) implements ActionInterface { + + public MessageActionImpl(String[] messages, String nick) { + this.messages = messages; + this.nick = nick == null ? "" : nick; + } + + @Override + public void doOn(Player player) { + for (String message : messages) { + AdventureUtil.playerMessage(player, + message.replace("{player}", player.getName()) + .replace("{world}", player.getWorld().getName()) + .replace("{x}", String.valueOf(player.getLocation().getBlockX())) + .replace("{y}", String.valueOf(player.getLocation().getBlockY())) + .replace("{z}", String.valueOf(player.getLocation().getBlockZ())) + .replace("{loot}", nick)); + } + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/object/action/MessageB.java b/src/main/java/net/momirealms/customfishing/object/action/MessageB.java deleted file mode 100644 index 49dba969..00000000 --- a/src/main/java/net/momirealms/customfishing/object/action/MessageB.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.momirealms.customfishing.object.action; - -import net.momirealms.customfishing.utils.AdventureUtil; -import org.bukkit.entity.Player; - -import java.util.List; - -public record MessageB(List messages) implements ActionB { - - @Override - public void doOn(Player player) { - messages.forEach(message -> { - AdventureUtil.playerMessage(player, message); - }); - } -} diff --git a/src/main/java/net/momirealms/customfishing/object/action/SkillXPImpl.java b/src/main/java/net/momirealms/customfishing/object/action/SkillXPImpl.java new file mode 100644 index 00000000..f3d1db42 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/action/SkillXPImpl.java @@ -0,0 +1,12 @@ +package net.momirealms.customfishing.object.action; + +import net.momirealms.customfishing.CustomFishing; +import org.bukkit.entity.Player; + +public record SkillXPImpl(double amount) implements ActionInterface { + + @Override + public void doOn(Player player) { + CustomFishing.plugin.getIntegrationManager().getSkillInterface().addXp(player, amount); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/object/action/SoundActionImpl.java b/src/main/java/net/momirealms/customfishing/object/action/SoundActionImpl.java new file mode 100644 index 00000000..4e14e0cf --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/action/SoundActionImpl.java @@ -0,0 +1,14 @@ +package net.momirealms.customfishing.object.action; + +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.entity.Player; + +public record SoundActionImpl(String sound) implements ActionInterface { + + @Override + public void doOn(Player player) { + AdventureUtil.playerSound(player, Sound.Source.PLAYER, Key.key(sound), 1, 1); + } +} diff --git a/src/main/java/net/momirealms/customfishing/object/action/VanillaXPImpl.java b/src/main/java/net/momirealms/customfishing/object/action/VanillaXPImpl.java new file mode 100644 index 00000000..50546ba9 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/action/VanillaXPImpl.java @@ -0,0 +1,15 @@ +package net.momirealms.customfishing.object.action; + +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.momirealms.customfishing.util.AdventureUtil; +import org.bukkit.entity.Player; + +public record VanillaXPImpl(int amount, boolean mending) implements ActionInterface { + + @Override + public void doOn(Player player) { + player.giveExp(amount, mending); + AdventureUtil.playerSound(player, Sound.Source.PLAYER, Key.key("minecraft:entity.experience_orb.pickup"), 1, 1); + } +} diff --git a/src/main/java/net/momirealms/customfishing/object/action/XPA.java b/src/main/java/net/momirealms/customfishing/object/action/XPA.java deleted file mode 100644 index 8e50e653..00000000 --- a/src/main/java/net/momirealms/customfishing/object/action/XPA.java +++ /dev/null @@ -1,17 +0,0 @@ -package net.momirealms.customfishing.object.action; - -import net.kyori.adventure.key.Key; -import net.momirealms.customfishing.ConfigReader; -import net.momirealms.customfishing.utils.AdventureUtil; -import org.bukkit.Sound; -import org.bukkit.entity.Player; - -public record XPA(int amount) implements ActionB { - - @Override - public void doOn(Player player) { - if (ConfigReader.Config.isSpigot) player.giveExp(amount); - else player.giveExp(amount, true); - AdventureUtil.playerSound(player, net.kyori.adventure.sound.Sound.Source.PLAYER, Key.key("minecraft:entity.experience_orb.pickup")); - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/object/action/XPB.java b/src/main/java/net/momirealms/customfishing/object/action/XPB.java deleted file mode 100644 index 565f718a..00000000 --- a/src/main/java/net/momirealms/customfishing/object/action/XPB.java +++ /dev/null @@ -1,17 +0,0 @@ -package net.momirealms.customfishing.object.action; - -import net.kyori.adventure.key.Key; -import net.momirealms.customfishing.ConfigReader; -import net.momirealms.customfishing.utils.AdventureUtil; -import org.bukkit.Sound; -import org.bukkit.entity.Player; - -public record XPB(int amount) implements ActionB { - - @Override - public void doOn(Player player) { - if (ConfigReader.Config.isSpigot) player.giveExp(amount); - else player.giveExp(amount, false); - AdventureUtil.playerSound(player, net.kyori.adventure.sound.Sound.Source.PLAYER, Key.key("minecraft:entity.experience_orb.pickup")); - } -} diff --git a/src/main/java/net/momirealms/customfishing/object/loot/DroppedItem.java b/src/main/java/net/momirealms/customfishing/object/loot/DroppedItem.java index 5109e792..160173d6 100644 --- a/src/main/java/net/momirealms/customfishing/object/loot/DroppedItem.java +++ b/src/main/java/net/momirealms/customfishing/object/loot/DroppedItem.java @@ -1,18 +1,18 @@ package net.momirealms.customfishing.object.loot; +import net.momirealms.customfishing.object.Difficulty; import net.momirealms.customfishing.object.LeveledEnchantment; - -import java.util.List; +import org.jetbrains.annotations.Nullable; public class DroppedItem extends Loot{ - boolean randomDurability; - List randomEnchants; - String type; - String id; + private boolean randomDurability; + private LeveledEnchantment[] randomEnchants; + private final String material; - public DroppedItem(String key) { - super(key); + public DroppedItem(String key, Difficulty difficulty, int time, int weight, String material) { + super(key, difficulty, time, weight); + this.material = material; } public boolean isRandomDurability() { @@ -23,27 +23,16 @@ public class DroppedItem extends Loot{ this.randomDurability = randomDurability; } - public List getRandomEnchants() { + @Nullable + public LeveledEnchantment[] getRandomEnchants() { return randomEnchants; } - public void setRandomEnchants(List randomEnchants) { + public void setRandomEnchants(LeveledEnchantment[] randomEnchants) { this.randomEnchants = randomEnchants; } - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; + public String getMaterial() { + return material; } } diff --git a/src/main/java/net/momirealms/customfishing/object/loot/Loot.java b/src/main/java/net/momirealms/customfishing/object/loot/Loot.java index 6255b6b3..154bf186 100644 --- a/src/main/java/net/momirealms/customfishing/object/loot/Loot.java +++ b/src/main/java/net/momirealms/customfishing/object/loot/Loot.java @@ -1,63 +1,38 @@ package net.momirealms.customfishing.object.loot; import net.momirealms.customfishing.object.Difficulty; -import net.momirealms.customfishing.object.action.ActionB; -import net.momirealms.customfishing.requirements.Requirement; - -import java.util.List; +import net.momirealms.customfishing.object.Layout; +import net.momirealms.customfishing.object.action.ActionInterface; +import net.momirealms.customfishing.object.requirements.RequirementInterface; public class Loot { - String key; - String nick; - Difficulty difficulty; - String group; - boolean showInFinder; - List layout; - List successActions; - List failureActions; - List hookActions; - int weight; - int time; - List requirements; - double score; + public static Loot EMPTY = new Loot("empty", new Difficulty(1,1), 5000, 10); - public Loot(String key) { + protected String key; + protected String nick; + protected Difficulty difficulty; + protected String group; + protected boolean showInFinder; + protected Layout[] layout; + protected ActionInterface[] successActions; + protected ActionInterface[] failureActions; + protected ActionInterface[] hookActions; + protected int weight; + protected int time; + protected RequirementInterface[] requirements; + protected double score; + + public Loot(String key, Difficulty difficulty, int time, int weight) { this.key = key; - } - - public List getHookActions() { - return hookActions; - } - - public void setHookActions(List hookActions) { - this.hookActions = hookActions; + this.difficulty = difficulty; + this.time = time; + this.weight = weight; } public String getKey() { return key; } - - public void setKey(String key) { - this.key = key; - } - - public List getSuccessActions() { - return successActions; - } - - public void setSuccessActions(List successActions) { - this.successActions = successActions; - } - - public List getFailureActions() { - return failureActions; - } - - public void setFailureActions(List failureActions) { - this.failureActions = failureActions; - } - public String getNick() { return nick; } @@ -66,14 +41,6 @@ public class Loot { this.nick = nick; } - public List getLayout() { - return layout; - } - - public void setLayout(List layout) { - this.layout = layout; - } - public Difficulty getDifficulty() { return difficulty; } @@ -98,12 +65,40 @@ public class Loot { this.showInFinder = showInFinder; } - public int getWeight() { - return weight; + public Layout[] getLayout() { + return layout; } - public void setWeight(int weight) { - this.weight = weight; + public void setLayout(Layout[] layout) { + this.layout = layout; + } + + public ActionInterface[] getSuccessActions() { + return successActions; + } + + public void setSuccessActions(ActionInterface[] successActions) { + this.successActions = successActions; + } + + public ActionInterface[] getFailureActions() { + return failureActions; + } + + public void setFailureActions(ActionInterface[] failureActions) { + this.failureActions = failureActions; + } + + public ActionInterface[] getHookActions() { + return hookActions; + } + + public void setHookActions(ActionInterface[] hookActions) { + this.hookActions = hookActions; + } + + public int getWeight() { + return weight; } public int getTime() { @@ -114,11 +109,11 @@ public class Loot { this.time = time; } - public List getRequirements() { + public RequirementInterface[] getRequirements() { return requirements; } - public void setRequirements(List requirements) { + public void setRequirements(RequirementInterface[] requirements) { this.requirements = requirements; } diff --git a/src/main/java/net/momirealms/customfishing/object/loot/Mob.java b/src/main/java/net/momirealms/customfishing/object/loot/Mob.java index aaf94a11..fa9e0703 100644 --- a/src/main/java/net/momirealms/customfishing/object/loot/Mob.java +++ b/src/main/java/net/momirealms/customfishing/object/loot/Mob.java @@ -1,35 +1,32 @@ package net.momirealms.customfishing.object.loot; +import net.momirealms.customfishing.object.Difficulty; import net.momirealms.customfishing.object.MobVector; +import org.jetbrains.annotations.NotNull; public class Mob extends Loot{ - final String mmID; - int mmLevel; - MobVector mobVector; + private final String mobID; + private final int mobLevel; + private final MobVector mobVector; - public Mob(String key, String mmID) { - super(key); - this.mmID = mmID; + public Mob(String key, Difficulty difficulty, int time, int weight, String mobID, int level, MobVector vector) { + super(key, difficulty, time, weight); + this.mobID = mobID; + this.mobLevel = level; + this.mobVector = vector; } - public String getMmID() { - return mmID; + public String getMobID() { + return mobID; } - public int getMmLevel() { - return mmLevel; - } - - public void setMmLevel(int mmLevel) { - this.mmLevel = mmLevel; + public int getMobLevel() { + return mobLevel; } + @NotNull public MobVector getMobVector() { return mobVector; } - - public void setMobVector(MobVector mobVector) { - this.mobVector = mobVector; - } } diff --git a/src/main/java/net/momirealms/customfishing/requirements/Biome.java b/src/main/java/net/momirealms/customfishing/object/requirements/BiomeImpl.java similarity index 84% rename from src/main/java/net/momirealms/customfishing/requirements/Biome.java rename to src/main/java/net/momirealms/customfishing/object/requirements/BiomeImpl.java index 252e9498..13022998 100644 --- a/src/main/java/net/momirealms/customfishing/requirements/Biome.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/BiomeImpl.java @@ -15,15 +15,13 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.requirements; +package net.momirealms.customfishing.object.requirements; + +import net.momirealms.customfishing.object.FishingCondition; import java.util.List; -public record Biome(List biomes) implements Requirement { - - public List getBiomes() { - return this.biomes; - } +public record BiomeImpl(List biomes) implements RequirementInterface { @Override public boolean isConditionMet(FishingCondition fishingCondition) { diff --git a/src/main/java/net/momirealms/customfishing/requirements/CustomPapi.java b/src/main/java/net/momirealms/customfishing/object/requirements/CustomPapi.java similarity index 51% rename from src/main/java/net/momirealms/customfishing/requirements/CustomPapi.java rename to src/main/java/net/momirealms/customfishing/object/requirements/CustomPapi.java index 13a2f608..b7a803e3 100644 --- a/src/main/java/net/momirealms/customfishing/requirements/CustomPapi.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/CustomPapi.java @@ -1,14 +1,34 @@ -package net.momirealms.customfishing.requirements; +/* + * 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 . + */ -import net.momirealms.customfishing.requirements.papi.*; +package net.momirealms.customfishing.object.requirements; + +import net.momirealms.customfishing.object.FishingCondition; +import net.momirealms.customfishing.object.requirements.papi.*; import org.bukkit.configuration.MemorySection; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; -public class CustomPapi implements Requirement { +public class CustomPapi implements RequirementInterface { public static HashSet allPapi = new HashSet<>(); - private PapiRequirement papiRequirement; public CustomPapi(Map expressions){ @@ -30,8 +50,11 @@ public class CustomPapi implements Requirement { else { if (expressions.get(key) instanceof MemorySection map){ String type = map.getString("type"); + if (type == null) return; String papi = map.getString("papi"); + if (papi == null) return; String value = map.getString("value"); + if (value == null) return; allPapi.add(papi); switch (type){ case "==" -> papiRequirement = new PapiEquals(papi, value); @@ -47,69 +70,49 @@ public class CustomPapi implements Requirement { } @Override - public boolean isConditionMet(FishingCondition fishingCondition) { - return papiRequirement.isMet(fishingCondition.getPapiMap()); + public boolean isConditionMet(FishingCondition plantingCondition) { + return papiRequirement.isMet(plantingCondition.getPapiMap()); } private void addAndRequirements(List requirements, Map map){ - List andRequirements = new ArrayList<>(); - map.keySet().forEach(key -> { - if (key.startsWith("&&")){ - if (map.get(key) instanceof MemorySection map2){ - addAndRequirements(andRequirements, map2.getValues(false)); - } - }else if (key.startsWith("||")){ - if (map.get(key) instanceof MemorySection map2){ - addOrRequirements(andRequirements, map2.getValues(false)); - } - }else { - if (map.get(key) instanceof MemorySection map2){ - String type = map2.getString("type"); - String papi = map2.getString("papi"); - String value = map2.getString("value"); - allPapi.add(papi); - switch (type){ - case "==" -> andRequirements.add(new PapiEquals(papi, value)); - case "!=" -> andRequirements.add(new PapiNotEquals(papi, value)); - case ">=" -> andRequirements.add(new PapiNoLess(papi, Double.parseDouble(value))); - case "<=" -> andRequirements.add(new PapiNoLarger(papi, Double.parseDouble(value))); - case "<" -> andRequirements.add(new PapiSmaller(papi, Double.parseDouble(value))); - case ">" -> andRequirements.add(new PapiGreater(papi, Double.parseDouble(value))); - } - } - } - }); - requirements.add(new ExpressionAnd(andRequirements)); + requirements.add(new ExpressionAnd(getRequirements(map))); } private void addOrRequirements(List requirements, Map map){ - List orRequirements = new ArrayList<>(); + requirements.add(new ExpressionOr(getRequirements(map))); + } + + private List getRequirements(Map map) { + List papiRequirements = new ArrayList<>(); map.keySet().forEach(key -> { if (key.startsWith("&&")){ if (map.get(key) instanceof MemorySection map2){ - addAndRequirements(orRequirements, map2.getValues(false)); + addAndRequirements(papiRequirements, map2.getValues(false)); } }else if (key.startsWith("||")){ if (map.get(key) instanceof MemorySection map2){ - addOrRequirements(orRequirements, map2.getValues(false)); + addOrRequirements(papiRequirements, map2.getValues(false)); } }else { if (map.get(key) instanceof MemorySection map2){ String type = map2.getString("type"); + if (type == null) return; String papi = map2.getString("papi"); + if (papi == null) return; String value = map2.getString("value"); + if (value == null) return; allPapi.add(papi); switch (type){ - case "==" -> orRequirements.add(new PapiEquals(papi, value)); - case "!=" -> orRequirements.add(new PapiNotEquals(papi, value)); - case ">=" -> orRequirements.add(new PapiNoLess(papi, Double.parseDouble(value))); - case "<=" -> orRequirements.add(new PapiNoLarger(papi, Double.parseDouble(value))); - case "<" -> orRequirements.add(new PapiSmaller(papi, Double.parseDouble(value))); - case ">" -> orRequirements.add(new PapiGreater(papi, Double.parseDouble(value))); + case "==" -> papiRequirements.add(new PapiEquals(papi, value)); + case "!=" -> papiRequirements.add(new PapiNotEquals(papi, value)); + case ">=" -> papiRequirements.add(new PapiNoLess(papi, Double.parseDouble(value))); + case "<=" -> papiRequirements.add(new PapiNoLarger(papi, Double.parseDouble(value))); + case "<" -> papiRequirements.add(new PapiSmaller(papi, Double.parseDouble(value))); + case ">" -> papiRequirements.add(new PapiGreater(papi, Double.parseDouble(value))); } } } }); - requirements.add(new ExpressionOr(orRequirements)); + return papiRequirements; } } diff --git a/src/main/java/net/momirealms/customfishing/requirements/Permission.java b/src/main/java/net/momirealms/customfishing/object/requirements/PermissionImpl.java similarity index 82% rename from src/main/java/net/momirealms/customfishing/requirements/Permission.java rename to src/main/java/net/momirealms/customfishing/object/requirements/PermissionImpl.java index 8f31dd06..c2ffd19f 100644 --- a/src/main/java/net/momirealms/customfishing/requirements/Permission.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/PermissionImpl.java @@ -15,9 +15,11 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.requirements; +package net.momirealms.customfishing.object.requirements; -public record Permission(String permission) implements Requirement { +import net.momirealms.customfishing.object.FishingCondition; + +public record PermissionImpl(String permission) implements RequirementInterface { public String getPermission() { return this.permission; diff --git a/src/main/java/net/momirealms/customfishing/requirements/Requirement.java b/src/main/java/net/momirealms/customfishing/object/requirements/RequirementInterface.java similarity index 82% rename from src/main/java/net/momirealms/customfishing/requirements/Requirement.java rename to src/main/java/net/momirealms/customfishing/object/requirements/RequirementInterface.java index 5d74eb63..c772f3db 100644 --- a/src/main/java/net/momirealms/customfishing/requirements/Requirement.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/RequirementInterface.java @@ -15,8 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.requirements; +package net.momirealms.customfishing.object.requirements; -public interface Requirement { +import net.momirealms.customfishing.object.FishingCondition; + +public interface RequirementInterface { boolean isConditionMet(FishingCondition fishingCondition); } diff --git a/src/main/java/net/momirealms/customfishing/requirements/Season.java b/src/main/java/net/momirealms/customfishing/object/requirements/SeasonImpl.java similarity index 63% rename from src/main/java/net/momirealms/customfishing/requirements/Season.java rename to src/main/java/net/momirealms/customfishing/object/requirements/SeasonImpl.java index 3e951f83..53cbe59b 100644 --- a/src/main/java/net/momirealms/customfishing/requirements/Season.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/SeasonImpl.java @@ -15,21 +15,21 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.requirements; +package net.momirealms.customfishing.object.requirements; -import net.momirealms.customfishing.ConfigReader; +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.integration.SeasonInterface; +import net.momirealms.customfishing.object.FishingCondition; import java.util.List; -public record Season(List seasons) implements Requirement { - - public List getSeasons() { - return this.seasons; - } +public record SeasonImpl(List seasons) implements RequirementInterface { @Override public boolean isConditionMet(FishingCondition fishingCondition) { - String currentSeason = ConfigReader.Config.season.getSeason(fishingCondition.getLocation().getWorld()); + SeasonInterface seasonInterface = CustomFishing.plugin.getIntegrationManager().getSeasonInterface(); + if (seasonInterface == null) return true; + String currentSeason = seasonInterface.getSeason(fishingCondition.getLocation().getWorld()); for (String season : seasons) { if (season.equalsIgnoreCase(currentSeason)) { return true; diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/SkillLevelImpl.java b/src/main/java/net/momirealms/customfishing/object/requirements/SkillLevelImpl.java new file mode 100644 index 00000000..51c5a1ea --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/requirements/SkillLevelImpl.java @@ -0,0 +1,13 @@ +package net.momirealms.customfishing.object.requirements; + +import net.momirealms.customfishing.CustomFishing; +import net.momirealms.customfishing.object.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/requirements/Time.java b/src/main/java/net/momirealms/customfishing/object/requirements/TimeImpl.java similarity index 81% rename from src/main/java/net/momirealms/customfishing/requirements/Time.java rename to src/main/java/net/momirealms/customfishing/object/requirements/TimeImpl.java index 3d8d1a3a..a77d9b44 100644 --- a/src/main/java/net/momirealms/customfishing/requirements/Time.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/TimeImpl.java @@ -15,17 +15,15 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.requirements; +package net.momirealms.customfishing.object.requirements; +import net.momirealms.customfishing.object.FishingCondition; +import net.momirealms.customfishing.object.requirements.RequirementInterface; import org.apache.commons.lang.StringUtils; import java.util.List; -public record Time(List times) implements Requirement{ - - public List getTimes() { - return this.times; - } +public record TimeImpl(List times) implements RequirementInterface { @Override public boolean isConditionMet(FishingCondition fishingCondition) { diff --git a/src/main/java/net/momirealms/customfishing/requirements/Weather.java b/src/main/java/net/momirealms/customfishing/object/requirements/WeatherImpl.java similarity index 70% rename from src/main/java/net/momirealms/customfishing/requirements/Weather.java rename to src/main/java/net/momirealms/customfishing/object/requirements/WeatherImpl.java index a3fe5f6e..1ef62da4 100644 --- a/src/main/java/net/momirealms/customfishing/requirements/Weather.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/WeatherImpl.java @@ -15,31 +15,23 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.requirements; +package net.momirealms.customfishing.object.requirements; -import net.momirealms.customfishing.utils.AdventureUtil; +import net.momirealms.customfishing.object.FishingCondition; import org.bukkit.World; import java.util.List; -public record Weather(List weathers) implements Requirement { - - public List getWeathers() { - return this.weathers; - } +public record WeatherImpl(List weathers) implements RequirementInterface { @Override public boolean isConditionMet(FishingCondition fishingCondition) { World world = fishingCondition.getLocation().getWorld(); if (world != null) { String currentWeather; - if (world.isThundering()) { - currentWeather = "thunder"; - } else if (world.isClearWeather()) { - currentWeather = "clear"; - } else { - currentWeather = "rain"; - } + if (world.isThundering()) currentWeather = "thunder"; + else if (world.isClearWeather()) currentWeather = "clear"; + else currentWeather = "rain"; for (String weather : weathers) { if (weather.equalsIgnoreCase(currentWeather)) { return true; diff --git a/src/main/java/net/momirealms/customfishing/requirements/World.java b/src/main/java/net/momirealms/customfishing/object/requirements/WorldImpl.java similarity index 80% rename from src/main/java/net/momirealms/customfishing/requirements/World.java rename to src/main/java/net/momirealms/customfishing/object/requirements/WorldImpl.java index 46da8dbf..a6731561 100644 --- a/src/main/java/net/momirealms/customfishing/requirements/World.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/WorldImpl.java @@ -15,17 +15,13 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.requirements; +package net.momirealms.customfishing.object.requirements; -import net.momirealms.customfishing.utils.AdventureUtil; +import net.momirealms.customfishing.object.FishingCondition; import java.util.List; -public record World(List worlds) implements Requirement { - - public List getWorlds() { - return this.worlds; - } +public record WorldImpl(List worlds) implements RequirementInterface { @Override public boolean isConditionMet(FishingCondition fishingCondition) { diff --git a/src/main/java/net/momirealms/customfishing/requirements/YPos.java b/src/main/java/net/momirealms/customfishing/object/requirements/YPosImpl.java similarity index 81% rename from src/main/java/net/momirealms/customfishing/requirements/YPos.java rename to src/main/java/net/momirealms/customfishing/object/requirements/YPosImpl.java index 2747e02b..409f5726 100644 --- a/src/main/java/net/momirealms/customfishing/requirements/YPos.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/YPosImpl.java @@ -15,17 +15,15 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.requirements; +package net.momirealms.customfishing.object.requirements; +import net.momirealms.customfishing.object.FishingCondition; +import net.momirealms.customfishing.object.requirements.RequirementInterface; import org.apache.commons.lang.StringUtils; import java.util.List; -public record YPos(List yPos) implements Requirement { - - public List getYPos() { - return this.yPos; - } +public record YPosImpl(List yPos) implements RequirementInterface { @Override public boolean isConditionMet(FishingCondition fishingCondition) { diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionAnd.java b/src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionAnd.java new file mode 100644 index 00000000..5755350c --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionAnd.java @@ -0,0 +1,32 @@ +/* + * 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.requirements.papi; + +import java.util.HashMap; +import java.util.List; + +public record ExpressionAnd(List requirements) implements PapiRequirement{ + + @Override + public boolean isMet(HashMap papiMap) { + for (PapiRequirement requirement : requirements) { + if (!requirement.isMet(papiMap)) return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionOr.java b/src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionOr.java new file mode 100644 index 00000000..357868dd --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/requirements/papi/ExpressionOr.java @@ -0,0 +1,32 @@ +/* + * 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.requirements.papi; + +import java.util.HashMap; +import java.util.List; + +public record ExpressionOr(List requirements) implements PapiRequirement{ + + @Override + public boolean isMet(HashMap papiMap) { + for (PapiRequirement requirement : requirements) { + if (requirement.isMet(papiMap)) return true; + } + return false; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiEquals.java b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiEquals.java new file mode 100644 index 00000000..5961ceb8 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiEquals.java @@ -0,0 +1,30 @@ +/* + * 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.requirements.papi; + +import java.util.HashMap; +import java.util.Objects; + +public record PapiEquals(String papi, String requirement) implements PapiRequirement{ + + @Override + public boolean isMet(HashMap papiMap) { + String value = papiMap.get(papi); + return Objects.equals(value, requirement); + } +} diff --git a/src/main/java/net/momirealms/customfishing/hook/PapiHook.java b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiGreater.java similarity index 66% rename from src/main/java/net/momirealms/customfishing/hook/PapiHook.java rename to src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiGreater.java index 9da7b399..405dec25 100644 --- a/src/main/java/net/momirealms/customfishing/hook/PapiHook.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiGreater.java @@ -15,13 +15,15 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.hook; +package net.momirealms.customfishing.object.requirements.papi; -import me.clip.placeholderapi.PlaceholderAPI; -import org.bukkit.entity.Player; +import java.util.HashMap; -public class PapiHook { - public static String parse(Player player, String text){ - return PlaceholderAPI.setPlaceholders(player, text); +public record PapiGreater(String papi, double requirement) implements PapiRequirement{ + + @Override + public boolean isMet(HashMap papiMap) { + double value = Double.parseDouble(papiMap.get(papi)); + return value > requirement; } } diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLarger.java b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLarger.java new file mode 100644 index 00000000..f78507df --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLarger.java @@ -0,0 +1,29 @@ +/* + * 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.requirements.papi; + +import java.util.HashMap; + +public record PapiNoLarger(String papi, double requirement) implements PapiRequirement{ + + @Override + public boolean isMet(HashMap papiMap) { + double value = Double.parseDouble(papiMap.get(papi)); + return value <= requirement; + } +} diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLess.java b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLess.java new file mode 100644 index 00000000..fd9f5acd --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNoLess.java @@ -0,0 +1,29 @@ +/* + * 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.requirements.papi; + +import java.util.HashMap; + +public record PapiNoLess(String papi, double requirement) implements PapiRequirement{ + + @Override + public boolean isMet(HashMap papiMap) { + double value = Double.parseDouble(papiMap.get(papi)); + return value >= requirement; + } +} diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNotEquals.java b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNotEquals.java new file mode 100644 index 00000000..69f3e2b0 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiNotEquals.java @@ -0,0 +1,30 @@ +/* + * 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.requirements.papi; + +import java.util.HashMap; +import java.util.Objects; + +public record PapiNotEquals(String papi, String requirement) implements PapiRequirement{ + + @Override + public boolean isMet(HashMap papiMap) { + String value = papiMap.get(papi); + return !Objects.equals(value, requirement); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/hook/skill/SkillXP.java b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiRequirement.java similarity index 78% rename from src/main/java/net/momirealms/customfishing/hook/skill/SkillXP.java rename to src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiRequirement.java index d8254002..a6e9d3c4 100644 --- a/src/main/java/net/momirealms/customfishing/hook/skill/SkillXP.java +++ b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiRequirement.java @@ -15,11 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.hook.skill; +package net.momirealms.customfishing.object.requirements.papi; -import org.bukkit.entity.Player; +import java.util.HashMap; -public interface SkillXP { - void addXp(Player player, double amount); - int getLevel(Player player); +public interface PapiRequirement { + boolean isMet(HashMap papiMap); } diff --git a/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiSmaller.java b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiSmaller.java new file mode 100644 index 00000000..7e282843 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/object/requirements/papi/PapiSmaller.java @@ -0,0 +1,29 @@ +/* + * 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.requirements.papi; + +import java.util.HashMap; + +public record PapiSmaller(String papi, double requirement) implements PapiRequirement{ + + @Override + public boolean isMet(HashMap papiMap) { + double value = Double.parseDouble(papiMap.get(papi)); + return value < requirement; + } +} diff --git a/src/main/java/net/momirealms/customfishing/requirements/Region.java b/src/main/java/net/momirealms/customfishing/requirements/Region.java deleted file mode 100644 index 76dc518a..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/Region.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.requirements; - -import com.sk89q.worldedit.bukkit.BukkitAdapter; -import com.sk89q.worldguard.WorldGuard; -import com.sk89q.worldguard.protection.ApplicableRegionSet; -import com.sk89q.worldguard.protection.regions.ProtectedRegion; -import com.sk89q.worldguard.protection.regions.RegionContainer; -import com.sk89q.worldguard.protection.regions.RegionQuery; - -import java.util.List; - -public record Region(List regions) implements Requirement { - - public List getRegions() { - return this.regions; - } - - @Override - public boolean isConditionMet(FishingCondition fishingCondition) { - RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); - RegionQuery query = container.createQuery(); - ApplicableRegionSet set = query.getApplicableRegions(BukkitAdapter.adapt(fishingCondition.getLocation())); - for (ProtectedRegion protectedRegion : set) { - if (regions.contains(protectedRegion.getId())) { - return true; - } - } - return false; - } -} diff --git a/src/main/java/net/momirealms/customfishing/requirements/SkillLevel.java b/src/main/java/net/momirealms/customfishing/requirements/SkillLevel.java deleted file mode 100644 index 35b716b4..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/SkillLevel.java +++ /dev/null @@ -1,10 +0,0 @@ -package net.momirealms.customfishing.requirements; - -import net.momirealms.customfishing.ConfigReader; - -public record SkillLevel(int level) implements Requirement{ - @Override - public boolean isConditionMet(FishingCondition fishingCondition) { - return level <= ConfigReader.Config.skillXP.getLevel(fishingCondition.getPlayer()); - } -} diff --git a/src/main/java/net/momirealms/customfishing/requirements/papi/ExpressionAnd.java b/src/main/java/net/momirealms/customfishing/requirements/papi/ExpressionAnd.java deleted file mode 100644 index 804f16a4..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/papi/ExpressionAnd.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.momirealms.customfishing.requirements.papi; - -import java.util.HashMap; -import java.util.List; - -public record ExpressionAnd(List requirements) implements PapiRequirement{ - - @Override - public boolean isMet(HashMap papiMap) { - for (PapiRequirement requirement : requirements) { - if (!requirement.isMet(papiMap)) return false; - } - return true; - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/requirements/papi/ExpressionOr.java b/src/main/java/net/momirealms/customfishing/requirements/papi/ExpressionOr.java deleted file mode 100644 index 3400333f..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/papi/ExpressionOr.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.momirealms.customfishing.requirements.papi; - -import java.util.HashMap; -import java.util.List; - -public record ExpressionOr(List requirements) implements PapiRequirement{ - - @Override - public boolean isMet(HashMap papiMap) { - for (PapiRequirement requirement : requirements) { - if (requirement.isMet(papiMap)) return true; - } - return false; - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiEquals.java b/src/main/java/net/momirealms/customfishing/requirements/papi/PapiEquals.java deleted file mode 100644 index 7515d309..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiEquals.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.momirealms.customfishing.requirements.papi; - -import java.util.HashMap; -import java.util.Objects; - -public record PapiEquals(String papi, String requirement) implements PapiRequirement{ - - @Override - public boolean isMet(HashMap papiMap) { - String value = papiMap.get(papi); - return Objects.equals(value, requirement); - } -} diff --git a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiGreater.java b/src/main/java/net/momirealms/customfishing/requirements/papi/PapiGreater.java deleted file mode 100644 index 8014abee..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiGreater.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.momirealms.customfishing.requirements.papi; - -import java.util.HashMap; - -public record PapiGreater(String papi, double requirement) implements PapiRequirement{ - - @Override - public boolean isMet(HashMap papiMap) { - double value = Double.parseDouble(papiMap.get(papi)); - return value > requirement; - } -} diff --git a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiNoLarger.java b/src/main/java/net/momirealms/customfishing/requirements/papi/PapiNoLarger.java deleted file mode 100644 index f80a5d8d..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiNoLarger.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.momirealms.customfishing.requirements.papi; - -import java.util.HashMap; - -public record PapiNoLarger(String papi, double requirement) implements PapiRequirement{ - - @Override - public boolean isMet(HashMap papiMap) { - double value = Double.parseDouble(papiMap.get(papi)); - return value <= requirement; - } -} diff --git a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiNoLess.java b/src/main/java/net/momirealms/customfishing/requirements/papi/PapiNoLess.java deleted file mode 100644 index ef2b51fa..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiNoLess.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.momirealms.customfishing.requirements.papi; - -import java.util.HashMap; - -public record PapiNoLess(String papi, double requirement) implements PapiRequirement{ - - @Override - public boolean isMet(HashMap papiMap) { - double value = Double.parseDouble(papiMap.get(papi)); - return value >= requirement; - } -} diff --git a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiNotEquals.java b/src/main/java/net/momirealms/customfishing/requirements/papi/PapiNotEquals.java deleted file mode 100644 index 5cf45bff..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiNotEquals.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.momirealms.customfishing.requirements.papi; - -import java.util.HashMap; -import java.util.Objects; - -public record PapiNotEquals(String papi, String requirement) implements PapiRequirement{ - - @Override - public boolean isMet(HashMap papiMap) { - String value = papiMap.get(papi); - return !Objects.equals(value, requirement); - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiRequirement.java b/src/main/java/net/momirealms/customfishing/requirements/papi/PapiRequirement.java deleted file mode 100644 index a022bf1a..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiRequirement.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.momirealms.customfishing.requirements.papi; - -import java.util.HashMap; - -public interface PapiRequirement { - boolean isMet(HashMap papiMap); -} diff --git a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiSmaller.java b/src/main/java/net/momirealms/customfishing/requirements/papi/PapiSmaller.java deleted file mode 100644 index 94f86ce4..00000000 --- a/src/main/java/net/momirealms/customfishing/requirements/papi/PapiSmaller.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.momirealms.customfishing.requirements.papi; - -import java.util.HashMap; - -public record PapiSmaller(String papi, double requirement) implements PapiRequirement{ - - @Override - public boolean isMet(HashMap papiMap) { - double value = Double.parseDouble(papiMap.get(papi)); - return value < requirement; - } -} diff --git a/src/main/java/net/momirealms/customfishing/titlebar/Timer.java b/src/main/java/net/momirealms/customfishing/titlebar/Timer.java deleted file mode 100644 index e21d5b34..00000000 --- a/src/main/java/net/momirealms/customfishing/titlebar/Timer.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.titlebar; - -import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.object.Difficulty; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitTask; - -public class Timer { - - private final TimerTask timerTask; - private final BukkitTask task; - private final String layout; - - public Timer(Player player, Difficulty difficulty, String layout) { - this.layout = layout; - this.timerTask = new TimerTask(player, difficulty, layout); - this.task = timerTask.runTaskTimerAsynchronously(CustomFishing.instance, 0,1); - timerTask.setTaskID(task.getTaskId()); - } - - public TimerTask getTimerTask(){ return this.timerTask; } - public int getTaskID (){ return this.task.getTaskId(); } - public String getLayout(){return this.layout;} -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customfishing/titlebar/TimerTask.java b/src/main/java/net/momirealms/customfishing/titlebar/TimerTask.java deleted file mode 100644 index 6084cd00..00000000 --- a/src/main/java/net/momirealms/customfishing/titlebar/TimerTask.java +++ /dev/null @@ -1,134 +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.titlebar; - -import net.momirealms.customfishing.object.Layout; -import net.momirealms.customfishing.utils.AdventureUtil; -import net.momirealms.customfishing.ConfigReader; -import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.object.Difficulty; -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; -import org.bukkit.scheduler.BukkitScheduler; - -import static net.momirealms.customfishing.listener.FishListener.fishingPlayers; - -public class TimerTask extends BukkitRunnable { - - private final Player player; - private final Difficulty difficulty; - private int taskID; - private int progress; - private int internalTimer; - private final int size; - private boolean face; - private final BukkitScheduler bukkitScheduler; - - 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 TimerTask(Player player, Difficulty difficulty, String layout){ - this.player = player; - this.difficulty = difficulty; - this.progress = 0; - this.internalTimer = 0; - this.face = true; - this.bukkitScheduler = Bukkit.getScheduler(); - Layout layoutUtil = ConfigReader.LAYOUT.get(layout); - this.start = layoutUtil.getStart(); - this.bar = layoutUtil.getBar(); - this.pointer = layoutUtil.getPointer(); - this.offset = layoutUtil.getOffset(); - this.end = layoutUtil.getEnd(); - this.pointerOffset = layoutUtil.getPointerOffset(); - this.title = layoutUtil.getTitle(); - this.size = layoutUtil.getSize(); - } - - public int getProgress() { return this.progress; } - public void setTaskID(int taskID){ - this.taskID = taskID; - } - - @Override - public void run() { - //移除提前收杆玩家 - if (fishingPlayers.get(player) == null){ - bukkitScheduler.cancelTask(taskID); - return; - } - //移除超时玩家 - if (System.currentTimeMillis() > fishingPlayers.get(player).getFishingTime()){ - AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.escape); - fishingPlayers.remove(player); - bukkitScheduler.cancelTask(taskID); - return; - } - - int timer = difficulty.getTimer() - 1; - int speed = difficulty.getSpeed(); - //设置指针方向 - if (progress <= speed - 1){ - face = true; - }else if(progress >= size - speed + 1){ - face = false; - } - //内部计时器操控 - if (internalTimer < timer){ - internalTimer++; - return; - }else { - if (face){ - internalTimer -= timer; - progress += speed; - }else { - internalTimer -= timer; - progress -= speed; - } - } - //发送title - 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){ - fishingPlayers.remove(player); - bukkitScheduler.cancelTask(taskID); - bukkitScheduler.runTask(CustomFishing.instance, ()-> { - player.removePotionEffect(PotionEffectType.SLOW); - }); - } - } -} diff --git a/src/main/java/net/momirealms/customfishing/utils/AdventureUtil.java b/src/main/java/net/momirealms/customfishing/util/AdventureUtil.java similarity index 73% rename from src/main/java/net/momirealms/customfishing/utils/AdventureUtil.java rename to src/main/java/net/momirealms/customfishing/util/AdventureUtil.java index 38d74951..ada046f9 100644 --- a/src/main/java/net/momirealms/customfishing/utils/AdventureUtil.java +++ b/src/main/java/net/momirealms/customfishing/util/AdventureUtil.java @@ -15,37 +15,47 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.utils; +package net.momirealms.customfishing.util; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; import net.kyori.adventure.sound.Sound; import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.title.Title; import net.momirealms.customfishing.CustomFishing; import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.time.Duration; public class AdventureUtil { + public static void sendMessage(CommandSender sender, String s) { + if (sender instanceof Player player) playerMessage(player, s); + else consoleMessage(s); + } + public static void consoleMessage(String s) { Audience au = CustomFishing.adventure.sender(Bukkit.getConsoleSender()); - Component parsed = CustomFishing.miniMessage.deserialize(s); + MiniMessage mm = MiniMessage.miniMessage(); + Component parsed = mm.deserialize(s); au.sendMessage(parsed); } public static void playerMessage(Player player, String s) { Audience au = CustomFishing.adventure.player(player); - Component parsed = CustomFishing.miniMessage.deserialize(s); + MiniMessage mm = MiniMessage.miniMessage(); + Component parsed = mm.deserialize(s); au.sendMessage(parsed); } public static void playerTitle(Player player, String s1, String s2, int in, int duration, int out) { Audience au = CustomFishing.adventure.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(CustomFishing.miniMessage.deserialize(s1), CustomFishing.miniMessage.deserialize(s2), times); + Title title = Title.title(mm.deserialize(s1), mm.deserialize(s2), times); au.showTitle(title); } @@ -58,11 +68,12 @@ public class AdventureUtil { public static void playerActionbar(Player player, String s) { Audience au = CustomFishing.adventure.player(player); - au.sendActionBar(CustomFishing.miniMessage.deserialize(s)); + MiniMessage mm = MiniMessage.miniMessage(); + au.sendActionBar(mm.deserialize(s)); } - public static void playerSound(Player player, Sound.Source source, Key key) { - Sound sound = Sound.sound(key, source, 1, 1); + 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); au.playSound(sound); } diff --git a/src/main/java/net/momirealms/customfishing/util/ArmorStandUtil.java b/src/main/java/net/momirealms/customfishing/util/ArmorStandUtil.java new file mode 100644 index 00000000..0ee46757 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/util/ArmorStandUtil.java @@ -0,0 +1,14 @@ +package net.momirealms.customfishing.util; + +import org.bukkit.entity.Player; + +public class ArmorStandUtil { + + public static int entityID = 654321234; + + public static void showNotice(Player player) { + + } + + +} diff --git a/src/main/java/net/momirealms/customfishing/util/ConfigUtil.java b/src/main/java/net/momirealms/customfishing/util/ConfigUtil.java new file mode 100644 index 00000000..a0a1b0f1 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/util/ConfigUtil.java @@ -0,0 +1,44 @@ +package net.momirealms.customfishing.util; + +import dev.dejvokep.boostedyaml.YamlDocument; +import dev.dejvokep.boostedyaml.dvs.versioning.BasicVersioning; +import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings; +import dev.dejvokep.boostedyaml.settings.general.GeneralSettings; +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.*; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; + +public class ConfigUtil { + + public static YamlConfiguration getConfig(String configName) { + File file = new File(CustomFishing.plugin.getDataFolder(), configName); + if (!file.exists()) CustomFishing.plugin.saveResource(configName, false); + return YamlConfiguration.loadConfiguration(file); + } + + public static void reload() { + ConfigManager.load(); + LayoutManager.load(); + MessageManager.load(); + LootManager.load(); + BonusManager.load(); + CustomFishing.plugin.getFishingManager().unload(); + CustomFishing.plugin.getFishingManager().load(); + CustomFishing.plugin.getCompetitionSchedule().unload(); + CustomFishing.plugin.getCompetitionSchedule().load(); + } + + 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()); + } catch (IOException e){ + Log.warn(e.getMessage()); + } + } +} diff --git a/src/main/java/net/momirealms/customfishing/utils/ItemUtil.java b/src/main/java/net/momirealms/customfishing/util/ItemStackUtil.java similarity index 63% rename from src/main/java/net/momirealms/customfishing/utils/ItemUtil.java rename to src/main/java/net/momirealms/customfishing/util/ItemStackUtil.java index aec38386..163aabc9 100644 --- a/src/main/java/net/momirealms/customfishing/utils/ItemUtil.java +++ b/src/main/java/net/momirealms/customfishing/util/ItemStackUtil.java @@ -1,40 +1,23 @@ -/* - * 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.utils; +package net.momirealms.customfishing.util; import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTItem; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.TranslatableComponent; +import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.momirealms.customfishing.ConfigReader; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.hook.ItemsAdderItem; -import net.momirealms.customfishing.hook.MMOItemsHook; -import net.momirealms.customfishing.hook.MythicItems; -import net.momirealms.customfishing.hook.OraxenItem; -import net.momirealms.customfishing.listener.PapiUnregister; +import net.momirealms.customfishing.manager.BonusManager; +import net.momirealms.customfishing.manager.LootManager; +import net.momirealms.customfishing.object.Item; +import net.momirealms.customfishing.object.LeveledEnchantment; import net.momirealms.customfishing.object.loot.DroppedItem; -import org.apache.commons.lang.StringUtils; +import net.momirealms.customfishing.object.loot.Loot; import org.bukkit.Material; import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.ItemMeta; @@ -42,66 +25,134 @@ import java.io.File; import java.io.IOException; import java.util.*; -public class ItemUtil { +public class ItemStackUtil { + + public static ItemStack getFromItem(Item item) { + ItemStack itemStack = new ItemStack(item.getMaterial()); + ItemMeta itemMeta = itemStack.getItemMeta(); + if (item.getCustomModelData() != 0) itemMeta.setCustomModelData(item.getCustomModelData()); + if (item.isUnbreakable()) itemMeta.setUnbreakable(true); + if (item.getItemFlags() != null) item.getItemFlags().forEach(itemMeta::addItemFlags); + if (item.getEnchantment() != null) { + if (itemStack.getType() == Material.ENCHANTED_BOOK){ + EnchantmentStorageMeta meta = (EnchantmentStorageMeta) itemMeta; + item.getEnchantment().forEach(enchantment -> meta.addStoredEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.getKey())),enchantment.getLevel(),true)); + itemStack.setItemMeta(meta); + } + else { + item.getEnchantment().forEach(enchantment -> itemMeta.addEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.getKey())),enchantment.getLevel(),true)); + itemStack.setItemMeta(itemMeta); + } + } + else { + itemStack.setItemMeta(itemMeta); + } + NBTItem nbtItem = new NBTItem(itemStack); + if (item.getName() != null) { + NBTCompound display = nbtItem.addCompound("display"); + String name = item.getName(); + if (name.contains("&") || name.contains("§")){ + name = name.replaceAll("&","§"); + name = replaceLegacy(name); + } + display.setString("Name", GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize("" + name))); + } + if (item.getLore() != null) { + NBTCompound display = nbtItem.addCompound("display"); + List lore = display.getStringList("Lore"); + item.getLore().forEach(line -> { + if (line.contains("&") || line.contains("§")){ + line = line.replaceAll("&","§"); + line = replaceLegacy(line); + } + lore.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize("" + line))); + }); + } + if (item.getNbt() != null) NBTUtil.setTags(item.getNbt(), nbtItem); + return nbtItem.getItem(); + } + + public static void addRandomDamage(ItemStack itemStack){ + if (itemStack.getItemMeta() instanceof Damageable damageable){ + damageable.setDamage((int) (itemStack.getType().getMaxDurability() * Math.random())); + itemStack.setItemMeta(damageable); + } + } + + public static void addOwner(ItemStack itemStack, String name){ + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString("M_Owner", name); + itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); + } + + public static void addRandomEnchants(ItemStack itemStack, LeveledEnchantment[] enchantments){ + ItemMeta itemMeta = itemStack.getItemMeta(); + if (itemStack.getType() == Material.ENCHANTED_BOOK){ + EnchantmentStorageMeta meta = (EnchantmentStorageMeta)itemMeta; + for (LeveledEnchantment enchantment : enchantments) { + if (enchantment.getChance() > Math.random()) meta.addStoredEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.getKey())),enchantment.getLevel(),true); + } + itemStack.setItemMeta(meta); + } + else { + for (LeveledEnchantment enchantment : enchantments) { + if (enchantment.getChance() > Math.random()) itemMeta.addEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.getKey())),enchantment.getLevel(),true); + } + itemStack.setItemMeta(itemMeta); + } + } + + public static ItemStack addIdentifier(ItemStack itemStack, String type, String id){ + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing"); + nbtCompound.setString("type", type); + nbtCompound.setString("id", id); + itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); + return itemStack; + } public static void givePlayerLoot(Player player, String lootKey, int amount){ - ItemStack itemStack = ConfigReader.LootItem.get(lootKey); - if (itemStack == null) return; + Loot loot = LootManager.WATERLOOTS.get(lootKey); + if (loot == null) { + loot = LootManager.LAVALOOTS.get(lootKey); + if (loot == null) return; + } + if (!(loot instanceof DroppedItem droppedItem)) return; + String key = droppedItem.getMaterial(); + ItemStack itemStack = CustomFishing.plugin.getIntegrationManager().build(key); + 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 = ConfigReader.RodItem.get(rodKey); - itemStack.setAmount(amount); - player.getInventory().addItem(itemStack); + ItemStack itemStack = BonusManager.RODITEMS.get(rodKey); + for (int i = 0; i < amount; i++) { + player.getInventory().addItem(itemStack); + } } public static void givePlayerBait(Player player, String baitKey, int amount){ - ItemStack itemStack = ConfigReader.BaitItem.get(baitKey); + ItemStack itemStack = BonusManager.BAITITEMS.get(baitKey); if (itemStack == null) return; itemStack.setAmount(amount); player.getInventory().addItem(itemStack); } public static void givePlayerUtil(Player player, String utilKey, int amount){ - ItemStack itemStack = ConfigReader.UtilItem.get(utilKey); + ItemStack itemStack = BonusManager.UTILITEMS.get(utilKey); if (itemStack == null) return; itemStack.setAmount(amount); player.getInventory().addItem(itemStack); } - public static ItemStack getItemStackFromOtherPlugins(String key){ - DroppedItem droppedItem = (DroppedItem) ConfigReader.LOOT.get(key); - ItemStack itemStack = null; - switch (droppedItem.getType()){ - case "ia" -> itemStack = ItemsAdderItem.getItemStack(droppedItem.getId()).clone(); - case "oraxen" -> itemStack = OraxenItem.getItemStack(droppedItem.getId()).clone(); - case "mm" -> itemStack = MythicItems.getItemStack(droppedItem.getId()).clone(); - case "mmoitems" -> itemStack = MMOItemsHook.getItemStack(droppedItem.getId()).clone(); - } - return itemStack; - } + public static boolean saveToFile(ItemStack itemStack, String fileName){ - public static void saveToFile(ItemStack itemStack, String fileName){ - - if (itemStack == null || itemStack.getType() == Material.AIR) return; + if (itemStack == null || itemStack.getType() == Material.AIR) return false; YamlConfiguration yamlConfiguration = new YamlConfiguration(); - yamlConfiguration.set(fileName + ".material", itemStack.getType().toString()); - ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta.hasDisplayName()){ - yamlConfiguration.set(fileName + ".display.name", replaceLegacy(itemMeta.getDisplayName())); - } - if (itemMeta.hasLore()){ - List lore = new ArrayList<>(); - itemMeta.getLore().forEach(line -> { - lore.add(replaceLegacy(line)); - }); - yamlConfiguration.set(fileName + ".display.lore", lore); - } if (itemMeta.hasCustomModelData()) { yamlConfiguration.set(fileName + ".custom-model-data", itemMeta.getCustomModelData()); } @@ -133,30 +184,30 @@ public class ItemUtil { NBTItem nbtItem = new NBTItem(itemStack); Map map0 = compoundToMap(nbtItem); - if (map0.size() != 0){ + if (map0.size() != 0) { yamlConfiguration.createSection(fileName + ".nbt", map0); } - File file = new File(CustomFishing.instance.getDataFolder(), File.separator + "loots" + File.separator + fileName + ".yml"); + File file = new File(CustomFishing.plugin.getDataFolder(), File.separator + "loots" + File.separator + fileName + ".yml"); try { yamlConfiguration.save(file); - ConfigReader.loadLoot(); - }catch (IOException e){ + LootManager.load(); + } catch (IOException e) { e.printStackTrace(); } + + return true; } public static Map compoundToMap(NBTCompound nbtCompound){ Map map = new HashMap<>(); nbtCompound.getKeys().forEach(key -> { if (key.equals("Enchantments") - || key.equals("Name") - || key.equals("Lore") - || key.equals("HideFlags") - || key.equals("CustomModelData") - || key.equals("StoredEnchantments") - || key.equals("Unbreakable")) return; + || key.equals("HideFlags") + || key.equals("CustomModelData") + || key.equals("StoredEnchantments") + || key.equals("Unbreakable")) return; switch (nbtCompound.getType(key)){ case NBTTagByte -> map.put(key, "(Byte) " + nbtCompound.getByte(key)); case NBTTagInt -> map.put(key, "(Int) " + nbtCompound.getInteger(key)); @@ -190,20 +241,6 @@ public class ItemUtil { return map; } - public static Component getDisplayName(ItemStack itemStack){ - NBTItem nbtItem = new NBTItem(itemStack); - NBTCompound nbtCompound = nbtItem.getCompound("display"); - if (nbtCompound != null){ - String name = nbtCompound.getString("Name"); - if (!name.equals("")){ - return GsonComponentSerializer.gson().deserialize(name); - } - } - String type = itemStack.getType().toString().toLowerCase(); - if (itemStack.getType().isBlock()) return GsonComponentSerializer.gson().deserialize("{\"translate\":\"block.minecraft."+ type + "\"}"); - else return GsonComponentSerializer.gson().deserialize("{\"translate\":\"item.minecraft."+ type + "\"}"); - } - public static String replaceLegacy(String s) { StringBuilder stringBuilder = new StringBuilder(); char[] chars = s.toCharArray(); @@ -312,4 +349,4 @@ public class ItemUtil { } return stringBuilder.toString(); } -} \ No newline at end of file +} diff --git a/src/main/java/net/momirealms/customfishing/utils/JedisUtil.java b/src/main/java/net/momirealms/customfishing/util/JedisUtil.java similarity index 70% rename from src/main/java/net/momirealms/customfishing/utils/JedisUtil.java rename to src/main/java/net/momirealms/customfishing/util/JedisUtil.java index bc6c7cbb..ad3a6903 100644 --- a/src/main/java/net/momirealms/customfishing/utils/JedisUtil.java +++ b/src/main/java/net/momirealms/customfishing/util/JedisUtil.java @@ -1,21 +1,4 @@ -/* - * 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.utils; +package net.momirealms.customfishing.util; import net.momirealms.customfishing.helper.Log; import org.bukkit.configuration.file.YamlConfiguration; @@ -48,7 +31,7 @@ public class JedisUtil { jedisPool = new JedisPool(jedisPoolConfig, configuration.getString("redis.host","localhost"), configuration.getInt("redis.port",6379)); - AdventureUtil.consoleMessage("[CustomFishing] Redis Enabled!"); + AdventureUtil.consoleMessage("[CustomFishing] Redis Server Connected!"); List minIdleJedisList = new ArrayList<>(jedisPoolConfig.getMinIdle()); for (int i = 0; i < jedisPoolConfig.getMinIdle(); i++) { diff --git a/src/main/java/net/momirealms/customfishing/util/NBTUtil.java b/src/main/java/net/momirealms/customfishing/util/NBTUtil.java new file mode 100644 index 00000000..0d473751 --- /dev/null +++ b/src/main/java/net/momirealms/customfishing/util/NBTUtil.java @@ -0,0 +1,92 @@ +package net.momirealms.customfishing.util; + +import de.tr7zw.changeme.nbtapi.NBTCompound; +import de.tr7zw.changeme.nbtapi.NBTItem; +import org.bukkit.configuration.MemorySection; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public class NBTUtil { + + public static NBTItem getNBTItem(Map nbt, ItemStack itemStack){ + NBTItem nbtItem = new NBTItem(itemStack); + setTags(nbt, nbtItem); + return nbtItem; + } + + public static void setTags(Map map, NBTCompound nbtCompound) { + for (String key : map.keySet()) { + if (map.get(key) instanceof MemorySection memorySection){ + NBTCompound newCompound = nbtCompound.addCompound(key); + setTags(memorySection.getValues(false), newCompound); + } + else if (map.get(key) instanceof List list){ + for (Object o : list) { + if (o instanceof String value) { + setListValue(key, value, nbtCompound); + } + } + } + else if (map.get(key) instanceof String value) { + setSingleValue(key, value, nbtCompound); + } + } + } + + private static void setListValue(String key, String value, NBTCompound nbtCompound) { + if (value.startsWith("(String) ")) { + nbtCompound.getStringList(key).add(value.substring(9)); + } else if (value.startsWith("(UUID) ")) { + nbtCompound.getUUIDList(key).add(UUID.fromString(value.substring(7))); + } else if (value.startsWith("(Double) ")) { + nbtCompound.getDoubleList(key).add(Double.valueOf(value.substring(9))); + } else if (value.startsWith("(Long) ")) { + nbtCompound.getLongList(key).add(Long.valueOf(value.substring(7))); + } else if (value.startsWith("(Float) ")) { + nbtCompound.getFloatList(key).add(Float.valueOf(value.substring(8))); + } else if (value.startsWith("(Int) ")) { + nbtCompound.getIntegerList(key).add(Integer.valueOf(value.substring(6))); + } else if (value.startsWith("(IntArray) ")){ + String[] split = value.substring(11).replace("[","").replace("]","").replaceAll("\\s", "").split(","); + int[] array = Arrays.stream(split).mapToInt(Integer::parseInt).toArray(); + nbtCompound.getIntArrayList(key).add(array); + } + } + + private static void setSingleValue(String key, String value, NBTCompound nbtCompound) { + if (value.startsWith("(Int) ")){ + nbtCompound.setInteger(key, Integer.valueOf(value.substring(6))); + } else if (value.startsWith("(String) ")){ + nbtCompound.setString(key, value.substring(9)); + } else if (value.startsWith("(Long) ")){ + nbtCompound.setLong(key, Long.valueOf(value.substring(7))); + } else if (value.startsWith("(Float) ")){ + nbtCompound.setFloat(key, Float.valueOf(value.substring(8))); + } else if (value.startsWith("(Double) ")){ + nbtCompound.setDouble(key, Double.valueOf(value.substring(9))); + } else if (value.startsWith("(Short) ")){ + nbtCompound.setShort(key, Short.valueOf(value.substring(8))); + } else if (value.startsWith("(Boolean) ")){ + nbtCompound.setBoolean(key, Boolean.valueOf(value.substring(10))); + } else if (value.startsWith("(UUID) ")){ + nbtCompound.setUUID(key, UUID.fromString(value.substring(7))); + } else if (value.startsWith("(Byte) ")){ + nbtCompound.setByte(key, Byte.valueOf(value.substring(7))); + } else if (value.startsWith("(ByteArray) ")){ + String[] split = value.substring(12).replace("[","").replace("]","").replaceAll("\\s", "").split(","); + byte[] bytes = new byte[split.length]; + for (int i = 0; i < split.length; i++){ + bytes[i] = Byte.parseByte(split[i]); + } + nbtCompound.setByteArray(key, bytes); + } else if (value.startsWith("(IntArray) ")){ + String[] split = value.substring(11).replace("[","").replace("]","").replaceAll("\\s", "").split(","); + int[] array = Arrays.stream(split).mapToInt(Integer::parseInt).toArray(); + nbtCompound.setIntArray(key, array); + } + } +} diff --git a/src/main/java/net/momirealms/customfishing/utils/ConfigUtil.java b/src/main/java/net/momirealms/customfishing/utils/ConfigUtil.java deleted file mode 100644 index 8649d058..00000000 --- a/src/main/java/net/momirealms/customfishing/utils/ConfigUtil.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.momirealms.customfishing.utils; - -import dev.dejvokep.boostedyaml.YamlDocument; -import dev.dejvokep.boostedyaml.dvs.versioning.BasicVersioning; -import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings; -import dev.dejvokep.boostedyaml.settings.general.GeneralSettings; -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 java.io.File; -import java.io.IOException; - -public class ConfigUtil { - - public static void update(){ - try { - YamlDocument.create(new File(CustomFishing.instance.getDataFolder(), "config.yml"), CustomFishing.instance.getResource("config.yml"), GeneralSettings.DEFAULT, LoaderSettings.builder().setAutoUpdate(true).build(), DumperSettings.DEFAULT, UpdaterSettings.builder().setVersioning(new BasicVersioning("config-version")).build()); - }catch (IOException e){ - Log.warn(e.getMessage()); - } - } -} diff --git a/src/main/java/net/momirealms/customfishing/utils/ItemStackUtil.java b/src/main/java/net/momirealms/customfishing/utils/ItemStackUtil.java deleted file mode 100644 index 595e6531..00000000 --- a/src/main/java/net/momirealms/customfishing/utils/ItemStackUtil.java +++ /dev/null @@ -1,129 +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.utils; - -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTItem; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.momirealms.customfishing.CustomFishing; -import net.momirealms.customfishing.object.Item; -import net.momirealms.customfishing.object.LeveledEnchantment; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.List; -import java.util.Objects; - -public class ItemStackUtil { - - public static ItemStack getFromItem(Item item){ - ItemStack itemStack = new ItemStack(Material.valueOf(item.getMaterial().toUpperCase())); - ItemMeta itemMeta = itemStack.getItemMeta(); - if (item.getCustomModelData() != 0){ - itemMeta.setCustomModelData(item.getCustomModelData()); - } - if (item.isUnbreakable()){ - itemMeta.setUnbreakable(true); - } - if (item.getItemFlags() != null){ - item.getItemFlags().forEach(itemMeta::addItemFlags); - } - if (item.getEnchantment() != null) { - if (itemStack.getType() == Material.ENCHANTED_BOOK){ - EnchantmentStorageMeta meta = (EnchantmentStorageMeta)itemMeta; - item.getEnchantment().forEach(enchantment -> meta.addStoredEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.getKey())),enchantment.getLevel(),true)); - itemStack.setItemMeta(meta); - }else { - item.getEnchantment().forEach(enchantment -> itemMeta.addEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.getKey())),enchantment.getLevel(),true)); - itemStack.setItemMeta(itemMeta); - } - } - else { - itemStack.setItemMeta(itemMeta); - } - NBTItem nbtItem = new NBTItem(itemStack); - if (item.getName() != null){ - NBTCompound display = nbtItem.addCompound("display"); - String name = item.getName(); - if (name.contains("&") || name.contains("§")){ - name = name.replaceAll("&","§"); - display.setString("Name", GsonComponentSerializer.gson().serialize(LegacyComponentSerializer.legacyAmpersand().deserialize(name))); - }else { - display.setString("Name", GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize("" + name))); - } - } - if(item.getLore() != null){ - NBTCompound display = nbtItem.addCompound("display"); - List lore = display.getStringList("Lore"); - item.getLore().forEach(line -> { - if (line.contains("&") || line.contains("§")){ - line = line.replaceAll("&","§"); - lore.add(GsonComponentSerializer.gson().serialize(LegacyComponentSerializer.legacyAmpersand().deserialize(line))); - }else { - lore.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize("" + line))); - } - }); - } - if (item.getNbt() != null){ - NBTUtil.setTags(item.getNbt(), nbtItem); - } - return nbtItem.getItem(); - } - - public static void addRandomEnchants(ItemStack itemStack, List enchantments){ - ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemStack.getType() == Material.ENCHANTED_BOOK){ - EnchantmentStorageMeta meta = (EnchantmentStorageMeta)itemMeta; - enchantments.forEach(enchantment -> { - if (enchantment.getChance() > Math.random()){ - meta.addStoredEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.getKey())),enchantment.getLevel(),true); - } - }); - itemStack.setItemMeta(meta); - } - else { - enchantments.forEach(enchantment -> { - if (enchantment.getChance() > Math.random()){ - itemMeta.addEnchant(Objects.requireNonNull(Enchantment.getByKey(enchantment.getKey())),enchantment.getLevel(),true); - } - }); - itemStack.setItemMeta(itemMeta); - } - } - - public static void addRandomDamage(ItemStack itemStack){ - if (itemStack.getItemMeta() instanceof Damageable damageable){ - damageable.setDamage((int) (itemStack.getType().getMaxDurability() * Math.random())); - itemStack.setItemMeta(damageable); - } - } - - public static void addOwner(ItemStack itemStack, String name){ - NBTItem nbtItem = new NBTItem(itemStack); - nbtItem.setString("M_Owner", name); - itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); - } -} diff --git a/src/main/java/net/momirealms/customfishing/utils/NBTUtil.java b/src/main/java/net/momirealms/customfishing/utils/NBTUtil.java deleted file mode 100644 index 33fb2d42..00000000 --- a/src/main/java/net/momirealms/customfishing/utils/NBTUtil.java +++ /dev/null @@ -1,115 +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.utils; - -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTItem; -import org.bukkit.configuration.MemorySection; -import org.bukkit.inventory.ItemStack; - -import java.util.*; - -public class NBTUtil { - - public static ItemStack addIdentifier(ItemStack itemStack, String type, String id){ - NBTItem nbtItem = new NBTItem(itemStack); - nbtItem.addCompound("CustomFishing"); - nbtItem.getCompound("CustomFishing").setString("type", type); - nbtItem.getCompound("CustomFishing").setString("id", id); - return nbtItem.getItem(); - } - - public static NBTItem getNBTItem(Map nbt, ItemStack itemStack){ - NBTItem nbtItem = new NBTItem(itemStack); - setTags(nbt, nbtItem); - return nbtItem; - } - - public static void setTags(Map map, NBTCompound nbtCompound){ - map.keySet().forEach(key -> { - if (map.get(key) instanceof MemorySection map2){ - nbtCompound.addCompound(key); - setTags(map2.getValues(false), nbtCompound.getCompound(key)); - } - else if (map.get(key) instanceof Map map1){ - nbtCompound.addCompound(key); - setTags((Map) map1, nbtCompound.getCompound(key)); - } - else if (map.get(key) instanceof List list){ - for (Object o : list) { - if (o instanceof String s) { - if (s.startsWith("(String) ")) { - nbtCompound.getStringList(key).add(s.substring(9)); - } else if (s.startsWith("(UUID) ")) { - nbtCompound.getUUIDList(key).add(UUID.fromString(s.substring(7))); - } else if (s.startsWith("(Double) ")) { - nbtCompound.getDoubleList(key).add(Double.valueOf(s.substring(9))); - } else if (s.startsWith("(Long) ")) { - nbtCompound.getLongList(key).add(Long.valueOf(s.substring(7))); - } else if (s.startsWith("(Float) ")) { - nbtCompound.getFloatList(key).add(Float.valueOf(s.substring(8))); - } else if (s.startsWith("(Int) ")) { - nbtCompound.getIntegerList(key).add(Integer.valueOf(s.substring(6))); - } else if (s.startsWith("(IntArray) ")){ - String[] split = s.substring(11).replace("[","").replace("]","").replaceAll("\\s", "").split(","); - int[] array = Arrays.stream(split).mapToInt(Integer::parseInt).toArray(); - nbtCompound.getIntArrayList(key).add(array); - } - } - else if (o instanceof Map map1) { - setTags(map1, nbtCompound.getCompoundList(key).addCompound()); - } - } - } - else { - if (map.get(key) instanceof String string){ - if (string.startsWith("(Int) ")){ - nbtCompound.setInteger(key, Integer.valueOf(string.substring(6))); - }else if (string.startsWith("(String) ")){ - nbtCompound.setString(key, string.substring(9)); - }else if (string.startsWith("(Long) ")){ - nbtCompound.setLong(key, Long.valueOf(string.substring(7))); - }else if (string.startsWith("(Float) ")){ - nbtCompound.setFloat(key, Float.valueOf(string.substring(8))); - }else if (string.startsWith("(Double) ")){ - nbtCompound.setDouble(key, Double.valueOf(string.substring(9))); - }else if (string.startsWith("(Short) ")){ - nbtCompound.setShort(key, Short.valueOf(string.substring(8))); - }else if (string.startsWith("(Boolean) ")){ - nbtCompound.setBoolean(key, Boolean.valueOf(string.substring(10))); - }else if (string.startsWith("(UUID) ")){ - nbtCompound.setUUID(key, UUID.fromString(string.substring(7))); - }else if (string.startsWith("(Byte) ")){ - nbtCompound.setByte(key, Byte.valueOf(string.substring(7))); - }else if (string.startsWith("(ByteArray) ")){ - String[] split = string.substring(12).replace("[","").replace("]","").replaceAll("\\s", "").split(","); - byte[] bytes = new byte[split.length]; - for (int i = 0; i < split.length; i++){ - bytes[i] = Byte.parseByte(split[i]); - } - nbtCompound.setByteArray(key, bytes); - }else if (string.startsWith("(IntArray) ")){ - String[] split = string.substring(11).replace("[","").replace("]","").replaceAll("\\s", "").split(","); - int[] array = Arrays.stream(split).mapToInt(Integer::parseInt).toArray(); - nbtCompound.setIntArray(key, array); - } - } - } - }); - } -} \ No newline at end of file diff --git a/src/main/resources/baits/default.yml b/src/main/resources/baits/default.yml index c02ddc91..712c9a5b 100644 --- a/src/main/resources/baits/default.yml +++ b/src/main/resources/baits/default.yml @@ -10,13 +10,13 @@ simple_bait: modifier: # Change the loot weight of the specified group # Add or subtract weights - weight-PM: + weight-add: silver: 5 gold: 3 # Multiply or divide weights - weight-MQ: + weight-multiply: silver: 1.1 - gold: 1.1 + gold: 0.9 # Change the time to fish (>1 for longer, <1 for shorter) time: 0.85 # Change the difficulty, for example, if the original difficulty is (1-6), now it becomes (1-9) diff --git a/src/main/resources/competition.yml b/src/main/resources/competition.yml index 79d797d0..0aaecf2b 100644 --- a/src/main/resources/competition.yml +++ b/src/main/resources/competition.yml @@ -1,16 +1,19 @@ example: - #TOTAL_SCORE - #CATCH_AMOUNT + # TOTAL_SCORE + # CATCH_AMOUNT + # RANDOM goal: CATCH_AMOUNT + # optional + # Fishing competition can also be started with a command start-time: - '5:30' - '17:30' + #seconds + duration: 300 - duration: 300 #seconds - - # Min players to begin the competition + # Min players to start the competition min-players: 2 # Competition information (it will only be shown to participants) @@ -19,7 +22,12 @@ example: color: YELLOW overlay: PROGRESS # https://docs.adventure.kyori.net/minimessage/format.html - text: 'Time Left: {time}s Rank: {rank} Time Left: {minute}m{second}s Points: {point}' + text: + - 'Time Left: {time}s Rank: {rank}' + - 'Time Left: {minute}m{second}s Points: {point}' + # seconds + switch-interval: 15 + # ticks refresh-rate: 10 command: @@ -51,7 +59,7 @@ example: - '' - '----------------------------------------' - # You can customize unlimited ranks' rewards by adding 4,5,6... + # You can customize unlimited ranks' rewards by adding ranks like 4,5,6... prize: 1: commands: diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 57735213..582de3fb 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,91 +1,112 @@ # don't change -config-version: '8' +config-version: '9' -config: - #en/es/cn - lang: en - integrations: - # fishing region hook - WorldGuard: false - # mobs hook - MythicMobs: false - # Papi hook - PlaceholderAPI: true - # Skill xp hook - # If skill xp is added not as expected please check if you have set skill-xp for each loot - # Some plugins like AureliumSkills will still add skill-xp when player failed to fish. Check the xp-source file in those skill plugins and set them to 0 - mcMMO: false - MMOCore: false - AureliumSkills: false - EcoSkills: false - # You need a restart to cancel the Jobs xp getting in vanilla way - JobsReborn: false - # Season hook - CustomCrops: false - RealisticSeasons: false +lang: en - # Worlds where the special fishing mechanic take effects - whitelist-worlds: - enable: false - worlds: - - world - # Should the fishing bar only show after player reel in - # Otherwise the bar would show immediately the bobber is hooked - double-reel-in: true +integration: + # Skill-xp + mcMMO: false + MMOCore: false + AureliumSkills: false + EcoSkills: false + JobsReborn: false + # Season condition + CustomCrops: false + RealisticSeasons: false - other-loot: - # This is useful for vanilla loots - # Vanilla loot is available only when 'double-reel-in' is true - vanilla: true - # 0.4 means 40% of the loots are from vanilla - # and 60% are from CustomFishing Loot system - vanilla-ratio: 0.4 - # Should vanilla loots have the same fishing mechanic CustomFishing provides - bar: true - # mcMMO treasure system - # chance represents the chance to try to be a mcMMO treasure - # But it doesn't mean 50% chance of the loot would be mcMMO treasure - # mcMMO has a complex treasure system - mcMMO: false - mcMMO-chance: 0.5 +worlds: + # Mode: whitelist/blacklist + mode: whitelist + list: + - world + + +mechanics: + + other-loots: + + # Should other loots have the same fishing mechanic CustomFishing provides + fishing-bar: true + + vanilla: + # Vanilla loot is available only when 'double-reel-in' is true + enable: true + # 0.4 means 40% of the loots are from vanilla + # and 60% are from CustomFishing Loot system + ratio: 0.4 + + mcMMO: + # mcMMO treasure system + # chance represents the chance to try to be a mcMMO treasure + # But it doesn't mean 50% chance of the loot would be mcMMO treasure + # mcMMO has a complex treasure system + enable: false + chance: 0.5 # The same to vanilla (refer to the wiki) # https://technical-minecraft.fandom.com/wiki/Fishing need-open-water: true need-special-rod: - # if set true and "double-reel-in" is true, players must use rods with CustomFishing's NBT Tags to get loots in CustomFishing but they can experience the special fishing mechanic. - # This option will not work if "double-reel-in" is false because in that mode no vanilla loots are available + # Players must use rods with CustomFishing's NBT Tags to get loots in CustomFishing but they can experience the special fishing mechanic. for-loots: false - # if set true and "double-reel-in" is true, players must use rods with CustomFishing's NBT Tags to experience the special fishing mechanic. Otherwise they can only fish in a vanilla way + # Players must use rods with CustomFishing's NBT Tags to experience the special fishing mechanic. Otherwise they can only fish in a vanilla way to-fish: false # does rod lose durability when player successfully fish rod-lose-durability: true - # Cool down time of fish finder + # Cool down time of fish finder(ms) fishfinder-cooldown: 3000 - # Change the time bobber needs to be hooked - time-multiply: 2 - - # Competition (Requires a restart) + # Competition fishing-competition: true - # Convert MMOItems' rod into CustomFishing's rod (Requires a restart) - # keep the same key name both in MMOItems and CustomFishing and rods can extend the bonus of those in CustomFishing - convert-MMOITEMS: false - # Prevent other players to pick up your fishing loot (Requires a restart) - # This is useful for players to fish in a public area - prevent-other-players-pick-up-loot: false +titles: + success: + title: + - 'Success!' + - 'GG!' + - 'Good Job!' + subtitle: + - 'You have captured a {loot}' + - 'Hi Harm Hi {loot} Here we go!' + fade: + # ticks + in: 10 + stay: 30 + out: 10 + failure: + title: + - 'Real food!' + - 'Failure!' + - 'Try next time!' + subtitle: + - 'The fish escaped' + - 'Pay more attention on it!' + fade: + in: 10 + stay: 30 + out: 10 - # If there's a plugin conflict, event priority sometimes works - # HIGHEST NORMAL LOWEST + + +other-settings: + + # MONITOR HIGHEST HIGH NORMAL LOW LOWEST event-priority: NORMAL - # If enabled, players would not be able to get job exp in vanilla way (Requires a restart) - disable-JobsReborn-fishing-exp: false \ No newline at end of file + # If enabled, players would not be able to get job exp in vanilla way + disable-JobsReborn-fishing-exp: false + + # Convert MMOItems' rod into CustomFishing's rod + # keep the same key name both in MMOItems and CustomFishing so rods can extend the bonus of those in CustomFishing + convert-MMOItems-rods: false + + # Prevent other players to pick up your fishing loot + # This is useful for players to fish in a public area + prevent-other-players-pick-up-loot: false \ No newline at end of file diff --git a/src/main/resources/database.yml b/src/main/resources/database.yml new file mode 100644 index 00000000..8dac85be --- /dev/null +++ b/src/main/resources/database.yml @@ -0,0 +1,30 @@ +# Do not change +config-version: '1' + +settings: + # Valid Options: SQLite MYSQL + # Only MYSQL supports pool. + storage-mode: SQLite + use-pool: false + disable-async: false + +# MySQL settings +MySQL: + host: localhost + port: 3306 + user: root + password: password + database: minecraft + table-name: nameplates_data + property: + use-ssl: false + encoding: utf8 + timezone: '' + allowPublicKeyRetrieval: false + +# Connection pool settings +Pool-Settings: + maximum-pool-size: 10 + minimum-idle: 10 + maximum-lifetime: 180000 + idle-timeout: 60000 \ No newline at end of file diff --git a/src/main/resources/loots/default.yml b/src/main/resources/loots/default.yml index cf390f63..e69de29b 100644 --- a/src/main/resources/loots/default.yml +++ b/src/main/resources/loots/default.yml @@ -1,462 +0,0 @@ -rubbish: - material: paper - show-in-fishfinder: false - display: - name: 'Garbage' - weight: 50 - time: 100000 - difficulty: 1-1 - custom-model-data: 640 - -Pufferfish: - material: pufferfish - display: - name: 'Pufferfish' - weight: 50 - time: 100000 - difficulty: 1-5 - requirements: - weather: - - clear - -cod: - material: cod - display: - name: 'Cod' - weight: 50 - time: 100000 - difficulty: 1-5 - requirements: - weather: - - clear - -salmon: - material: salmon - display: - name: 'Salmon' - weight: 50 - time: 100000 - difficulty: 1-5 - requirements: - weather: - - clear - -tropical_fish: - material: tropical_fish - display: - name: 'Tropical Fish' - weight: 50 - time: 100000 - difficulty: 1-5 - requirements: - weather: - - clear - biome: - - minecraft:jungle - - minecraft:bamboo_jungle - -tuna: - material: paper - display: - name: 'Tuna Fish' - weight: 50 - time: 100000 - difficulty: 1-1 - custom-model-data: 641 - -tuna_fish_silver_star: - material: paper - display: - name: 'Tuna Fish Silver Star' - weight: 50 - time: 100000 - difficulty: 1-1 - group: silver - custom-model-data: 666 - -tuna_fish_golden_star: - material: paper - display: - name: 'Tuna Fish Golden Star' - weight: 50 - time: 100000 - difficulty: 1-1 - group: gold - custom-model-data: 667 - -pike: - material: paper - display: - name: 'Pike Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 642 - -pike_fish_silver_star: - material: paper - display: - name: 'Pike Fish Silver Star' - weight: 50 - time: 100000 - difficulty: 1-2 - group: silver - custom-model-data: 664 - -pike_fish_golden_star: - material: paper - display: - name: 'Pike Fish Golden Star' - weight: 50 - time: 100000 - difficulty: 1-2 - group: gold - custom-model-data: 665 - -golden: - material: paper - display: - name: 'Golden Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 643 - -golden_fish_silver_star: - material: paper - display: - name: 'Golden Fish Silver Star' - weight: 50 - time: 100000 - difficulty: 1-2 - group: silver - custom-model-data: 658 - -golden_fish_golden_star: - material: paper - display: - name: 'Golden Fish Golden Star' - weight: 50 - time: 100000 - group: gold - difficulty: 1-2 - custom-model-data: 659 - -perch_fish: - material: paper - display: - name: 'Perch Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 644 - -perch_fish_silver_star: - material: paper - display: - name: 'Perch Fish Silver Star' - weight: 50 - time: 100000 - group: silver - difficulty: 1-2 - custom-model-data: 660 - -perch_fish_golden_star: - material: paper - display: - name: 'Perch Fish Golden Star' - weight: 50 - group: gold - time: 100000 - difficulty: 1-2 - custom-model-data: 661 - -mullet_fish: - material: paper - display: - name: 'Mullet Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 645 - -mullet_fish_silver_star: - material: paper - display: - name: 'Mullet Fish Silver Star' - weight: 50 - group: silver - time: 100000 - difficulty: 1-2 - custom-model-data: 662 - -mullet_fish_golden_star: - material: paper - display: - name: 'Mullet Fish Golden Star' - weight: 50 - time: 100000 - group: gold - difficulty: 1-2 - custom-model-data: 663 - -sardine_fish: - material: paper - display: - name: 'Sardine Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 668 - -sardine_fish_silver_star: - material: paper - display: - name: 'Sardine Fish Silver Star' - weight: 50 - time: 100000 - group: silver - difficulty: 1-2 - custom-model-data: 669 - -sardine_fish_golden_star: - material: paper - display: - name: 'Sardine Fish Golden Star' - weight: 50 - time: 100000 - group: gold - difficulty: 1-2 - custom-model-data: 670 - -carp_fish: - material: paper - display: - name: 'Carp Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 671 - -carp_fish_silver_star: - material: paper - display: - name: 'Carp Fish Silver Star' - weight: 50 - time: 100000 - group: silver - difficulty: 1-2 - custom-model-data: 672 - -carp_fish_golden_star: - material: paper - display: - name: 'Carp Fish Golden Star' - weight: 50 - time: 100000 - group: gold - difficulty: 1-2 - custom-model-data: 673 - -cat_fish: - material: paper - display: - name: 'Cat Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 674 - -cat_fish_silver_star: - material: paper - display: - name: 'Cat Fish Silver Star' - weight: 50 - group: silver - time: 100000 - difficulty: 1-2 - custom-model-data: 675 - -cat_fish_golden_star: - material: paper - display: - name: 'Cat Fish Golden Star' - weight: 50 - time: 100000 - group: gold - difficulty: 1-2 - custom-model-data: 676 - -octopus_fish: - material: paper - display: - name: 'Octopus Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 677 - -octopus_fish_silver_star: - material: paper - display: - name: 'Octopus Fish Silver Star' - weight: 50 - group: silver - time: 100000 - difficulty: 1-2 - custom-model-data: 678 - -octopus_fish_golden_star: - material: paper - display: - name: 'Octopus Fish Golden Star' - weight: 50 - time: 100000 - group: gold - difficulty: 1-2 - custom-model-data: 679 - -sunfish_fish: - material: paper - display: - name: 'Sunfish Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 680 - -sunfish_fish_silver_star: - material: paper - display: - name: 'Sunfish Fish Silver Star' - weight: 50 - group: silver - time: 100000 - difficulty: 1-2 - custom-model-data: 681 - -sunfish_fish_golden_star: - material: paper - display: - name: 'Sunfish Fish Golden Star' - weight: 50 - time: 100000 - group: gold - difficulty: 1-2 - custom-model-data: 682 - -red_spnapper_fish: - material: paper - display: - name: 'Red Snapper Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 683 - -red_spnapper_fish_silver_star: - material: paper - display: - name: 'Red Snapper Fish Silver Star' - weight: 50 - time: 100000 - group: silver - difficulty: 1-2 - custom-model-data: 684 - -red_spnapper_fish_golden_star: - material: paper - display: - name: 'Red Snapper Golden Star' - weight: 50 - time: 100000 - group: gold - difficulty: 1-2 - custom-model-data: 685 - -salmon_void_fish: - material: paper - display: - name: 'Salmon Void Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 686 - -salmon_void_fish_silver_star: - material: paper - display: - name: 'Salmon Void Fish Silver Star' - weight: 50 - time: 100000 - group: silver - difficulty: 1-2 - custom-model-data: 687 - -salmon_void_fish_golden_star: - material: paper - display: - name: 'Salmon Void Fish Golden Star' - weight: 50 - time: 100000 - group: gold - difficulty: 1-2 - custom-model-data: 688 - -woodskip_fish: - material: paper - display: - name: 'Woodskip Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 689 - -woodskip_fish_silver_star: - material: paper - display: - name: 'Woodskip Fish Silver Star' - weight: 50 - group: silver - time: 100000 - difficulty: 1-2 - custom-model-data: 690 - -woodskip_fish_golden_star: - material: paper - display: - name: 'Woodskip Fish Golden Star' - weight: 50 - group: gold - time: 100000 - difficulty: 1-2 - custom-model-data: 691 - -sturgeon_fish: - material: paper - display: - name: 'Sturgeon Fish' - weight: 50 - time: 100000 - difficulty: 1-2 - custom-model-data: 692 - -sturgeon_fish_silver_star: - material: paper - display: - name: 'Sturgeon Fish Silver Star' - weight: 50 - group: silver - time: 100000 - difficulty: 1-2 - custom-model-data: 693 - -sturgeon_fish_golden_star: - material: paper - display: - name: 'Sturgeon Fish Golden Star' - weight: 50 - time: 100000 - group: gold - difficulty: 1-2 - custom-model-data: 694 \ No newline at end of file diff --git a/src/main/resources/loots/example.yml b/src/main/resources/loots/example.yml index 8aec1e5d..3ddbd98f 100644 --- a/src/main/resources/loots/example.yml +++ b/src/main/resources/loots/example.yml @@ -7,6 +7,8 @@ rainbow_fish: 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 diff --git a/src/main/resources/messages/messages_cn.yml b/src/main/resources/messages/messages_cn.yml index c1a69755..ffca6f24 100644 --- a/src/main/resources/messages/messages_cn.yml +++ b/src/main/resources/messages/messages_cn.yml @@ -4,7 +4,7 @@ messages: prefix: '[CustomFishing] ' reload: '重载成功.' no-perm: '你没有权限!' - not-online: '玩家不在线!' + not-online: '玩家 {Player} 不在线!' not-exist: '此物品不存在!' escape: '太久没拉钩鱼儿跑走啦!' give-item: '成功给予玩家 {Player} {Amount}x {Item}.' @@ -12,6 +12,8 @@ messages: no-console: '这个指令不能由控制台执行!' wrong-amount: '不能给玩家数量为负数的物品!' lack-args: '参数不足.' + none-args: '非空参数!' + invalid-args: '无效参数!' cooldown: '你使用找鱼器的速度太快了!' possible-loots: '此处可能钓到: ' split-char: ',' diff --git a/src/main/resources/messages/messages_en.yml b/src/main/resources/messages/messages_en.yml index 3f1c0b92..a6544dcb 100644 --- a/src/main/resources/messages/messages_en.yml +++ b/src/main/resources/messages/messages_en.yml @@ -12,6 +12,8 @@ messages: no-console: 'This command cannot be executed from the console!' wrong-amount: 'You cannot give a player an item with a negative quantity!' lack-args: 'Insufficient parameters.' + none-args: 'None arguments!' + invalid-args: 'Invalid arguments!' cooldown: 'You''re using the fish finder too fast!' possible-loots: 'Possible loots here: ' split-char: ', ' diff --git a/src/main/resources/messages/messages_es.yml b/src/main/resources/messages/messages_es.yml index b1d134bb..f9d4ed16 100644 --- a/src/main/resources/messages/messages_es.yml +++ b/src/main/resources/messages/messages_es.yml @@ -12,6 +12,8 @@ messages: no-console: '¡Este comando no puede ser ejecutado por la consola!' wrong-amount: 'No puedes dar a un jugador un artículo con una cantidad negativa.' lack-args: 'Parámetros insuficientes.' + none-args: '¡Ningún argumento!' + invalid-args: 'Argumentos no válidos' cooldown: '¡Estás usando el buscador de peces demasiado rápido!' possible-loots: 'Posible pesca aquí: ' split-char: ', ' diff --git a/src/main/resources/mobs/example.yml b/src/main/resources/mobs/example.yml index 8d775b03..c934d18b 100644 --- a/src/main/resources/mobs/example.yml +++ b/src/main/resources/mobs/example.yml @@ -3,7 +3,7 @@ skeletalknight: enable: true # MythicMobsID - mythicmobsID: SkeletalKnight + mob: SkeletalKnight # The level of the mob level: 0 @@ -29,7 +29,7 @@ skeletalknight: piranha: enable: false - mythicmobsID: piranha + mob: piranha name: 'Piranha' weight: 50 time: 1000000 diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index aebede3d..caa715cd 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,7 +1,7 @@ name: CustomFishing version: '${version}' main: net.momirealms.customfishing.CustomFishing -api-version: 1.16 +api-version: 1.17 authors: [ XiaoMoMi ] softdepend: - MythicMobs diff --git a/src/main/resources/rods/default.yml b/src/main/resources/rods/default.yml index e2f9ee15..269e1cfe 100644 --- a/src/main/resources/rods/default.yml +++ b/src/main/resources/rods/default.yml @@ -11,7 +11,7 @@ nature_fishing_cane: name: 'Nature Fishing Cane' custom-model-data: 2 modifier: - weight-PM: + weight-add: silver: 5 silver_fishing_rod: @@ -19,7 +19,7 @@ silver_fishing_rod: name: 'Silver Fishing Rod' custom-model-data: 3 modifier: - weight-PM: + weight-add: silver: 20 gold: -10 @@ -28,7 +28,7 @@ golden_fishing_rod: name: 'Golden Fishing Rod' custom-model-data: 4 modifier: - weight-PM: + weight-add: silver: -20 gold: 20 @@ -37,6 +37,6 @@ star_fishing_rod: name: 'Star Fishing Rod' custom-model-data: 5 modifier: - weight-PM: + weight-add: silver: 20 gold: 10 \ No newline at end of file diff --git a/src/main/resources/titles.yml b/src/main/resources/titles.yml deleted file mode 100644 index 8ea02a49..00000000 --- a/src/main/resources/titles.yml +++ /dev/null @@ -1,27 +0,0 @@ -#MiniMessage Format -#https://docs.adventure.kyori.net/minimessage/format.html -titles: - failure: - title: - - 'Real food!' - - 'Failure!' - - 'Try next time!' - subtitle: - - 'The fish escaped' - - 'Pay more attention on it!' - fade: - in: 10 - stay: 30 - out: 10 - success: - title: - - 'Success!' - - 'GG!' - - 'Good Job!' - subtitle: - - 'You have captured a {loot}' - - 'Hi Harm Hi {loot} Here we go!' - fade: - in: 10 - stay: 30 - out: 10 \ No newline at end of file diff --git a/src/main/resources/totems.yml b/src/main/resources/totems.yml new file mode 100644 index 00000000..12914ba3 --- /dev/null +++ b/src/main/resources/totems.yml @@ -0,0 +1,55 @@ +example: + # Totem Core Block ID + core: + - b + - r + radius: 10 + # seconds + duration: 300 + particle: SPELL + + # Potion effect type and its amplifier + potion-effects: + NIGHT_VISION: 1 + + # Fishing bonus + modifier: + weight-add: + silver: -20 + gold: 20 + + # placeholders: {activator} {players_in_radius} {all_players} + # {world} {x} {y} {z} + commands: + - 'effect give {player_in_radius} ' + + messages: + activator: + - You activated a totem + players_in_radius: + - You are now in {activator}'s totem + - Your chance of getting gold fish is temporarily up + all_players: + - {activator} activated a totem at {world},{x},{y},{z} + + # The layout of the totem + # The greater the layer is, the higher the y position is + # Totem core can be put anywhere in the layout + # “*” represents any type of block is allowed here + # “()“ represents the block is protected and will not be removed when activating + # “>“ represents the block would turn into another block after activating + # “|“ represents alternative block choice for this place + layer: + 1: + - 'g>n (c) g>n' + - '(c) (c) (c)' + - 'g>n (c) g>n' + 2: + - '(c) air (c)' + - 'air r|b>h air' + - '(c) air (c)' + 3: + - '* (c) *' + - '(c) (c) (c)' + - '* (c) *' + diff --git a/src/main/resources/utils/totem_items.yml b/src/main/resources/utils/totem_items.yml new file mode 100644 index 00000000..e69de29b