diff --git a/README.md b/README.md index 46a830b..1c34899 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ water bucket or watering can. Max storage and range can be customized.\ Watering-can also has its max storage and effective range. 1x1 1x3 3x3 and even 9x99 is supported! ### OverWeight -If configurated, crops will still absorb water every day and have a very little chance to be OverWeight(gigantic) before it's dead.\ +If configurated, crops will still absorb water every day and have a very little chance to be OverWeight(gigantic) before it's dead. ### Quality Crops have three qualities, if you don't want this feature just disable it in config. diff --git a/build.gradle b/build.gradle index f97b173..f5a0927 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ plugins { group = 'net.momirealms' -version = '1.5.26.3' +version = '1.5.26.4' repositories { mavenCentral() diff --git a/src/main/java/net/momirealms/customcrops/ConfigReader.java b/src/main/java/net/momirealms/customcrops/ConfigReader.java index 683e4b5..ced5c11 100644 --- a/src/main/java/net/momirealms/customcrops/ConfigReader.java +++ b/src/main/java/net/momirealms/customcrops/ConfigReader.java @@ -18,12 +18,17 @@ package net.momirealms.customcrops; import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; import net.momirealms.customcrops.fertilizer.Fertilizer; import net.momirealms.customcrops.fertilizer.QualityCrop; import net.momirealms.customcrops.fertilizer.RetainingSoil; import net.momirealms.customcrops.fertilizer.SpeedGrow; +import net.momirealms.customcrops.helper.Log; import net.momirealms.customcrops.integrations.protection.*; import net.momirealms.customcrops.integrations.skill.*; +import net.momirealms.customcrops.objects.Crop; +import net.momirealms.customcrops.objects.Sprinkler; +import net.momirealms.customcrops.objects.WateringCan; import net.momirealms.customcrops.requirements.Biome; import net.momirealms.customcrops.requirements.Permission; import net.momirealms.customcrops.requirements.Requirement; @@ -41,20 +46,18 @@ import java.util.*; public class ConfigReader { - public static HashMap CROPS = new HashMap<>(); + public static HashMap CROPS = new HashMap<>(); public static HashMap FERTILIZERS = new HashMap<>(); public static HashMap CANS = new HashMap<>(); public static HashMap SPRINKLERS = new HashMap<>(); public static YamlConfiguration getConfig(String configName) { File file = new File(CustomCrops.plugin.getDataFolder(), configName); - if (!file.exists()) { - CustomCrops.plugin.saveResource(configName, false); - } + if (!file.exists()) CustomCrops.plugin.saveResource(configName, false); return YamlConfiguration.loadConfiguration(file); } - public static void ReloadConfig(){ + public static void reloadConfig(){ Sounds.loadSound(); Config.loadConfig(); Season.loadSeason(); @@ -93,16 +96,16 @@ public class ConfigReader { public static boolean nwSeason; public static boolean needEmptyHand; public static boolean boneMeal; + public static boolean realisticSeason; public static Particle boneMealSuccess; public static double boneMealChance; public static double quality_1; public static double quality_2; public static SkillXP skillXP; - public static int version; + public static String version; public static void loadConfig(){ - //存读基本配置文件 CustomCrops.plugin.saveDefaultConfig(); CustomCrops.plugin.reloadConfig(); FileConfiguration config = CustomCrops.plugin.getConfig(); @@ -129,22 +132,19 @@ public class ConfigReader { boneMealSuccess = Particle.valueOf(config.getString("config.bone-meal.success-particle", "VILLAGER_HAPPY").toUpperCase()); } - //数量与高度限制 enableLimit = config.getBoolean("config.limit.enable",true); if (enableLimit){ cropLimit = config.getInt("config.limit.crop",64); sprinklerLimit = config.getInt("config.limit.sprinkler",16); } - if (Bukkit.getServer().getClass().getPackage().getName().contains("16") || Bukkit.getServer().getClass().getPackage().getName().contains("17")){ - yMin = 0; - yMax = 256; - } - if (Bukkit.getServer().getClass().getPackage().getName().contains("18") || Bukkit.getServer().getClass().getPackage().getName().contains("19")){ - yMin = -64; - yMax = 320; + + String serverVersion = Bukkit.getServer().getClass().getPackage().getName(); + if (serverVersion.contains("16") || serverVersion.contains("17")){ + yMin = 0; yMax = 256; + }else { + yMin = -64; yMax = 320; } - //农作物品质 quality = config.getBoolean("config.quality.enable",true); if (quality){ String[] split = StringUtils.split(config.getString("config.quality.default-ratio","17/2/1"), "/"); @@ -159,137 +159,82 @@ public class ConfigReader { sprinklerRefill = config.getInt("config.sprinkler-refill",2); waterCanRefill = config.getInt("config.water-can-refill",1); - version = config.getInt("config-version",1); + version = config.getString("config-version"); canAddWater = config.getBoolean("config.water-can-add-water-to-sprinkler",true); if (allWorld){ - if (config.getStringList("config.whitelist-worlds").size() > 1){ - referenceWorld = config.getStringList("config.whitelist-worlds").get(0); - AdventureManager.consoleMessage("[CustomCrops] Only one whitelist world is allowed when \"all-world-grow\" enabled!"); - }else { - referenceWorld = config.getStringList("config.whitelist-worlds").get(0); - } + if (config.getStringList("config.whitelist-worlds").size() > 1) AdventureManager.consoleMessage("[CustomCrops] Only one whitelist world is allowed when \"all-world-grow\" enabled!"); + referenceWorld = config.getStringList("config.whitelist-worlds").get(0); } - //农作物生长的白名单世界 worlds = new ArrayList<>(); worldNames = config.getStringList("config.whitelist-worlds"); worldNames.forEach(worldName -> { World world = Bukkit.getWorld(worldName); - if (world == null){ - AdventureManager.consoleMessage("[CustomCrops] World " + worldName + " doesn't exist"); - }else { - worlds.add(world); - } + if (world == null) AdventureManager.consoleMessage("[CustomCrops] World " + worldName + " doesn't exist"); + else worlds.add(world); }); - //处理插件兼容性 + integration = new ArrayList<>(); - if(config.getBoolean("config.integration.Residence",false)){ - if(Bukkit.getPluginManager().getPlugin("Residence") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize Residence!"); - }else { - integration.add(new Residence()); - AdventureManager.consoleMessage("[CustomCrops] Residence Hooked!"); - } + if (config.getBoolean("config.integration.Residence",false)){ + if (Bukkit.getPluginManager().getPlugin("Residence") == null) Log.warn("Failed to initialize Residence!"); + else {integration.add(new Residence());hookMessage("Residence");} } - if(config.getBoolean("config.integration.Kingdoms",false)){ - if(Bukkit.getPluginManager().getPlugin("Kingdoms") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize Kingdoms!"); - }else { - integration.add(new KingdomsX()); - AdventureManager.consoleMessage("[CustomCrops] KingdomsX Hooked!"); - } + if (config.getBoolean("config.integration.Kingdoms",false)){ + if (Bukkit.getPluginManager().getPlugin("Kingdoms") == null) Log.warn("Failed to initialize Kingdoms!"); + else {integration.add(new KingdomsX());hookMessage("Kingdoms");} } - if(config.getBoolean("config.integration.WorldGuard",false)){ - if(Bukkit.getPluginManager().getPlugin("WorldGuard") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize WorldGuard!"); - }else { - integration.add(new WorldGuard()); - AdventureManager.consoleMessage("[CustomCrops] WorldGuard Hooked!"); - } + if (config.getBoolean("config.integration.WorldGuard",false)){ + if (Bukkit.getPluginManager().getPlugin("WorldGuard") == null) Log.warn("Failed to initialize WorldGuard!"); + else {integration.add(new WorldGuard());hookMessage("WorldGuard");} } - if(config.getBoolean("config.integration.GriefDefender",false)){ - if(Bukkit.getPluginManager().getPlugin("GriefDefender") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize GriefDefender!"); - }else { - integration.add(new GriefDefender()); - AdventureManager.consoleMessage("[CustomCrops] GriefDefender Hooked!"); - } + if (config.getBoolean("config.integration.GriefDefender",false)){ + if(Bukkit.getPluginManager().getPlugin("GriefDefender") == null) Log.warn("Failed to initialize GriefDefender!"); + else {integration.add(new GriefDefender());hookMessage("GriefDefender");} } - if(config.getBoolean("config.integration.PlotSquared",false)){ - if(Bukkit.getPluginManager().getPlugin("PlotSquared") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize PlotSquared!"); - }else { - integration.add(new PlotSquared()); - AdventureManager.consoleMessage("[CustomCrops] PlotSquared Hooked!"); - } + if (config.getBoolean("config.integration.PlotSquared",false)){ + if(Bukkit.getPluginManager().getPlugin("PlotSquared") == null) Log.warn("Failed to initialize PlotSquared!"); + else {integration.add(new PlotSquared());hookMessage("PlotSquared");} } - if(config.getBoolean("config.integration.Towny",false)){ - if(Bukkit.getPluginManager().getPlugin("Towny") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize Towny!"); - }else { - integration.add(new Towny()); - AdventureManager.consoleMessage("[CustomCrops] Towny Hooked!"); - } + if (config.getBoolean("config.integration.Towny",false)){ + if (Bukkit.getPluginManager().getPlugin("Towny") == null) Log.warn("Failed to initialize Towny!"); + else {integration.add(new Towny());hookMessage("Towny");} } - if(config.getBoolean("config.integration.Lands",false)){ - if(Bukkit.getPluginManager().getPlugin("Lands") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize Lands!"); - }else { - integration.add(new Lands()); - AdventureManager.consoleMessage("[CustomCrops] Lands Hooked!"); - } + if (config.getBoolean("config.integration.Lands",false)){ + if (Bukkit.getPluginManager().getPlugin("Lands") == null) Log.warn("Failed to initialize Lands!"); + else {integration.add(new Lands());hookMessage("Lands");} } - if(config.getBoolean("config.integration.GriefPrevention",false)){ - if(Bukkit.getPluginManager().getPlugin("GriefPrevention") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize GriefPrevention!"); - }else { - integration.add(new GriefPrevention()); - AdventureManager.consoleMessage("[CustomCrops] GriefPrevention Hooked!"); - } + if (config.getBoolean("config.integration.GriefPrevention",false)){ + if (Bukkit.getPluginManager().getPlugin("GriefPrevention") == null) Log.warn("Failed to initialize GriefPrevention!"); + else {integration.add(new GriefPrevention());hookMessage("GriefPrevention");} } - if(config.getBoolean("config.integration.CrashClaim",false)){ - if(Bukkit.getPluginManager().getPlugin("CrashClaim") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize CrashClaim!"); - }else { - integration.add(new CrashClaim()); - AdventureManager.consoleMessage("[CustomCrops] CrashClaim Hooked!"); - } + if (config.getBoolean("config.integration.CrashClaim",false)){ + if (Bukkit.getPluginManager().getPlugin("CrashClaim") == null) Log.warn("Failed to initialize CrashClaim!"); + else {integration.add(new CrashClaim());hookMessage("CrashClaim");} + } + + realisticSeason = false; + if (config.getBoolean("config.integration.RealisticSeasons",false)){ + if (Bukkit.getPluginManager().getPlugin("RealisticSeasons") == null) Log.warn("Failed to initialize RealisticSeasons!"); + else {realisticSeason = true;hookMessage("RealisticSeasons");} } skillXP = null; - - if(config.getBoolean("config.integration.mcMMO",false)){ - if(Bukkit.getPluginManager().getPlugin("mcMMO") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize mcMMO!"); - }else { - skillXP = new mcMMO(); - AdventureManager.consoleMessage("[CustomCrops] mcMMO Hooked!"); - } + if (config.getBoolean("config.integration.mcMMO",false)){ + if (Bukkit.getPluginManager().getPlugin("mcMMO") == null) Log.warn("Failed to initialize mcMMO!"); + else {skillXP = new mcMMO();hookMessage("mcMMO");} } - if(config.getBoolean("config.integration.AureliumSkills",false)){ - if(Bukkit.getPluginManager().getPlugin("AureliumSkills") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize AureliumSkills!"); - }else { - skillXP = new Aurelium(); - AdventureManager.consoleMessage("[CustomCrops] AureliumSkills Hooked!"); - } + if (config.getBoolean("config.integration.AureliumSkills",false)){ + if (Bukkit.getPluginManager().getPlugin("AureliumSkills") == null) Log.warn("Failed to initialize AureliumSkills!"); + else {skillXP = new Aurelium();hookMessage("AureliumSkills");} } if(config.getBoolean("config.integration.MMOCore",false)){ - if(Bukkit.getPluginManager().getPlugin("MMOCore") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize MMOCore!"); - }else { - skillXP = new MMOCore(); - AdventureManager.consoleMessage("[CustomCrops] MMOCore Hooked!"); - } + if(Bukkit.getPluginManager().getPlugin("MMOCore") == null) Log.warn("Failed to initialize MMOCore!"); + else {skillXP = new MMOCore();hookMessage("MMOCore");} } if(config.getBoolean("config.integration.EcoSkills",false)){ - if(Bukkit.getPluginManager().getPlugin("EcoSkills") == null){ - CustomCrops.plugin.getLogger().warning("Failed to initialize EcoSkills!"); - }else { - skillXP = new EcoSkill(); - AdventureManager.consoleMessage("[CustomCrops] EcoSkills Hooked!"); - } + if(Bukkit.getPluginManager().getPlugin("EcoSkills") == null) Log.warn("Failed to initialize EcoSkills!"); + else {skillXP = new EcoSkill();hookMessage("EcoSkills");} } } } @@ -309,12 +254,14 @@ public class ConfigReader { public static List waterLore; public static void loadBasic(){ + YamlConfiguration config = getConfig("basic.yml"); + pot = config.getString("basic.pot","customcrops:pot"); watered_pot = config.getString("basic.watered-pot","customcrops:watered_pot"); glass = config.getString("basic.greenhouse-glass","customcrops:greenhouse_glass"); dead = config.getString("basic.dead-crop","customcrops:crop_stage_death"); - soilDetector = StringUtils.split(config.getString("basic.soil-detector","customcrops:soil_detector"),":")[1]; + soilDetector = config.getString("basic.soil-detector","customcrops:soil_detector"); hasWaterLore = config.getBoolean("lore.watering-can.enable",false); if (hasWaterLore){ @@ -328,17 +275,14 @@ public class ConfigReader { CANS.clear(); if (config.contains("water-can")){ config.getConfigurationSection("water-can").getKeys(false).forEach(key -> { - if (key.equals(StringUtils.split(config.getString("water-can." + key + ".item"),":")[1])){ - int width = config.getInt("water-can." + key + ".width"); - if (width % 2 == 0){ - AdventureManager.consoleMessage("[CustomCrops] Watering Can " + key + "'s width should be odd!"); - return; - } - WateringCan wateringCan = new WateringCan(config.getInt("water-can." + key + ".max"), width, config.getInt("water-can." + key + ".length")); - CANS.put(key, wateringCan); - }else { - AdventureManager.consoleMessage("[CustomCrops] Watering Can " + key + "'s key should be the same"); + int width = config.getInt("water-can." + key + ".width"); + if (width % 2 == 0){ + AdventureManager.consoleMessage("[CustomCrops] Watering Can " + key + "'s width should be odd!"); + return; } + String namespacedID = config.getString("water-can." + key + ".item"); + WateringCan wateringCan = new WateringCan(config.getInt("water-can." + key + ".max"), width, config.getInt("water-can." + key + ".length")); + CANS.put(namespacedID, wateringCan); }); } AdventureManager.consoleMessage("[CustomCrops] " + CANS.size() + " cans loaded!"); @@ -346,16 +290,13 @@ public class ConfigReader { SPRINKLERS.clear(); if (config.contains("sprinkler")){ config.getConfigurationSection("sprinkler").getKeys(false).forEach(key -> { - if (key.equals(StringUtils.split(config.getString("sprinkler." + key + ".3Ditem"),":")[1])){ - Sprinkler sprinklerData = new Sprinkler(config.getInt("sprinkler." + key + ".range"), config.getInt("sprinkler." + key + ".max-water")); - sprinklerData.setNamespacedID_2(config.getString("sprinkler." + key + ".3Ditem")); - String twoD = config.getString("sprinkler." + key + ".2Ditem"); - sprinklerData.setNamespacedID_1(twoD); - SPRINKLERS.put(key, sprinklerData); - SPRINKLERS.put(StringUtils.split(twoD,":")[1], sprinklerData); - }else { - AdventureManager.consoleMessage("[CustomCrops] Sprinkler " + key + "'s key should be the same with ItemsAdder 3D sprinkler's key"); - } + Sprinkler sprinklerData = new Sprinkler(config.getInt("sprinkler." + key + ".range"), config.getInt("sprinkler." + key + ".max-water")); + String threeD = config.getString("sprinkler." + key + ".3Ditem"); + sprinklerData.setNamespacedID_2(threeD); + String twoD = config.getString("sprinkler." + key + ".2Ditem"); + sprinklerData.setNamespacedID_1(twoD); + SPRINKLERS.put(threeD, sprinklerData); + SPRINKLERS.put(twoD, sprinklerData); }); } AdventureManager.consoleMessage("[CustomCrops] " + SPRINKLERS.size()/2 + " sprinklers loaded!"); @@ -371,25 +312,17 @@ public class ConfigReader { public static int duration; public static void loadSeason(){ + YamlConfiguration config = getConfig("season.yml"); - enable = config.getBoolean("season.enable",false); - if (enable){ - if (Config.growMode == 4){ - AdventureManager.consoleMessage("[CustomCrops] Warining: It's not advised to enable season in mode 4"); - } + if (Config.growMode == 4) AdventureManager.consoleMessage("[CustomCrops] Warining: It's not advised to enable season in mode 4"); greenhouse = config.getBoolean("season.greenhouse.enable",false); - if (greenhouse) { - range = config.getInt("season.greenhouse.range",7); - } + if (greenhouse) range = config.getInt("season.greenhouse.range",7); seasonChange = config.getBoolean("season.auto-season-change.enable",false); duration = config.getInt("season.auto-season-change.duration",28); - if (seasonChange) { - AdventureManager.consoleMessage("[CustomCrops] Season Change mode: Auto"); - }else { - AdventureManager.consoleMessage("[CustomCrops] Season Change mode: Command"); - } + if (seasonChange) AdventureManager.consoleMessage("[CustomCrops] Season Change mode: Auto"); + else AdventureManager.consoleMessage("[CustomCrops] Season Change mode: Command"); } } } @@ -495,30 +428,26 @@ public class ConfigReader { YamlConfiguration config = getConfig("crops.yml"); Set keys = config.getConfigurationSection("crops").getKeys(false); keys.forEach(key -> { - CropInstance cropInstance; + Crop cropInstance; if (config.contains("crops." + key + ".amount")){ String[] split = StringUtils.split(config.getString("crops." + key + ".amount"),"~"); - cropInstance = new CropInstance(Integer.parseInt(split[0]),Integer.parseInt(split[1])); + cropInstance = new Crop(Integer.parseInt(split[0]),Integer.parseInt(split[1])); }else { AdventureManager.consoleMessage("[CustomCrops] You forget to set " + key +"'s amount!"); return; } - if (config.contains("crops." + key + ".gigantic")){ + cropInstance.setGrowChance(config.getDouble("crops." + key + ".grow-chance", 1)); + if (config.contains("crops." + key + ".gigantic")) cropInstance.setGiant(config.getString("crops." + key + ".gigantic.block")); cropInstance.setGiantChance(config.getDouble("crops." + key + ".gigantic.chance")); - } - if (Season.enable && config.contains("crops." + key + ".season")){ + if (Season.enable && config.contains("crops." + key + ".season")) cropInstance.setSeasons(config.getStringList("crops." + key + ".season")); - } - if (config.contains("crops." + key + ".return")){ + if (config.contains("crops." + key + ".return")) cropInstance.setReturnStage(config.getString("crops." + key + ".return")); - } - if (config.contains("crops." + key + ".commands")){ + if (config.contains("crops." + key + ".commands")) cropInstance.setCommands(config.getStringList("crops." + key + ".commands")); - } - if (config.contains("crops." + key + ".skill-xp")){ + if (config.contains("crops." + key + ".skill-xp")) cropInstance.setSkillXP(config.getDouble("crops." + key + ".skill-xp")); - } if (config.contains("crops." + key + ".requirements")){ List requirements = new ArrayList<>(); config.getConfigurationSection("crops." + key + ".requirements").getValues(false).forEach((requirement, value) -> { @@ -531,23 +460,12 @@ public class ConfigReader { }); cropInstance.setRequirements(requirements); } - if (config.contains("crops." + key + ".grow-chance")){ - cropInstance.setGrowChance(config.getDouble("crops." + key + ".grow-chance")); - }else { - cropInstance.setGrowChance(1); - } if (Config.quality){ cropInstance.setQuality_1(config.getString("crops." + key + ".quality.1")); cropInstance.setQuality_2(config.getString("crops." + key + ".quality.2")); cropInstance.setQuality_3(config.getString("crops." + key + ".quality.3")); - if (config.contains("crops." + key + ".drop-ia-loots")){ - cropInstance.setDropIALoot(config.getBoolean("crops." + key + ".drop-ia-loots")); - }else { - cropInstance.setDropIALoot(false); - } - }else { - cropInstance.setDropIALoot(false); - } + cropInstance.setDropIALoot(config.getBoolean("crops." + key + ".drop-ia-loots", false)); + }else {cropInstance.setDropIALoot(false);} CROPS.put(key, cropInstance); }); AdventureManager.consoleMessage("[CustomCrops] " + CROPS.size() + " crops loaded!"); @@ -558,26 +476,27 @@ public class ConfigReader { YamlConfiguration config = getConfig("fertilizer.yml"); if (config.contains("speed")){ config.getConfigurationSection("speed").getKeys(false).forEach(key -> { - SpeedGrow speedGrow = new SpeedGrow(key, config.getInt("speed." + key + ".times"), config.getDouble("speed." + key + ".chance"), config.getBoolean("speed." + key + ".before-plant")); + String id = StringUtils.split(config.getString("speed." + key + ".item"), ":")[1]; + SpeedGrow speedGrow = new SpeedGrow(id, config.getInt("speed." + key + ".times"), config.getDouble("speed." + key + ".chance"), config.getBoolean("speed." + key + ".before-plant")); speedGrow.setName(config.getString("speed." + key + ".name")); - if (config.contains("speed." + key + ".particle")){ + if (config.contains("speed." + key + ".particle")) speedGrow.setParticle(Particle.valueOf(config.getString("speed." + key + ".particle").toUpperCase())); - } - FERTILIZERS.put(StringUtils.split(config.getString("speed." + key + ".item"), ":")[1], speedGrow); + FERTILIZERS.put(id, speedGrow); }); } if (config.contains("retaining")){ config.getConfigurationSection("retaining").getKeys(false).forEach(key -> { - RetainingSoil retainingSoil = new RetainingSoil(key, config.getInt("retaining." + key + ".times"), config.getDouble("retaining." + key + ".chance"), config.getBoolean("retaining." + key + ".before-plant")); + String id = StringUtils.split(config.getString("retaining." + key + ".item"), ":")[1]; + RetainingSoil retainingSoil = new RetainingSoil(id, config.getInt("retaining." + key + ".times"), config.getDouble("retaining." + key + ".chance"), config.getBoolean("retaining." + key + ".before-plant")); retainingSoil.setName(config.getString("retaining." + key + ".name")); - if (config.contains("retaining." + key + ".particle")){ + if (config.contains("retaining." + key + ".particle")) retainingSoil.setParticle(Particle.valueOf(config.getString("retaining." + key + ".particle").toUpperCase())); - } - FERTILIZERS.put(StringUtils.split(config.getString("retaining." + key + ".item"), ":")[1], retainingSoil); + FERTILIZERS.put(id, retainingSoil); }); } if (config.contains("quality")){ config.getConfigurationSection("quality").getKeys(false).forEach(key -> { + String id = StringUtils.split(config.getString("quality." + key + ".item"), ":")[1]; String[] split = StringUtils.split(config.getString("quality." + key + ".chance"), "/"); int[] weight = new int[3]; weight[0] = Integer.parseInt(split[0]); @@ -585,10 +504,9 @@ public class ConfigReader { weight[2] = Integer.parseInt(split[2]); QualityCrop qualityCrop = new QualityCrop(key, config.getInt("quality." + key + ".times"), weight, config.getBoolean("quality." + key + ".before-plant")); qualityCrop.setName(config.getString("quality." + key + ".name")); - if (config.contains("quality." + key + ".particle")){ + if (config.contains("quality." + key + ".particle")) qualityCrop.setParticle(Particle.valueOf(config.getString("quality." + key + ".particle").toUpperCase())); - } - FERTILIZERS.put(StringUtils.split(config.getString("quality." + key + ".item"), ":")[1], qualityCrop); + FERTILIZERS.put(id, qualityCrop); }); } AdventureManager.consoleMessage("[CustomCrops] " + FERTILIZERS.size() + " fertilizers loaded!"); @@ -597,65 +515,51 @@ public class ConfigReader { public static class Sounds{ public static Key waterPotKey; - public static net.kyori.adventure.sound.Sound.Source waterPotSource; - + public static Sound.Source waterPotSource; public static Key addWaterToCanKey; - public static net.kyori.adventure.sound.Sound.Source addWaterToCanSource; - + public static Sound.Source addWaterToCanSource; public static Key addWaterToSprinklerKey; - public static net.kyori.adventure.sound.Sound.Source addWaterToSprinklerSource; - + public static Sound.Source addWaterToSprinklerSource; public static Key placeSprinklerKey; - public static net.kyori.adventure.sound.Sound.Source placeSprinklerSource; - + public static Sound.Source placeSprinklerSource; public static Key plantSeedKey; - public static net.kyori.adventure.sound.Sound.Source plantSeedSource; - + public static Sound.Source plantSeedSource; public static Key useFertilizerKey; - public static net.kyori.adventure.sound.Sound.Source useFertilizerSource; - + public static Sound.Source useFertilizerSource; public static Key harvestKey; - public static net.kyori.adventure.sound.Sound.Source harvestSource; - + public static Sound.Source harvestSource; public static Key boneMealKey; - public static net.kyori.adventure.sound.Sound.Source boneMealSource; + public static Sound.Source boneMealSource; public static void loadSound(){ YamlConfiguration config = getConfig("sounds.yml"); - waterPotKey = Key.key(config.getString("water-pot.sound", "minecraft:block.water.ambient")); - waterPotSource = net.kyori.adventure.sound.Sound.Source.valueOf(config.getString("water-pot.type","player").toUpperCase()); - + waterPotSource = Sound.Source.valueOf(config.getString("water-pot.type","player").toUpperCase()); addWaterToCanKey = Key.key(config.getString("add-water-to-can.sound", "minecraft:item.bucket.fill")); - addWaterToCanSource = net.kyori.adventure.sound.Sound.Source.valueOf(config.getString("add-water-to-can.type","player").toUpperCase()); - + addWaterToCanSource = Sound.Source.valueOf(config.getString("add-water-to-can.type","player").toUpperCase()); addWaterToSprinklerKey = Key.key(config.getString("add-water-to-sprinkler.sound", "minecraft:item.bucket.fill")); - addWaterToSprinklerSource = net.kyori.adventure.sound.Sound.Source.valueOf(config.getString("add-water-to-sprinkler.type","player").toUpperCase()); - + addWaterToSprinklerSource = Sound.Source.valueOf(config.getString("add-water-to-sprinkler.type","player").toUpperCase()); placeSprinklerKey = Key.key(config.getString("place-sprinkler.sound", "minecraft:block.bone_block.place")); - placeSprinklerSource = net.kyori.adventure.sound.Sound.Source.valueOf(config.getString("place-sprinkler.type","player").toUpperCase()); - + placeSprinklerSource = Sound.Source.valueOf(config.getString("place-sprinkler.type","player").toUpperCase()); plantSeedKey = Key.key(config.getString("plant-seed.sound", "minecraft:item.hoe.till")); - plantSeedSource = net.kyori.adventure.sound.Sound.Source.valueOf(config.getString("plant-seed.type","player").toUpperCase()); - + plantSeedSource = Sound.Source.valueOf(config.getString("plant-seed.type","player").toUpperCase()); useFertilizerKey = Key.key(config.getString("use-fertilizer.sound", "minecraft:item.hoe.till")); - useFertilizerSource = net.kyori.adventure.sound.Sound.Source.valueOf(config.getString("use-fertilizer.type","player").toUpperCase()); - + useFertilizerSource = Sound.Source.valueOf(config.getString("use-fertilizer.type","player").toUpperCase()); harvestKey = Key.key(config.getString("harvest.sound", "minecraft:block.crop.break")); - harvestSource = net.kyori.adventure.sound.Sound.Source.valueOf(config.getString("harvest.type", "player").toUpperCase()); - + harvestSource = Sound.Source.valueOf(config.getString("harvest.type", "player").toUpperCase()); boneMealKey = Key.key(config.getString("bonemeal.sound", "minecraft:item.hoe.till")); - boneMealSource = net.kyori.adventure.sound.Sound.Source.valueOf(config.getString("bonemeal.type","player").toUpperCase()); + boneMealSource = Sound.Source.valueOf(config.getString("bonemeal.type","player").toUpperCase()); } } public static void tryEnableJedis(){ YamlConfiguration configuration = ConfigReader.getConfig("redis.yml"); - if (configuration.getBoolean("redis.enable")){ + JedisUtil.useRedis = configuration.getBoolean("redis.enable", false); + if (JedisUtil.useRedis) JedisUtil.initializeRedis(configuration); - JedisUtil.useRedis = true; - }else { - JedisUtil.useRedis = false; - } + } + + private static void hookMessage(String plugin){ + AdventureManager.consoleMessage("[CustomCrops] " + plugin + " Hooked!"); } } diff --git a/src/main/java/net/momirealms/customcrops/CustomCrops.java b/src/main/java/net/momirealms/customcrops/CustomCrops.java index 532bbd3..ceb6a74 100644 --- a/src/main/java/net/momirealms/customcrops/CustomCrops.java +++ b/src/main/java/net/momirealms/customcrops/CustomCrops.java @@ -21,7 +21,10 @@ import net.kyori.adventure.platform.bukkit.BukkitAudiences; import net.momirealms.customcrops.commands.Executor; import net.momirealms.customcrops.commands.Completer; import net.momirealms.customcrops.datamanager.*; +import net.momirealms.customcrops.datamanager.CropManager; +import net.momirealms.customcrops.datamanager.SprinklerManager; import net.momirealms.customcrops.helper.LibraryLoader; +import net.momirealms.customcrops.hook.Placeholders; import net.momirealms.customcrops.listener.*; import net.momirealms.customcrops.timer.CropTimer; import net.momirealms.customcrops.utils.*; @@ -60,10 +63,11 @@ public final class CustomCrops extends JavaPlugin { @Override public void onEnable() { - plugin = this; + adventure = BukkitAudiences.create(plugin); AdventureManager.consoleMessage("[CustomCrops] Running on " + Bukkit.getVersion()); - ConfigReader.ReloadConfig(); + ConfigReader.reloadConfig(); + if(Bukkit.getPluginManager().getPlugin("PlaceHolderAPI") != null){ placeholders = new Placeholders(); placeholders.register(); @@ -74,10 +78,12 @@ public final class CustomCrops extends JavaPlugin { Objects.requireNonNull(Bukkit.getPluginCommand("customcrops")).setExecutor(new Executor(this)); Objects.requireNonNull(Bukkit.getPluginCommand("customcrops")).setTabCompleter(new Completer()); + //公用事件 Bukkit.getPluginManager().registerEvents(new ItemSpawn(), this); + Bukkit.getPluginManager().registerEvents(new JoinAndQuit(), this); + Bukkit.getPluginManager().registerEvents(new RightClick(), this); Bukkit.getPluginManager().registerEvents(new BreakBlock(), this); - Bukkit.getPluginManager().registerEvents(new JoinAndQuit(), this); Bukkit.getPluginManager().registerEvents(new BreakFurniture(), this); Bukkit.getPluginManager().registerEvents(new InteractEntity(this), this); @@ -93,10 +99,10 @@ public final class CustomCrops extends JavaPlugin { this.sprinklerManager.loadData(); this.potManager = new PotManager(); this.potManager.loadData(); - this.cropTimer = new CropTimer(this); + this.cropTimer = new CropTimer(); checkIAConfig(); - if (ConfigReader.Config.version != 2){ - UpdateConfig.update(); + if (!Objects.equals(ConfigReader.Config.version, "3")){ + ConfigUtil.update(); } AdventureManager.consoleMessage("[CustomCrops] Plugin Enabled!"); } @@ -129,7 +135,7 @@ public final class CustomCrops extends JavaPlugin { } getLogger().info("Backing Up..."); - BackUp.backUpData(); + FileUtil.backUpData(); getLogger().info("Done."); if (cropTimer != null) { diff --git a/src/main/java/net/momirealms/customcrops/commands/Executor.java b/src/main/java/net/momirealms/customcrops/commands/Executor.java index cdde6cb..0349bb9 100644 --- a/src/main/java/net/momirealms/customcrops/commands/Executor.java +++ b/src/main/java/net/momirealms/customcrops/commands/Executor.java @@ -20,7 +20,7 @@ package net.momirealms.customcrops.commands; import net.momirealms.customcrops.utils.AdventureManager; import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.utils.BackUp; +import net.momirealms.customcrops.utils.FileUtil; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; @@ -53,7 +53,7 @@ public class Executor implements CommandExecutor { switch (args[0]){ case "reload" -> { long time = System.currentTimeMillis(); - ConfigReader.ReloadConfig(); + ConfigReader.reloadConfig(); if(sender instanceof Player){ AdventureManager.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.reload.replace("{time}", String.valueOf(System.currentTimeMillis() - time))); }else { @@ -139,7 +139,7 @@ public class Executor implements CommandExecutor { } } case "backup" -> { - BackUp.backUpData(); + FileUtil.backUpData(); if (sender instanceof Player player){ AdventureManager.playerMessage(player,ConfigReader.Message.prefix + ConfigReader.Message.backUp); }else { diff --git a/src/main/java/net/momirealms/customcrops/datamanager/CropManager.java b/src/main/java/net/momirealms/customcrops/datamanager/CropManager.java index d5d74e2..c034c83 100644 --- a/src/main/java/net/momirealms/customcrops/datamanager/CropManager.java +++ b/src/main/java/net/momirealms/customcrops/datamanager/CropManager.java @@ -26,9 +26,9 @@ import net.momirealms.customcrops.CustomCrops; import net.momirealms.customcrops.fertilizer.Fertilizer; import net.momirealms.customcrops.fertilizer.RetainingSoil; import net.momirealms.customcrops.fertilizer.SpeedGrow; -import net.momirealms.customcrops.utils.CropInstance; +import net.momirealms.customcrops.objects.Crop; import net.momirealms.customcrops.utils.JedisUtil; -import net.momirealms.customcrops.utils.SimpleLocation; +import net.momirealms.customcrops.objects.SimpleLocation; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -309,7 +309,7 @@ public class CropManager { } //农作物实例不存在 String[] cropNameList = StringUtils.split(id,"_"); - CropInstance cropInstance = ConfigReader.CROPS.get(cropNameList[0]); + Crop cropInstance = ConfigReader.CROPS.get(cropNameList[0]); if (cropInstance == null){ return true; } diff --git a/src/main/java/net/momirealms/customcrops/datamanager/PotManager.java b/src/main/java/net/momirealms/customcrops/datamanager/PotManager.java index 9a9fdcf..d82abc9 100644 --- a/src/main/java/net/momirealms/customcrops/datamanager/PotManager.java +++ b/src/main/java/net/momirealms/customcrops/datamanager/PotManager.java @@ -24,10 +24,8 @@ import net.momirealms.customcrops.fertilizer.Fertilizer; import net.momirealms.customcrops.fertilizer.QualityCrop; import net.momirealms.customcrops.fertilizer.RetainingSoil; import net.momirealms.customcrops.fertilizer.SpeedGrow; -import net.momirealms.customcrops.utils.SimpleLocation; +import net.momirealms.customcrops.objects.SimpleLocation; import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.file.YamlConfiguration; diff --git a/src/main/java/net/momirealms/customcrops/datamanager/SeasonManager.java b/src/main/java/net/momirealms/customcrops/datamanager/SeasonManager.java index 0241dae..2231c36 100644 --- a/src/main/java/net/momirealms/customcrops/datamanager/SeasonManager.java +++ b/src/main/java/net/momirealms/customcrops/datamanager/SeasonManager.java @@ -17,6 +17,7 @@ package net.momirealms.customcrops.datamanager; +import net.momirealms.customcrops.hook.RealisticSeason; import net.momirealms.customcrops.utils.AdventureManager; import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.CustomCrops; @@ -80,13 +81,17 @@ public class SeasonManager{ * @param world 世界 */ public void getSeason(World world) { - int season = (int) ((world.getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) / ConfigReader.Season.duration; - switch (season) { - case 0 -> SEASON.put(world.getName(), "spring"); - case 1 -> SEASON.put(world.getName(), "summer"); - case 2 -> SEASON.put(world.getName(), "autumn"); - case 3 -> SEASON.put(world.getName(), "winter"); - default -> AdventureManager.consoleMessage("[CustomCrops] 自动季节计算错误!"); + if (ConfigReader.Config.realisticSeason){ + SEASON.put(world.getName(), RealisticSeason.getSeason(world)); + }else { + int season = (int) ((world.getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) / ConfigReader.Season.duration; + switch (season) { + case 0 -> SEASON.put(world.getName(), "spring"); + case 1 -> SEASON.put(world.getName(), "summer"); + case 2 -> SEASON.put(world.getName(), "autumn"); + case 3 -> SEASON.put(world.getName(), "winter"); + default -> AdventureManager.consoleMessage("[CustomCrops] 自动季节计算错误!"); + } } } diff --git a/src/main/java/net/momirealms/customcrops/datamanager/SprinklerManager.java b/src/main/java/net/momirealms/customcrops/datamanager/SprinklerManager.java index cf9a1bf..0d36262 100644 --- a/src/main/java/net/momirealms/customcrops/datamanager/SprinklerManager.java +++ b/src/main/java/net/momirealms/customcrops/datamanager/SprinklerManager.java @@ -19,6 +19,8 @@ package net.momirealms.customcrops.datamanager; import dev.lone.itemsadder.api.CustomBlock; import net.momirealms.customcrops.listener.JoinAndQuit; +import net.momirealms.customcrops.objects.SimpleLocation; +import net.momirealms.customcrops.objects.Sprinkler; import net.momirealms.customcrops.utils.*; import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.CustomCrops; @@ -136,7 +138,7 @@ public class SprinklerManager { bukkitScheduler.runTask(CustomCrops.plugin, ()->{ int water = (int) map.get("water"); int range = (int) Optional.ofNullable(map.get("range")).orElse(0); - if(!IAFurniture.getFromLocation(location, world)){ + if(!IAFurnitureUtil.isSprinkler(location)){ data.set(worldName + "." + chunk + "." + key, null); return; } @@ -246,7 +248,7 @@ public class SprinklerManager { String[] coordinate = StringUtils.split(key, ","); Location location = new Location(world,Double.parseDouble(coordinate[0])+0.5,Double.parseDouble(coordinate[1])+0.5,Double.parseDouble(coordinate[2])+0.5); bukkitScheduler.runTask(CustomCrops.plugin, ()->{ - if(!IAFurniture.getFromLocation(location, world)){ + if(!IAFurnitureUtil.isSprinkler(location)){ data.set(worldName + "." + chunk + "." + key, null); return; } diff --git a/src/main/java/net/momirealms/customcrops/utils/Placeholders.java b/src/main/java/net/momirealms/customcrops/hook/Placeholders.java similarity index 86% rename from src/main/java/net/momirealms/customcrops/utils/Placeholders.java rename to src/main/java/net/momirealms/customcrops/hook/Placeholders.java index 2867bdf..21043b7 100644 --- a/src/main/java/net/momirealms/customcrops/utils/Placeholders.java +++ b/src/main/java/net/momirealms/customcrops/hook/Placeholders.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.utils; +package net.momirealms.customcrops.hook; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import net.momirealms.customcrops.ConfigReader; @@ -40,12 +40,13 @@ public class Placeholders extends PlaceholderExpansion{ @Override public @NotNull String getVersion() { - return "1.2"; + return "1.3"; } @Override public String onRequest(OfflinePlayer player, String params) { if (params.equalsIgnoreCase("season")){ + if (!ConfigReader.Season.enable) return "null"; return Optional.ofNullable(SeasonManager.SEASON.get(player.getPlayer().getWorld().getName())).orElse(ConfigReader.Message.noSeason) .replace("spring", ConfigReader.Message.spring) .replace("summer", ConfigReader.Message.summer) @@ -53,6 +54,7 @@ public class Placeholders extends PlaceholderExpansion{ .replace("winter", ConfigReader.Message.winter); } if (params.startsWith("season_")){ + if (!ConfigReader.Season.enable) return "null"; return SeasonManager.SEASON.get(params.substring(7)) .replace("spring", ConfigReader.Message.spring) .replace("summer", ConfigReader.Message.summer) @@ -60,21 +62,21 @@ public class Placeholders extends PlaceholderExpansion{ .replace("winter", ConfigReader.Message.winter); } if (params.equalsIgnoreCase("nextseason")){ - if (!ConfigReader.Config.worlds.contains(player.getPlayer().getWorld())){ - return ConfigReader.Message.noSeason; - } + if (!ConfigReader.Season.enable) return "null"; + if (!ConfigReader.Config.worlds.contains(player.getPlayer().getWorld())) return ConfigReader.Message.noSeason; return String.valueOf(ConfigReader.Season.duration - ((int) ((player.getPlayer().getWorld().getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) % ConfigReader.Season.duration)); } if (params.startsWith("nextseason_")){ + if (!ConfigReader.Season.enable) return "null"; return String.valueOf(ConfigReader.Season.duration - ((int) ((Bukkit.getWorld(params.substring(11)).getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) % ConfigReader.Season.duration)); } if (params.equalsIgnoreCase("current")){ - if (!ConfigReader.Config.worlds.contains(player.getPlayer().getWorld())){ - return ConfigReader.Message.noSeason; - } + if (!ConfigReader.Season.enable) return "null"; + if (!ConfigReader.Config.worlds.contains(player.getPlayer().getWorld())) return ConfigReader.Message.noSeason; return String.valueOf((int) ((player.getPlayer().getWorld().getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) % ConfigReader.Season.duration + 1); } if (params.startsWith("current_")){ + if (!ConfigReader.Season.enable) return "null"; return String.valueOf(((int) (Bukkit.getWorld(params.substring(8)).getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) % ConfigReader.Season.duration+ 1); } return null; diff --git a/src/main/java/net/momirealms/customcrops/hook/RealisticSeason.java b/src/main/java/net/momirealms/customcrops/hook/RealisticSeason.java new file mode 100644 index 0000000..06df7b2 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/hook/RealisticSeason.java @@ -0,0 +1,26 @@ +package net.momirealms.customcrops.hook; + +import me.casperge.realisticseasons.api.SeasonsAPI; +import org.bukkit.World; + +public class RealisticSeason { + + public static 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/customcrops/integrations/protection/KingdomsX.java b/src/main/java/net/momirealms/customcrops/integrations/protection/KingdomsX.java index d0c7707..8d4b3e9 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/KingdomsX.java +++ b/src/main/java/net/momirealms/customcrops/integrations/protection/KingdomsX.java @@ -44,10 +44,9 @@ public class KingdomsX implements Integration { if (kp.getKingdom() != null) { Kingdom kingdom = kp.getKingdom(); return kingdom != cropKingdom; - } else { - return false; } + else return false; } - return true; + else return true; } } diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/Lands.java b/src/main/java/net/momirealms/customcrops/integrations/protection/Lands.java index 46159ea..a954f29 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/Lands.java +++ b/src/main/java/net/momirealms/customcrops/integrations/protection/Lands.java @@ -29,20 +29,14 @@ public class Lands implements Integration{ @Override public boolean canBreak(Location location, Player player) { Area area = new LandsIntegration(CustomCrops.plugin).getAreaByLoc(location); - if (area != null){ - return area.hasFlag(player, Flags.BLOCK_BREAK, false); - }else { - return true; - } + if (area != null) return area.hasFlag(player, Flags.BLOCK_BREAK, false); + else return true; } @Override public boolean canPlace(Location location, Player player) { Area area = new LandsIntegration(CustomCrops.plugin).getAreaByLoc(location); - if (area != null){ - return area.hasFlag(player, Flags.BLOCK_PLACE, false); - }else { - return true; - } + if (area != null) return area.hasFlag(player, Flags.BLOCK_PLACE, false); + else return true; } } diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/PlotSquared.java b/src/main/java/net/momirealms/customcrops/integrations/protection/PlotSquared.java index a9e9679..b242718 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/PlotSquared.java +++ b/src/main/java/net/momirealms/customcrops/integrations/protection/PlotSquared.java @@ -35,10 +35,7 @@ public class PlotSquared implements Integration { private boolean isAllowed(org.bukkit.Location location, Player player) { Location plotLoc = Location.at(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); if (plotLoc.isPlotRoad()) return false; - if (plotLoc.getPlotArea() != null){ - return plotLoc.getPlotArea().getPlot(plotLoc).isAdded(player.getUniqueId()); - }else { - return true; - } + if (plotLoc.getPlotArea() != null) return plotLoc.getPlotArea().getPlot(plotLoc).isAdded(player.getUniqueId()); + else return true; } } diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/WorldGuard.java b/src/main/java/net/momirealms/customcrops/integrations/protection/WorldGuard.java index a25518d..76383c7 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/WorldGuard.java +++ b/src/main/java/net/momirealms/customcrops/integrations/protection/WorldGuard.java @@ -40,9 +40,8 @@ public class WorldGuard implements Integration { if (hasRegion(world, BukkitAdapter.asBlockVector(location))){ RegionQuery query = platform.getRegionContainer().createQuery(); return query.testBuild(BukkitAdapter.adapt(location), localPlayer, Flags.BUILD); - }else { - return true; } + else return true; } @Override @@ -53,9 +52,8 @@ public class WorldGuard implements Integration { if (hasRegion(world, BukkitAdapter.asBlockVector(location))){ RegionQuery query = platform.getRegionContainer().createQuery(); return query.testBuild(BukkitAdapter.adapt(location), localPlayer, Flags.BLOCK_BREAK); - }else { - return true; } + else return true; } private boolean hasRegion(World world, BlockVector3 vector){ diff --git a/src/main/java/net/momirealms/customcrops/limits/CropsPerChunk.java b/src/main/java/net/momirealms/customcrops/limits/CropsPerChunk.java index 8c659b9..2b03775 100644 --- a/src/main/java/net/momirealms/customcrops/limits/CropsPerChunk.java +++ b/src/main/java/net/momirealms/customcrops/limits/CropsPerChunk.java @@ -24,28 +24,22 @@ import org.bukkit.Location; public class CropsPerChunk { public static boolean isLimited(Location location){ - if(!ConfigReader.Config.enableLimit){ - return false; - } + if (!ConfigReader.Config.enableLimit) return false; int n = 1; Location chunkLocation = new Location(location.getWorld(),location.getChunk().getX()*16,ConfigReader.Config.yMin,location.getChunk().getZ()*16); Label_out: - for (int i = 0; i < 16; ++i) { + for (int i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) { Location square = chunkLocation.clone().add(i, 0.0, j); for (int k = ConfigReader.Config.yMin; k <= ConfigReader.Config.yMax; ++k) { square.add(0.0, 1.0, 0.0); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(square.getBlock()); - if(customBlock != null){ - if (customBlock.getNamespacedID().contains("_stage_")) { - if (n++ > ConfigReader.Config.cropLimit) { + if(customBlock != null) + if (customBlock.getNamespacedID().contains("_stage_")) + if (n++ > ConfigReader.Config.cropLimit) break Label_out; - } - } - } } } - } return n > ConfigReader.Config.cropLimit; } } diff --git a/src/main/java/net/momirealms/customcrops/limits/SprinklersPerChunk.java b/src/main/java/net/momirealms/customcrops/limits/SprinklersPerChunk.java index 5aa8061..ef04cf9 100644 --- a/src/main/java/net/momirealms/customcrops/limits/SprinklersPerChunk.java +++ b/src/main/java/net/momirealms/customcrops/limits/SprinklersPerChunk.java @@ -18,33 +18,26 @@ package net.momirealms.customcrops.limits; import net.momirealms.customcrops.ConfigReader; -import net.momirealms.customcrops.utils.IAFurniture; +import net.momirealms.customcrops.utils.IAFurnitureUtil; import org.bukkit.Location; -import org.bukkit.World; public class SprinklersPerChunk { public static boolean isLimited(Location location){ - if(!ConfigReader.Config.enableLimit){ - return false; - } + if (!ConfigReader.Config.enableLimit) return false; int n = 1; - Location chunkLocation = new Location(location.getWorld(),location.getChunk().getX()*16,ConfigReader.Config.yMin,location.getChunk().getZ()*16); - World world = location.getWorld(); + Location chunkLocation = new Location(location.getWorld(),location.getChunk().getX()*16, ConfigReader.Config.yMin,location.getChunk().getZ()*16); Label_out: - for (int i = 0; i < 16; ++i) { + for (int i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) { Location square = chunkLocation.clone().add(i + 0.5, 0.5, j + 0.5); for (int k = ConfigReader.Config.yMin; k <= ConfigReader.Config.yMax; ++k) { square.add(0.0, 1.0, 0.0); - if(IAFurniture.getFromLocation(square, world)){ - if (n++ > ConfigReader.Config.sprinklerLimit) { + if(IAFurnitureUtil.isSprinkler(square)) + if (n++ > ConfigReader.Config.sprinklerLimit) break Label_out; - } - } } } - } return n > ConfigReader.Config.sprinklerLimit; } } diff --git a/src/main/java/net/momirealms/customcrops/listener/BreakBlock.java b/src/main/java/net/momirealms/customcrops/listener/BreakBlock.java index 96b61aa..439976a 100644 --- a/src/main/java/net/momirealms/customcrops/listener/BreakBlock.java +++ b/src/main/java/net/momirealms/customcrops/listener/BreakBlock.java @@ -26,8 +26,8 @@ import net.momirealms.customcrops.datamanager.PotManager; import net.momirealms.customcrops.fertilizer.Fertilizer; import net.momirealms.customcrops.fertilizer.QualityCrop; import net.momirealms.customcrops.integrations.protection.Integration; -import net.momirealms.customcrops.utils.CropInstance; -import net.momirealms.customcrops.utils.SimpleLocation; +import net.momirealms.customcrops.objects.Crop; +import net.momirealms.customcrops.objects.SimpleLocation; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -51,77 +51,51 @@ public class BreakBlock implements Listener { if(namespacedId.contains("_stage_")){ Player player = event.getPlayer(); Location location = event.getBlock().getLocation(); - for (Integration integration : ConfigReader.Config.integration){ + for (Integration integration : ConfigReader.Config.integration) if(!integration.canBreak(location, player)) return; - } - if(player.getInventory().getItemInMainHand().containsEnchantment(Enchantment.SILK_TOUCH) || player.getInventory().getItemInMainHand().getType() == Material.SHEARS){ + if (player.getInventory().getItemInMainHand().containsEnchantment(Enchantment.SILK_TOUCH) || player.getInventory().getItemInMainHand().getType() == Material.SHEARS){ event.setCancelled(true); CustomBlock.place(namespacedId, location); - CustomBlock.byAlreadyPlaced(location.getBlock()).getLoot().forEach(itemStack -> { - location.getWorld().dropItem(location.clone().add(0.5,0.2,0.5), itemStack); - }); + CustomBlock.byAlreadyPlaced(location.getBlock()).getLoot().forEach(itemStack -> location.getWorld().dropItem(location.clone().add(0.5,0.2,0.5), itemStack)); CustomBlock.remove(location); return; } - if(!ConfigReader.Config.quality || namespacedId.equals(ConfigReader.Basic.dead)) return; + if (!ConfigReader.Config.quality || namespacedId.equals(ConfigReader.Basic.dead)) return; String[] cropNameList = StringUtils.split(StringUtils.split(namespacedId, ":")[1], "_"); int nextStage = Integer.parseInt(cropNameList[2]) + 1; if (CustomBlock.getInstance(StringUtils.chop(namespacedId) + nextStage) == null) { Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, ()-> { if (location.getBlock().getType() != Material.AIR) return; - CropInstance cropInstance = ConfigReader.CROPS.get(cropNameList[0]); + Crop cropInstance = ConfigReader.CROPS.get(cropNameList[0]); ThreadLocalRandom current = ThreadLocalRandom.current(); int random = current.nextInt(cropInstance.getMin(), cropInstance.getMax() + 1); Location itemLoc = location.clone().add(0.5,0.2,0.5); World world = location.getWorld(); - Fertilizer fertilizer = PotManager.Cache.get(SimpleLocation.fromLocation(location.clone().subtract(0,1,0))); List commands = cropInstance.getCommands(); - if (commands != null){ - Bukkit.getScheduler().callSyncMethod(CustomCrops.plugin, ()-> { - for (String command : commands){ + Fertilizer fertilizer = PotManager.Cache.get(SimpleLocation.fromLocation(location.clone().subtract(0,1,0))); + if (commands != null) + Bukkit.getScheduler().runTask(CustomCrops.plugin, ()-> { + for (String command : commands) Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName())); - } - return null; }); - } - if (ConfigReader.Config.skillXP != null && cropInstance.getSkillXP() != 0){ - Bukkit.getScheduler().callSyncMethod(CustomCrops.plugin, ()-> { - ConfigReader.Config.skillXP.addXp(player, cropInstance.getSkillXP()); - return null; - }); - } + if (ConfigReader.Config.skillXP != null && cropInstance.getSkillXP() != 0) + Bukkit.getScheduler().runTask(CustomCrops.plugin, ()-> ConfigReader.Config.skillXP.addXp(player, cropInstance.getSkillXP())); if (fertilizer != null){ if (fertilizer instanceof QualityCrop qualityCrop){ int[] weights = qualityCrop.getChance(); double weightTotal = weights[0] + weights[1] + weights[2]; - double rank_1 = weights[0]/(weightTotal); - double rank_2 = 1 - weights[1]/(weightTotal); - Bukkit.getScheduler().callSyncMethod(CustomCrops.plugin, ()-> { + Bukkit.getScheduler().runTask(CustomCrops.plugin, ()-> { for (int i = 0; i < random; i++){ double ran = Math.random(); - if (ran < rank_1){ - world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_1()).getItemStack()); - }else if(ran > rank_2){ - world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_2()).getItemStack()); - }else { - world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_3()).getItemStack()); - } + if (ran < weights[0]/(weightTotal)) world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_1()).getItemStack()); + else if(ran > 1 - weights[1]/(weightTotal)) world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_2()).getItemStack()); + else world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_3()).getItemStack()); } - return null; - }); - - }else { - Bukkit.getScheduler().callSyncMethod(CustomCrops.plugin, ()-> { - normalDrop(cropInstance, random, itemLoc, world); - return null; }); } - } else { - Bukkit.getScheduler().callSyncMethod(CustomCrops.plugin, ()-> { - normalDrop(cropInstance, random, itemLoc, world); - return null; - }); + else Bukkit.getScheduler().runTask(CustomCrops.plugin, ()-> normalDrop(cropInstance, random, itemLoc, world)); } + else Bukkit.getScheduler().runTask(CustomCrops.plugin, ()-> normalDrop(cropInstance, random, itemLoc, world)); }); } } @@ -130,9 +104,8 @@ public class BreakBlock implements Listener { PotManager.Cache.remove(SimpleLocation.fromLocation(location)); World world = location.getWorld(); Block blockUp = location.add(0,1,0).getBlock(); - for (Integration integration : ConfigReader.Config.integration){ + for (Integration integration : ConfigReader.Config.integration) if(!integration.canBreak(location, event.getPlayer())) return; - } if(CustomBlock.byAlreadyPlaced(blockUp) != null){ CustomBlock customBlock = CustomBlock.byAlreadyPlaced(blockUp); String cropNamespacedId = customBlock.getNamespacedID(); @@ -143,7 +116,7 @@ public class BreakBlock implements Listener { String[] cropNameList = StringUtils.split(StringUtils.split(cropNamespacedId, ":")[1], "_"); int nextStage = Integer.parseInt(cropNameList[2]) + 1; if (CustomBlock.getInstance(StringUtils.chop(cropNamespacedId) + nextStage) == null) { - CropInstance cropInstance = ConfigReader.CROPS.get(cropNameList[0]); + Crop cropInstance = ConfigReader.CROPS.get(cropNameList[0]); ThreadLocalRandom current = ThreadLocalRandom.current(); int random = current.nextInt(cropInstance.getMin(), cropInstance.getMax() + 1); Location itemLoc = location.clone().add(0.5,0.2,0.5); @@ -152,29 +125,20 @@ public class BreakBlock implements Listener { if (fertilizer instanceof QualityCrop qualityCrop){ int[] weights = qualityCrop.getChance(); double weightTotal = weights[0] + weights[1] + weights[2]; - double rank_1 = weights[0]/(weightTotal); - double rank_2 = 1 - weights[1]/(weightTotal); for (int i = 0; i < random; i++){ double ran = Math.random(); - if (ran < rank_1){ - world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_1()).getItemStack()); - }else if(ran > rank_2){ - world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_2()).getItemStack()); - }else { - world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_3()).getItemStack()); - } + if (ran < weights[0]/(weightTotal)) world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_1()).getItemStack()); + else if(ran > 1 - weights[1]/(weightTotal)) world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_2()).getItemStack()); + else world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_3()).getItemStack()); } } } - else { - normalDrop(cropInstance, random, itemLoc, world); - } + else normalDrop(cropInstance, random, itemLoc, world); return; } } - for (ItemStack itemStack : customBlock.getLoot()) { + for (ItemStack itemStack : customBlock.getLoot()) world.dropItem(location.clone().add(0.5, 0.2, 0.5), itemStack); - } CustomBlock.remove(location); } } @@ -188,7 +152,7 @@ public class BreakBlock implements Listener { * @param itemLoc 掉落物位置 * @param world 世界 */ - static void normalDrop(CropInstance cropInstance, int random, Location itemLoc, World world) { + static void normalDrop(Crop cropInstance, int random, Location itemLoc, World world) { for (int i = 0; i < random; i++){ double ran = Math.random(); if (ran < ConfigReader.Config.quality_1){ diff --git a/src/main/java/net/momirealms/customcrops/listener/BreakFurniture.java b/src/main/java/net/momirealms/customcrops/listener/BreakFurniture.java index 3cdd638..efa2cc4 100644 --- a/src/main/java/net/momirealms/customcrops/listener/BreakFurniture.java +++ b/src/main/java/net/momirealms/customcrops/listener/BreakFurniture.java @@ -3,9 +3,8 @@ package net.momirealms.customcrops.listener; import dev.lone.itemsadder.api.Events.FurnitureBreakEvent; import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.datamanager.SprinklerManager; -import net.momirealms.customcrops.utils.SimpleLocation; -import net.momirealms.customcrops.utils.Sprinkler; -import org.apache.commons.lang.StringUtils; +import net.momirealms.customcrops.objects.SimpleLocation; +import net.momirealms.customcrops.objects.Sprinkler; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -13,7 +12,7 @@ public class BreakFurniture implements Listener { @EventHandler public void onBreakFurniture(FurnitureBreakEvent event){ - Sprinkler config = ConfigReader.SPRINKLERS.get(StringUtils.split(event.getNamespacedID(),":")[1]); + Sprinkler config = ConfigReader.SPRINKLERS.get(event.getNamespacedID()); if (config != null){ SimpleLocation simpleLocation = SimpleLocation.fromLocation(event.getBukkitEntity().getLocation()); SprinklerManager.Cache.remove(simpleLocation); diff --git a/src/main/java/net/momirealms/customcrops/listener/InteractEntity.java b/src/main/java/net/momirealms/customcrops/listener/InteractEntity.java index 548fb69..41907dd 100644 --- a/src/main/java/net/momirealms/customcrops/listener/InteractEntity.java +++ b/src/main/java/net/momirealms/customcrops/listener/InteractEntity.java @@ -19,29 +19,25 @@ package net.momirealms.customcrops.listener; import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTItem; -import dev.lone.itemsadder.api.CustomFurniture; -import dev.lone.itemsadder.api.Events.FurnitureBreakEvent; import dev.lone.itemsadder.api.Events.FurnitureInteractEvent; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.CustomCrops; import net.momirealms.customcrops.datamanager.SprinklerManager; +import net.momirealms.customcrops.objects.SimpleLocation; +import net.momirealms.customcrops.objects.Sprinkler; +import net.momirealms.customcrops.objects.WateringCan; import net.momirealms.customcrops.utils.*; -import org.apache.commons.lang.StringUtils; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerInteractAtEntityEvent; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.List; -import java.util.Optional; public class InteractEntity implements Listener { @@ -55,13 +51,11 @@ public class InteractEntity implements Listener { @EventHandler public void onEntityInteract(FurnitureInteractEvent event){ - Sprinkler config = ConfigReader.SPRINKLERS.get(StringUtils.split(event.getNamespacedID(),":")[1]); + Sprinkler config = ConfigReader.SPRINKLERS.get(event.getNamespacedID()); if(config != null){ long time = System.currentTimeMillis(); Player player = event.getPlayer(); - if (time - (coolDown.getOrDefault(player, time - 200)) < 200) { - return; - } + if (time - (coolDown.getOrDefault(player, time - 200)) < 200) return; coolDown.put(player, time); ItemStack itemStack = player.getInventory().getItemInMainHand(); Location location = event.getBukkitEntity().getLocation(); @@ -77,17 +71,13 @@ public class InteractEntity implements Listener { if (sprinkler != null){ currentWater = sprinkler.getWater(); currentWater += ConfigReader.Config.sprinklerRefill; - if (currentWater > maxWater){ - currentWater = maxWater; - } + if (currentWater > maxWater) currentWater = maxWater; sprinkler.setWater(currentWater); }else { String path = world + "." + x / 16 + "," + z / 16 + "." + x + "," + location.getBlockY() + "," + z ; currentWater = plugin.getSprinklerManager().data.getInt(path+ ".water"); currentWater += ConfigReader.Config.sprinklerRefill; - if (currentWater > maxWater){ - currentWater = maxWater; - } + if (currentWater > maxWater) currentWater = maxWater; plugin.getSprinklerManager().data.set(path + ".water", currentWater); plugin.getSprinklerManager().data.set(path + ".range", config.getRange()); } @@ -101,36 +91,40 @@ public class InteractEntity implements Listener { NBTCompound nbtCompound = nbtItem.getCompound("itemsadder"); if (nbtCompound != null) { String id = nbtCompound.getString("id"); - Optional can = Optional.ofNullable(ConfigReader.CANS.get(id)); - if (can.isPresent()) { - WateringCan wateringCan = can.get(); - water--; - nbtItem.setInteger("WaterAmount", water); + String namespace = nbtCompound.getString("namespace"); + WateringCan wateringCan = ConfigReader.CANS.get(namespace + ":" + id); + if (wateringCan != null) { + nbtItem.setInteger("WaterAmount", --water); AdventureManager.playerSound(player, ConfigReader.Sounds.addWaterToSprinklerSource, ConfigReader.Sounds.addWaterToSprinklerKey); if (sprinkler != null){ currentWater = sprinkler.getWater(); currentWater++; - if (currentWater > maxWater){ - currentWater = maxWater; - } + if (currentWater > maxWater) currentWater = maxWater; sprinkler.setWater(currentWater); }else { String path = world + "." + x / 16 + "," + z / 16 + "." + x + "," + location.getBlockY() + "," + z + ".water"; currentWater = plugin.getSprinklerManager().data.getInt(path); currentWater++; - if (currentWater > maxWater){ - currentWater = maxWater; - } + if (currentWater > maxWater) currentWater = maxWater; plugin.getSprinklerManager().data.set(path, currentWater); } if (ConfigReader.Message.hasWaterInfo){ - String string = ConfigReader.Message.waterLeft + ConfigReader.Message.waterFull.repeat(water) + - ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water) + ConfigReader.Message.waterRight; - AdventureManager.playerActionbar(player, string.replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water))); + AdventureManager.playerActionbar(player, + (ConfigReader.Message.waterLeft + + ConfigReader.Message.waterFull.repeat(water) + + ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water) + + ConfigReader.Message.waterRight) + .replace("{max_water}", String.valueOf(wateringCan.getMax())) + .replace("{water}", String.valueOf(water))); } if (ConfigReader.Basic.hasWaterLore){ - String string = (ConfigReader.Basic.waterLeft + ConfigReader.Basic.waterFull.repeat(water) + - ConfigReader.Basic.waterEmpty.repeat(wateringCan.getMax() - water) + ConfigReader.Basic.waterRight).replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water)); + String string = + (ConfigReader.Basic.waterLeft + + ConfigReader.Basic.waterFull.repeat(water) + + ConfigReader.Basic.waterEmpty.repeat(wateringCan.getMax() - water) + + ConfigReader.Basic.waterRight) + .replace("{max_water}", String.valueOf(wateringCan.getMax())) + .replace("{water}", String.valueOf(water)); List lores = nbtItem.getCompound("display").getStringList("Lore"); lores.clear(); ConfigReader.Basic.waterLore.forEach(lore -> lores.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(lore.replace("{water_info}", string))))); @@ -138,21 +132,22 @@ public class InteractEntity implements Listener { itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); } } - }else { - currentWater = getCurrentWater(location, world, x, z, sprinkler); } + else currentWater = getCurrentWater(location, world, x, z, sprinkler); } - else { - currentWater = getCurrentWater(location, world, x, z, sprinkler); - } - } - if (ConfigReader.Message.hasSprinklerInfo){ - String string = ConfigReader.Message.sprinklerLeft + ConfigReader.Message.sprinklerFull.repeat(currentWater) + - ConfigReader.Message.sprinklerEmpty.repeat(maxWater - currentWater) + ConfigReader.Message.sprinklerRight; - if(!HoloUtil.cache.contains(location.add(0, ConfigReader.Message.sprinklerOffset,0))) { - HoloUtil.showHolo(string.replace("{max_water}", String.valueOf(maxWater)).replace("{water}", String.valueOf(currentWater)), player, location, ConfigReader.Message.sprinklerTime); - } + else currentWater = getCurrentWater(location, world, x, z, sprinkler); } + if (ConfigReader.Message.hasSprinklerInfo) + HoloUtil.showHolo( + (ConfigReader.Message.sprinklerLeft + + ConfigReader.Message.sprinklerFull.repeat(currentWater) + + ConfigReader.Message.sprinklerEmpty.repeat(maxWater - currentWater) + + ConfigReader.Message.sprinklerRight) + .replace("{max_water}", String.valueOf(maxWater)) + .replace("{water}", String.valueOf(currentWater)), + player, + location.add(0, ConfigReader.Message.sprinklerOffset,0), + ConfigReader.Message.sprinklerTime); } } @@ -167,9 +162,8 @@ public class InteractEntity implements Listener { */ private int getCurrentWater(Location location, String world, int x, int z, Sprinkler sprinkler) { int currentWater; - if (sprinkler != null){ - currentWater = sprinkler.getWater(); - }else { + if (sprinkler != null) currentWater = sprinkler.getWater(); + else { String path = world + "." + x / 16 + "," + z / 16 + "." + x + "," + location.getBlockY() + "," + z + ".water"; currentWater = plugin.getSprinklerManager().data.getInt(path); } diff --git a/src/main/java/net/momirealms/customcrops/listener/ItemSpawn.java b/src/main/java/net/momirealms/customcrops/listener/ItemSpawn.java index 15677ff..ee345f0 100644 --- a/src/main/java/net/momirealms/customcrops/listener/ItemSpawn.java +++ b/src/main/java/net/momirealms/customcrops/listener/ItemSpawn.java @@ -27,13 +27,9 @@ public class ItemSpawn implements Listener { @EventHandler public void entitySpawn(EntitySpawnEvent event){ - if(event.getEntity() instanceof Item item) { - if(CustomStack.byItemStack(item.getItemStack()) != null){ - String id = CustomStack.byItemStack(item.getItemStack()).getId(); - if(id.contains("_stage_")){ + if(event.getEntity() instanceof Item item) + if(CustomStack.byItemStack(item.getItemStack()) != null) + if(CustomStack.byItemStack(item.getItemStack()).getId().contains("_stage_")) item.remove(); - } - } - } } } \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/listener/JoinAndQuit.java b/src/main/java/net/momirealms/customcrops/listener/JoinAndQuit.java index 1996277..17ec447 100644 --- a/src/main/java/net/momirealms/customcrops/listener/JoinAndQuit.java +++ b/src/main/java/net/momirealms/customcrops/listener/JoinAndQuit.java @@ -14,19 +14,13 @@ public class JoinAndQuit implements Listener { @EventHandler public void onJoin(PlayerJoinEvent event){ - if (JedisUtil.useRedis){ - JedisUtil.addPlayer(event.getPlayer().getName()); - }else { - onlinePlayers.add(event.getPlayer().getName()); - } + if (JedisUtil.useRedis) JedisUtil.addPlayer(event.getPlayer().getName()); + else onlinePlayers.add(event.getPlayer().getName()); } @EventHandler public void onQuit(PlayerQuitEvent event){ - if (JedisUtil.useRedis){ - JedisUtil.remPlayer(event.getPlayer().getName()); - }else { - onlinePlayers.remove(event.getPlayer().getName()); - } + if (JedisUtil.useRedis) JedisUtil.remPlayer(event.getPlayer().getName()); + else onlinePlayers.remove(event.getPlayer().getName()); } } \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/listener/PapiReload.java b/src/main/java/net/momirealms/customcrops/listener/PapiReload.java index 2e4ebae..83de715 100644 --- a/src/main/java/net/momirealms/customcrops/listener/PapiReload.java +++ b/src/main/java/net/momirealms/customcrops/listener/PapiReload.java @@ -8,10 +8,8 @@ public class PapiReload implements Listener { @EventHandler public void onReload(me.clip.placeholderapi.events.ExpansionUnregisterEvent event){ - if (CustomCrops.placeholders != null){ - if (event.getExpansion().equals(CustomCrops.placeholders)){ + if (CustomCrops.placeholders != null) + if (event.getExpansion().equals(CustomCrops.placeholders)) CustomCrops.placeholders.register(); - } - } } } diff --git a/src/main/java/net/momirealms/customcrops/listener/RightClick.java b/src/main/java/net/momirealms/customcrops/listener/RightClick.java index 4a4f65c..031dd24 100644 --- a/src/main/java/net/momirealms/customcrops/listener/RightClick.java +++ b/src/main/java/net/momirealms/customcrops/listener/RightClick.java @@ -35,6 +35,10 @@ import net.momirealms.customcrops.fertilizer.SpeedGrow; import net.momirealms.customcrops.integrations.protection.Integration; import net.momirealms.customcrops.limits.CropsPerChunk; import net.momirealms.customcrops.limits.SprinklersPerChunk; +import net.momirealms.customcrops.objects.Crop; +import net.momirealms.customcrops.objects.SimpleLocation; +import net.momirealms.customcrops.objects.Sprinkler; +import net.momirealms.customcrops.objects.WateringCan; import net.momirealms.customcrops.requirements.PlantingCondition; import net.momirealms.customcrops.requirements.Requirement; import net.momirealms.customcrops.utils.*; @@ -52,7 +56,6 @@ import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.List; -import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; public class RightClick implements Listener { @@ -63,9 +66,7 @@ public class RightClick implements Listener { public void onInteract(PlayerInteractEvent event){ long time = System.currentTimeMillis(); Player player = event.getPlayer(); - if (time - (coolDown.getOrDefault(player, time - 250)) < 250) { - return; - } + if (time - (coolDown.getOrDefault(player, time - 250)) < 250) return; coolDown.put(player, time); Action action = event.getAction(); if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK){ @@ -75,82 +76,61 @@ public class RightClick implements Listener { NBTCompound nbtCompound = nbtItem.getCompound("itemsadder"); if (nbtCompound != null){ String id = nbtCompound.getString("id"); + String namespace = nbtCompound.getString("namespace"); + String itemNID = namespace + ":" + id; if (id.endsWith("_seeds") && action == Action.RIGHT_CLICK_BLOCK && event.getBlockFace() == BlockFace.UP){ String cropName = StringUtils.remove(id, "_seeds"); - Optional crop = Optional.ofNullable(ConfigReader.CROPS.get(cropName)); - if (crop.isPresent()){ + Crop cropInstance = ConfigReader.CROPS.get(cropName); + if (cropInstance != null){ Block block = event.getClickedBlock(); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); if (customBlock == null) return; String namespacedID = customBlock.getNamespacedID(); if (namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)){ Location location = block.getLocation().add(0,1,0); //已+1 - for (Integration integration : ConfigReader.Config.integration){ + for (Integration integration : ConfigReader.Config.integration) if(!integration.canPlace(location, player)) return; - } - if(IAFurniture.getFromLocation(location.clone().add(0.5, 0.5, 0.5), location.getWorld())){ - return; - } - CropInstance cropInstance = crop.get(); + if(IAFurnitureUtil.isSprinkler(location.clone().add(0.5, 0.5, 0.5))) return; PlantingCondition plantingCondition = new PlantingCondition(player, location); - if (cropInstance.getRequirements() != null){ - for (Requirement requirement : cropInstance.getRequirements()){ + if (cropInstance.getRequirements() != null) + for (Requirement requirement : cropInstance.getRequirements()) if (!requirement.canPlant(plantingCondition)) return; - } - } Label_out: if (ConfigReader.Season.enable && cropInstance.getSeasons() != null){ if (!ConfigReader.Config.allWorld){ - for (String season : cropInstance.getSeasons()) { - if (season.equals(SeasonManager.SEASON.get(location.getWorld().getName()))){ + for (String season : cropInstance.getSeasons()) + if (season.equals(SeasonManager.SEASON.get(location.getWorld().getName()))) break Label_out; - } - } }else { - for(String season : cropInstance.getSeasons()){ - if (season.equals(SeasonManager.SEASON.get(ConfigReader.Config.referenceWorld))) { + for(String season : cropInstance.getSeasons()) + if (season.equals(SeasonManager.SEASON.get(ConfigReader.Config.referenceWorld))) break Label_out; - } - } } if(ConfigReader.Season.greenhouse){ for(int i = 1; i <= ConfigReader.Season.range; i++){ CustomBlock cb = CustomBlock.byAlreadyPlaced(location.clone().add(0,i,0).getBlock()); - if (cb != null){ - if(cb.getNamespacedID().equalsIgnoreCase(ConfigReader.Basic.glass)){ + if (cb != null) + if(cb.getNamespacedID().equalsIgnoreCase(ConfigReader.Basic.glass)) break Label_out; - } - } } } - if (ConfigReader.Config.nwSeason){ - AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.badSeason); - } - if (ConfigReader.Config.pwSeason){ - return; - } - } - if (location.getBlock().getType() != Material.AIR){ - return; + if (ConfigReader.Config.nwSeason) AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.badSeason); + if (ConfigReader.Config.pwSeason) return; } + if (location.getBlock().getType() != Material.AIR) return; + if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1); if (CropsPerChunk.isLimited(location)){ AdventureManager.playerMessage(player,ConfigReader.Message.prefix + ConfigReader.Message.crop_limit.replace("{max}", String.valueOf(ConfigReader.Config.cropLimit))); return; } - if (player.getGameMode() != GameMode.CREATIVE){ - itemStack.setAmount(itemStack.getAmount() - 1); - } CropManager.Cache.put(location, player.getName()); - CustomBlock.place((nbtCompound.getString("namespace") + ":" + cropName + "_stage_1"), location); + CustomBlock.place((namespace + ":" + cropName + "_stage_1"), location); AdventureManager.playerSound(player, ConfigReader.Sounds.plantSeedSource, ConfigReader.Sounds.plantSeedKey); - return; } - }else { - AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.not_configed); - } + }else AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.not_configed); return; } - WateringCan wateringCan = ConfigReader.CANS.get(id); + WateringCan wateringCan = ConfigReader.CANS.get(itemNID); if (wateringCan != null){ int water = nbtItem.getInteger("WaterAmount"); List lineOfSight = player.getLineOfSight(null, 5); @@ -158,27 +138,30 @@ public class RightClick implements Listener { if (block.getType() == Material.WATER) { if (wateringCan.getMax() > water){ water += ConfigReader.Config.waterCanRefill; - if (water > wateringCan.getMax()){ - water = wateringCan.getMax(); - } + if (water > wateringCan.getMax()) water = wateringCan.getMax(); nbtItem.setInteger("WaterAmount", water); player.getWorld().playSound(player.getLocation(), Sound.ITEM_BUCKET_FILL,1,1); - - if (ConfigReader.Message.hasWaterInfo){ - String string = ConfigReader.Message.waterLeft + ConfigReader.Message.waterFull.repeat(water) + - ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water) + ConfigReader.Message.waterRight; - AdventureManager.playerActionbar(player, string.replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water))); - } + if (ConfigReader.Message.hasWaterInfo) + AdventureManager.playerActionbar(player, + (ConfigReader.Message.waterLeft + + ConfigReader.Message.waterFull.repeat(water) + + ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water) + + ConfigReader.Message.waterRight) + .replace("{max_water}", String.valueOf(wateringCan.getMax())) + .replace("{water}", String.valueOf(water))); if (ConfigReader.Basic.hasWaterLore){ - String string = (ConfigReader.Basic.waterLeft + ConfigReader.Basic.waterFull.repeat(water) + - ConfigReader.Basic.waterEmpty.repeat(wateringCan.getMax() - water) + ConfigReader.Basic.waterRight).replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water)); List lores = nbtItem.getCompound("display").getStringList("Lore"); lores.clear(); + String string = + (ConfigReader.Basic.waterLeft + + ConfigReader.Basic.waterFull.repeat(water) + + ConfigReader.Basic.waterEmpty.repeat(wateringCan.getMax() - water) + + ConfigReader.Basic.waterRight) + .replace("{max_water}", String.valueOf(wateringCan.getMax())) + .replace("{water}", String.valueOf(water)); ConfigReader.Basic.waterLore.forEach(lore -> lores.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(lore.replace("{water_info}", string))))); } - if (ConfigReader.Config.hasParticle){ - player.getWorld().spawnParticle(Particle.WATER_SPLASH, block.getLocation().add(0.5,1, 0.5),15,0.1,0.1,0.1); - } + if (ConfigReader.Config.hasParticle) player.getWorld().spawnParticle(Particle.WATER_SPLASH, block.getLocation().add(0.5,1, 0.5),15,0.1,0.1,0.1); itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); } return; @@ -188,41 +171,57 @@ public class RightClick implements Listener { Block block = event.getClickedBlock(); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); if (customBlock == null) return; - for (Integration integration : ConfigReader.Config.integration){ + for (Integration integration : ConfigReader.Config.integration) if(!integration.canPlace(block.getLocation(), player)) return; - } String namespacedID = customBlock.getNamespacedID(); if ((namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)) && event.getBlockFace() == BlockFace.UP){ nbtItem.setInteger("WaterAmount", water - 1); AdventureManager.playerSound(player, ConfigReader.Sounds.waterPotSource, ConfigReader.Sounds.waterPotKey); waterPot(wateringCan.getWidth(), wateringCan.getLength(), block.getLocation(), player.getLocation().getYaw()); - if (ConfigReader.Message.hasWaterInfo){ - String string = ConfigReader.Message.waterLeft + ConfigReader.Message.waterFull.repeat(water - 1) + - ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water + 1) + ConfigReader.Message.waterRight; - AdventureManager.playerActionbar(player, string.replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water -1))); - } + if (ConfigReader.Message.hasWaterInfo) + AdventureManager.playerActionbar(player, + (ConfigReader.Message.waterLeft + + ConfigReader.Message.waterFull.repeat(water - 1) + + ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water + 1) + + ConfigReader.Message.waterRight) + .replace("{max_water}", String.valueOf(wateringCan.getMax())) + .replace("{water}", String.valueOf(water -1))); if (ConfigReader.Basic.hasWaterLore){ - String string = (ConfigReader.Basic.waterLeft + ConfigReader.Basic.waterFull.repeat(water - 1) + - ConfigReader.Basic.waterEmpty.repeat(wateringCan.getMax() - water + 1) + ConfigReader.Basic.waterRight).replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water -1)); List lores = nbtItem.getCompound("display").getStringList("Lore"); lores.clear(); + String string = + (ConfigReader.Basic.waterLeft + + ConfigReader.Basic.waterFull.repeat(water - 1) + + ConfigReader.Basic.waterEmpty.repeat(wateringCan.getMax() - water + 1) + + ConfigReader.Basic.waterRight) + .replace("{max_water}", String.valueOf(wateringCan.getMax())) + .replace("{water}", String.valueOf(water -1)); ConfigReader.Basic.waterLore.forEach(lore -> lores.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(lore.replace("{water_info}", string))))); } itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); - } else if (namespacedID.contains("_stage_")){ + } + else if (namespacedID.contains("_stage_")){ nbtItem.setInteger("WaterAmount", water - 1); AdventureManager.playerSound(player, ConfigReader.Sounds.waterPotSource, ConfigReader.Sounds.waterPotKey); waterPot(wateringCan.getWidth(), wateringCan.getLength(), block.getLocation().subtract(0,1,0), player.getLocation().getYaw()); - if (ConfigReader.Message.hasWaterInfo){ - String string = ConfigReader.Message.waterLeft + ConfigReader.Message.waterFull.repeat(water - 1) + - ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water + 1) + ConfigReader.Message.waterRight; - AdventureManager.playerActionbar(player, string.replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water -1))); - } + if (ConfigReader.Message.hasWaterInfo) + AdventureManager.playerActionbar(player, + (ConfigReader.Message.waterLeft + + ConfigReader.Message.waterFull.repeat(water - 1) + + ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water + 1) + + ConfigReader.Message.waterRight) + .replace("{max_water}", String.valueOf(wateringCan.getMax())) + .replace("{water}", String.valueOf(water -1))); if (ConfigReader.Basic.hasWaterLore){ - String string = (ConfigReader.Basic.waterLeft + ConfigReader.Basic.waterFull.repeat(water - 1) + - ConfigReader.Basic.waterEmpty.repeat(wateringCan.getMax() - water + 1) + ConfigReader.Basic.waterRight).replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water -1)); List lores = nbtItem.getCompound("display").getStringList("Lore"); lores.clear(); + String string = + (ConfigReader.Basic.waterLeft + + ConfigReader.Basic.waterFull.repeat(water - 1) + + ConfigReader.Basic.waterEmpty.repeat(wateringCan.getMax() - water + 1) + + ConfigReader.Basic.waterRight) + .replace("{max_water}", String.valueOf(wateringCan.getMax())) + .replace("{water}", String.valueOf(water -1)); ConfigReader.Basic.waterLore.forEach(lore -> lores.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(lore.replace("{water_info}", string))))); } itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); @@ -235,9 +234,8 @@ public class RightClick implements Listener { Block block = event.getClickedBlock(); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); if (customBlock == null) return; - for (Integration integration : ConfigReader.Config.integration){ + for (Integration integration : ConfigReader.Config.integration) if(!integration.canPlace(block.getLocation(), player)) return; - } String namespacedID = customBlock.getNamespacedID(); if (namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)){ CustomBlock customBlockUp = CustomBlock.byAlreadyPlaced(block.getLocation().clone().add(0,1,0).getBlock()); @@ -246,24 +244,18 @@ public class RightClick implements Listener { AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.beforePlant); return; }else { - if (player.getGameMode() != GameMode.CREATIVE){ - itemStack.setAmount(itemStack.getAmount() - 1); - } + if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1); AdventureManager.playerSound(player, ConfigReader.Sounds.useFertilizerSource, ConfigReader.Sounds.useFertilizerKey); addFertilizer(fertilizerConfig, block.getLocation()); } }else { - if (player.getGameMode() != GameMode.CREATIVE){ - itemStack.setAmount(itemStack.getAmount() - 1); - } + if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1); AdventureManager.playerSound(player, ConfigReader.Sounds.useFertilizerSource, ConfigReader.Sounds.useFertilizerKey); addFertilizer(fertilizerConfig, block.getLocation()); } }else if (namespacedID.contains("_stage_")){ if (!fertilizerConfig.isBefore()){ - if (player.getGameMode() != GameMode.CREATIVE){ - itemStack.setAmount(itemStack.getAmount() - 1); - } + if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1); addFertilizer(fertilizerConfig, block.getLocation().subtract(0,1,0)); AdventureManager.playerSound(player, ConfigReader.Sounds.useFertilizerSource, ConfigReader.Sounds.useFertilizerKey); }else { @@ -273,49 +265,46 @@ public class RightClick implements Listener { } return; } - Sprinkler sprinkler = ConfigReader.SPRINKLERS.get(id); + Sprinkler sprinkler = ConfigReader.SPRINKLERS.get(itemNID); if (sprinkler != null && action == Action.RIGHT_CLICK_BLOCK && event.getBlockFace() == BlockFace.UP){ Location location = event.getClickedBlock().getLocation(); - for (Integration integration : ConfigReader.Config.integration){ + for (Integration integration : ConfigReader.Config.integration) if (!integration.canPlace(location, player)) return; - } - if(IAFurniture.getFromLocation(location.clone().add(0.5, 1.5, 0.5), location.getWorld())){ - return; - } - if(SprinklersPerChunk.isLimited(location)){ + if (IAFurnitureUtil.isSprinkler(location.clone().add(0.5, 1.5, 0.5))) return; + if (SprinklersPerChunk.isLimited(location)){ AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.sprinkler_limit.replace("{max}", String.valueOf(ConfigReader.Config.sprinklerLimit))); return; } Sprinkler sprinklerData = new Sprinkler(sprinkler.getRange(), 0); sprinklerData.setPlayer(player.getName()); - if (player.getGameMode() != GameMode.CREATIVE){ - itemStack.setAmount(itemStack.getAmount() - 1); - } + if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1); SimpleLocation simpleLocation = SimpleLocation.fromLocation(location.add(0,1,0)); SprinklerManager.Cache.put(simpleLocation, sprinklerData); SprinklerManager.RemoveCache.remove(simpleLocation); - IAFurniture.placeFurniture(sprinkler.getNamespacedID_2(),location); + IAFurnitureUtil.placeFurniture(sprinkler.getNamespacedID_2(),location); AdventureManager.playerSound(player, ConfigReader.Sounds.placeSprinklerSource, ConfigReader.Sounds.placeSprinklerKey); return; } - if (ConfigReader.Message.hasCropInfo && id.equals(ConfigReader.Basic.soilDetector) && action == Action.RIGHT_CLICK_BLOCK){ + if (ConfigReader.Message.hasCropInfo && itemNID.equals(ConfigReader.Basic.soilDetector) && action == Action.RIGHT_CLICK_BLOCK){ Block block = event.getClickedBlock(); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); if (customBlock == null) return; - for (Integration integration : ConfigReader.Config.integration){ - if(!integration.canPlace(block.getLocation(), player)) return; - } + for (Integration integration : ConfigReader.Config.integration) if(!integration.canPlace(block.getLocation(), player)) return; String namespacedID = customBlock.getNamespacedID(); if (namespacedID.contains("_stage_")){ Location location = block.getLocation().subtract(0,1,0); Fertilizer fertilizer = PotManager.Cache.get(SimpleLocation.fromLocation(location)); if (fertilizer != null){ Fertilizer config = ConfigReader.FERTILIZERS.get(fertilizer.getKey()); - String name = config.getName(); - int max_times = config.getTimes(); - if(!HoloUtil.cache.contains(location.add(0.5, ConfigReader.Message.cropOffset, 0.5))) { - HoloUtil.showHolo(ConfigReader.Message.cropText.replace("{fertilizer}", name).replace("{times}", String.valueOf(fertilizer.getTimes())).replace("{max_times}", String.valueOf(max_times)), player, location, ConfigReader.Message.cropTime); - } + if (config == null) return; + HoloUtil.showHolo( + ConfigReader.Message.cropText + .replace("{fertilizer}", config.getName()) + .replace("{times}", String.valueOf(fertilizer.getTimes())) + .replace("{max_times}", String.valueOf(config.getTimes())), + player, + location.add(0.5, ConfigReader.Message.cropOffset, 0.5), + ConfigReader.Message.cropTime); } }else if(namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)){ Location location = block.getLocation(); @@ -324,9 +313,14 @@ public class RightClick implements Listener { Fertilizer config = ConfigReader.FERTILIZERS.get(fertilizer.getKey()); String name = config.getName(); int max_times = config.getTimes(); - if(!HoloUtil.cache.contains(location.add(0.5,ConfigReader.Message.cropOffset,0.5))){ - HoloUtil.showHolo(ConfigReader.Message.cropText.replace("{fertilizer}", name).replace("{times}", String.valueOf(fertilizer.getTimes())).replace("{max_times}", String.valueOf(max_times)), player, location, ConfigReader.Message.cropTime); - } + HoloUtil.showHolo( + ConfigReader.Message.cropText + .replace("{fertilizer}", name) + .replace("{times}", String.valueOf(fertilizer.getTimes())) + .replace("{max_times}", String.valueOf(max_times)), + player, + location.add(0.5,ConfigReader.Message.cropOffset,0.5), + ConfigReader.Message.cropTime); } } } @@ -335,18 +329,15 @@ public class RightClick implements Listener { Block block = event.getClickedBlock(); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); if (customBlock == null) return; - for (Integration integration : ConfigReader.Config.integration){ + for (Integration integration : ConfigReader.Config.integration) if(!integration.canPlace(block.getLocation(), player)) return; - } String namespacedID = customBlock.getNamespacedID(); if (namespacedID.contains("_stage_") && !namespacedID.equals(ConfigReader.Basic.dead)){ int nextStage = Integer.parseInt(namespacedID.substring(namespacedID.length()-1)) + 1; String next = StringUtils.chop(namespacedID) + nextStage; if (CustomBlock.getInstance(next) != null){ Location location = block.getLocation(); - if (player.getGameMode() != GameMode.CREATIVE){ - itemStack.setAmount(itemStack.getAmount() - 1); - } + if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1); AdventureManager.playerSound(player, ConfigReader.Sounds.boneMealSource, ConfigReader.Sounds.boneMealKey); if (Math.random() < ConfigReader.Config.boneMealChance){ CustomBlock.remove(location); @@ -356,13 +347,11 @@ public class RightClick implements Listener { } } } - else if(ConfigReader.Config.rightClickHarvest && !ConfigReader.Config.needEmptyHand && action == Action.RIGHT_CLICK_BLOCK){ + else if(ConfigReader.Config.rightClickHarvest && !ConfigReader.Config.needEmptyHand && action == Action.RIGHT_CLICK_BLOCK) rightClickHarvest(event.getClickedBlock(), player); - } } - else if (ConfigReader.Config.rightClickHarvest && action == Action.RIGHT_CLICK_BLOCK) { + else if (ConfigReader.Config.rightClickHarvest && action == Action.RIGHT_CLICK_BLOCK) rightClickHarvest(event.getClickedBlock(), player); - } } } @@ -375,62 +364,43 @@ public class RightClick implements Listener { Location location = block.getLocation(); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); if (customBlock == null) return; - for (Integration integration : ConfigReader.Config.integration){ + for (Integration integration : ConfigReader.Config.integration) if (!integration.canBreak(location, player)) return; - } String namespacedID = customBlock.getNamespacedID(); if (namespacedID.contains("_stage_")){ if(namespacedID.equals(ConfigReader.Basic.dead)) return; String[] cropNameList = StringUtils.split(customBlock.getId(), "_"); int nextStage = Integer.parseInt(cropNameList[2]) + 1; if (CustomBlock.getInstance(StringUtils.chop(namespacedID) + nextStage) == null) { - CropInstance cropInstance = ConfigReader.CROPS.get(cropNameList[0]); + Crop cropInstance = ConfigReader.CROPS.get(cropNameList[0]); if (ConfigReader.Config.quality){ ThreadLocalRandom current = ThreadLocalRandom.current(); int random = current.nextInt(cropInstance.getMin(), cropInstance.getMax() + 1); World world = location.getWorld(); Location itemLoc = location.clone().add(0.5,0.2,0.5); - Fertilizer fertilizer = PotManager.Cache.get(location.clone().subtract(0,1,0)); + Fertilizer fertilizer = PotManager.Cache.get(SimpleLocation.fromLocation(location.clone().subtract(0,1,0))); List commands = cropInstance.getCommands(); - if (commands != null){ - for (String command : commands){ + if (commands != null) + for (String command : commands) Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName())); - } - } - if (ConfigReader.Config.skillXP != null && cropInstance.getSkillXP() != 0){ - ConfigReader.Config.skillXP.addXp(player, cropInstance.getSkillXP()); - } - if (cropInstance.doesDropIALoot()){ - customBlock.getLoot().forEach(itemStack -> { - location.getWorld().dropItem(location.clone().add(0.5,0.2,0.5), itemStack); - }); - } + if (ConfigReader.Config.skillXP != null && cropInstance.getSkillXP() != 0) ConfigReader.Config.skillXP.addXp(player, cropInstance.getSkillXP()); + if (cropInstance.doesDropIALoot()) customBlock.getLoot().forEach(itemStack -> location.getWorld().dropItem(location.clone().add(0.5,0.2,0.5), itemStack)); if (fertilizer != null){ if (fertilizer instanceof QualityCrop qualityCrop){ int[] weights = qualityCrop.getChance(); double weightTotal = weights[0] + weights[1] + weights[2]; - double rank_1 = weights[0]/(weightTotal); - double rank_2 = 1 - weights[1]/(weightTotal); for (int i = 0; i < random; i++){ double ran = Math.random(); - if (ran < rank_1){ - world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_1()).getItemStack()); - }else if(ran > rank_2){ - world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_2()).getItemStack()); - }else { - world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_3()).getItemStack()); - } + if (ran < weights[0]/(weightTotal)) world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_1()).getItemStack()); + else if(ran > 1 - weights[1]/(weightTotal)) world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_2()).getItemStack()); + else world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_3()).getItemStack()); } - }else { - BreakBlock.normalDrop(cropInstance, random, itemLoc, world); } + else BreakBlock.normalDrop(cropInstance, random, itemLoc, world); } - else { - BreakBlock.normalDrop(cropInstance, random, itemLoc, world); - } - }else { - customBlock.getLoot().forEach(loot-> location.getWorld().dropItem(location.clone().add(0.5,0.2,0.5), loot)); + else BreakBlock.normalDrop(cropInstance, random, itemLoc, world); } + else customBlock.getLoot().forEach(loot-> location.getWorld().dropItem(location.clone().add(0.5,0.2,0.5), loot)); CustomBlock.remove(location); AdventureManager.playerSound(player, ConfigReader.Sounds.harvestSource, ConfigReader.Sounds.harvestKey); if(cropInstance.getReturnStage() != null){ @@ -462,9 +432,8 @@ public class RightClick implements Listener { RetainingSoil retainingSoil = new RetainingSoil(config.getKey(), config.getTimes(),config.getChance(), config.isBefore()); PotManager.Cache.put(SimpleLocation.fromLocation(location), retainingSoil); } - if (fertilizerConfig.getParticle() != null){ + if (fertilizerConfig.getParticle() != null) location.getWorld().spawnParticle(fertilizerConfig.getParticle(), location.add(0.5,1.3,0.5), 5,0.2,0.2,0.2); - } } /** @@ -475,16 +444,10 @@ public class RightClick implements Listener { * @param yaw 视角 */ private void waterPot(int width, int length, Location location, float yaw){ - if (ConfigReader.Config.hasParticle){ + if (ConfigReader.Config.hasParticle) location.getWorld().spawnParticle(Particle.WATER_SPLASH, location.clone().add(0.5,1.2,0.5),15,0.1,0.1, 0.1); - } int extend = width / 2; - // -90~90 z+ - // -180~-90 & 90-180 z- - // -180~0 x+ - // 0~180 x- if (yaw < 45 && yaw > -135) { - // -45 ~ 45 if (yaw > -45) { for (int i = -extend; i <= extend; i++) { Location tempLoc = location.clone().add(i, 0, -1); @@ -500,7 +463,6 @@ public class RightClick implements Listener { } } } - // -135 ~ -45 else { for (int i = -extend; i <= extend; i++) { Location tempLoc = location.clone().add(-1, 0, i); @@ -518,7 +480,6 @@ public class RightClick implements Listener { } } else { - // 45 ~ 135 if (yaw > 45 && yaw < 135) { for (int i = -extend; i <= extend; i++) { Location tempLoc = location.clone().add(1, 0, i); @@ -534,7 +495,6 @@ public class RightClick implements Listener { } } } - // -180 ~ -135 135~180 else { for (int i = -extend; i <= extend; i++) { Location tempLoc = location.clone().add(i, 0, 1); diff --git a/src/main/java/net/momirealms/customcrops/utils/CropInstance.java b/src/main/java/net/momirealms/customcrops/objects/Crop.java similarity index 96% rename from src/main/java/net/momirealms/customcrops/utils/CropInstance.java rename to src/main/java/net/momirealms/customcrops/objects/Crop.java index f4d219d..5ed2192 100644 --- a/src/main/java/net/momirealms/customcrops/utils/CropInstance.java +++ b/src/main/java/net/momirealms/customcrops/objects/Crop.java @@ -15,13 +15,13 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.utils; +package net.momirealms.customcrops.objects; import net.momirealms.customcrops.requirements.Requirement; import java.util.List; -public class CropInstance { +public class Crop { private double giantChance; private String giant; @@ -38,7 +38,7 @@ public class CropInstance { private List commands; private double growChance; - public CropInstance(int min, int max){ + public Crop(int min, int max){ this.min = min; this.max = max; } diff --git a/src/main/java/net/momirealms/customcrops/utils/SimpleLocation.java b/src/main/java/net/momirealms/customcrops/objects/SimpleLocation.java similarity index 98% rename from src/main/java/net/momirealms/customcrops/utils/SimpleLocation.java rename to src/main/java/net/momirealms/customcrops/objects/SimpleLocation.java index d792323..8149918 100644 --- a/src/main/java/net/momirealms/customcrops/utils/SimpleLocation.java +++ b/src/main/java/net/momirealms/customcrops/objects/SimpleLocation.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.utils; +package net.momirealms.customcrops.objects; import org.bukkit.Location; diff --git a/src/main/java/net/momirealms/customcrops/utils/Sprinkler.java b/src/main/java/net/momirealms/customcrops/objects/Sprinkler.java similarity index 97% rename from src/main/java/net/momirealms/customcrops/utils/Sprinkler.java rename to src/main/java/net/momirealms/customcrops/objects/Sprinkler.java index c36e1be..7d851f0 100644 --- a/src/main/java/net/momirealms/customcrops/utils/Sprinkler.java +++ b/src/main/java/net/momirealms/customcrops/objects/Sprinkler.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.utils; +package net.momirealms.customcrops.objects; public class Sprinkler { diff --git a/src/main/java/net/momirealms/customcrops/utils/WateringCan.java b/src/main/java/net/momirealms/customcrops/objects/WateringCan.java similarity index 95% rename from src/main/java/net/momirealms/customcrops/utils/WateringCan.java rename to src/main/java/net/momirealms/customcrops/objects/WateringCan.java index 4300b8b..b9ccacc 100644 --- a/src/main/java/net/momirealms/customcrops/utils/WateringCan.java +++ b/src/main/java/net/momirealms/customcrops/objects/WateringCan.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.utils; +package net.momirealms.customcrops.objects; public record WateringCan(int max, int width, int length) { diff --git a/src/main/java/net/momirealms/customcrops/requirements/Biome.java b/src/main/java/net/momirealms/customcrops/requirements/Biome.java index 8638251..eaac8f1 100644 --- a/src/main/java/net/momirealms/customcrops/requirements/Biome.java +++ b/src/main/java/net/momirealms/customcrops/requirements/Biome.java @@ -31,11 +31,9 @@ public record Biome(List biomes) implements Requirement { @Override public boolean canPlant(PlantingCondition plantingCondition) { String currentBiome = plantingCondition.getLocation().getBlock().getBiome().getKey().toString(); - for (String biome : biomes) { - if (currentBiome.equalsIgnoreCase(biome)) { + for (String biome : biomes) + if (currentBiome.equalsIgnoreCase(biome)) return true; - } - } AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badBiome); return false; } diff --git a/src/main/java/net/momirealms/customcrops/requirements/Permission.java b/src/main/java/net/momirealms/customcrops/requirements/Permission.java index cba114c..4c38988 100644 --- a/src/main/java/net/momirealms/customcrops/requirements/Permission.java +++ b/src/main/java/net/momirealms/customcrops/requirements/Permission.java @@ -28,9 +28,7 @@ public record Permission(String permission) implements Requirement { @Override public boolean canPlant(PlantingCondition plantingCondition) { - if (plantingCondition.getPlayer().hasPermission(permission)){ - return true; - } + if (plantingCondition.getPlayer().hasPermission(permission)) return true; AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badPerm); return false; } diff --git a/src/main/java/net/momirealms/customcrops/requirements/World.java b/src/main/java/net/momirealms/customcrops/requirements/World.java index fde2558..4b47411 100644 --- a/src/main/java/net/momirealms/customcrops/requirements/World.java +++ b/src/main/java/net/momirealms/customcrops/requirements/World.java @@ -31,9 +31,7 @@ public record World(List worlds) implements Requirement { @Override public boolean canPlant(PlantingCondition plantingCondition) { org.bukkit.World world = plantingCondition.getLocation().getWorld(); - if (worlds.contains(world.getName())){ - return true; - } + if (worlds.contains(world.getName())) return true; AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badWorld); return false; } diff --git a/src/main/java/net/momirealms/customcrops/requirements/YPos.java b/src/main/java/net/momirealms/customcrops/requirements/YPos.java index f034870..a317f3b 100644 --- a/src/main/java/net/momirealms/customcrops/requirements/YPos.java +++ b/src/main/java/net/momirealms/customcrops/requirements/YPos.java @@ -34,9 +34,7 @@ public record YPos(List yPos) implements Requirement { int y = (int) plantingCondition.getLocation().getY(); for (String range : yPos) { String[] yMinMax = StringUtils.split(range, "~"); - if (y > Integer.parseInt(yMinMax[0]) && y < Integer.parseInt(yMinMax[1])) { - return true; - } + if (y > Integer.parseInt(yMinMax[0]) && y < Integer.parseInt(yMinMax[1])) return true; } AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badY); return false; diff --git a/src/main/java/net/momirealms/customcrops/timer/CropTimer.java b/src/main/java/net/momirealms/customcrops/timer/CropTimer.java index 857ecd5..8e6b524 100644 --- a/src/main/java/net/momirealms/customcrops/timer/CropTimer.java +++ b/src/main/java/net/momirealms/customcrops/timer/CropTimer.java @@ -26,14 +26,11 @@ public class CropTimer { private final int taskID; - public CropTimer(CustomCrops plugin) { - TimeCheck tc = new TimeCheck(plugin); + public CropTimer() { + TimeCheck tc = new TimeCheck(); BukkitTask task; - if (ConfigReader.Config.asyncCheck){ - task = tc.runTaskTimerAsynchronously(CustomCrops.plugin, 1,1); - }else { - task = tc.runTaskTimer(CustomCrops.plugin, 1,1); - } + if (ConfigReader.Config.asyncCheck) task = tc.runTaskTimerAsynchronously(CustomCrops.plugin, 1,1); + else task = tc.runTaskTimer(CustomCrops.plugin, 1,1); this.taskID = task.getTaskId(); } diff --git a/src/main/java/net/momirealms/customcrops/timer/TimeCheck.java b/src/main/java/net/momirealms/customcrops/timer/TimeCheck.java index a62ab33..0bb240f 100644 --- a/src/main/java/net/momirealms/customcrops/timer/TimeCheck.java +++ b/src/main/java/net/momirealms/customcrops/timer/TimeCheck.java @@ -24,44 +24,37 @@ import org.bukkit.scheduler.BukkitRunnable; public class TimeCheck extends BukkitRunnable { - private final CustomCrops plugin; - public TimeCheck(CustomCrops plugin){ - this.plugin = plugin; - } - @Override public void run() { ConfigReader.Config.worlds.forEach(world ->{ long time = world.getTime(); ConfigReader.Config.cropGrowTimeList.forEach(cropGrowTime -> { - if(time == 0){ - if(ConfigReader.Season.enable && ConfigReader.Season.seasonChange){ - plugin.getSeasonManager().getSeason(world); - } - } + if(time == 0) + if(ConfigReader.Season.enable && ConfigReader.Season.seasonChange) + CustomCrops.plugin.getSeasonManager().getSeason(world); if(time == cropGrowTime){ if (ConfigReader.Config.allWorld){ Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> { - plugin.getCropManager().cropGrowAll(); + CustomCrops.plugin.getCropManager().cropGrowAll(); }); Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.plugin, ()->{ - plugin.getSprinklerManager().sprinklerWorkAll(); + CustomCrops.plugin.getSprinklerManager().sprinklerWorkAll(); }, ConfigReader.Config.timeToGrow); }else { Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> { switch (ConfigReader.Config.growMode){ - case 1 -> plugin.getCropManager().growModeOne(world.getName()); - case 2 -> plugin.getCropManager().growModeTwo(world.getName()); - case 3 -> plugin.getCropManager().growModeThree(world.getName()); - case 4 -> plugin.getCropManager().growModeFour(world.getName()); + case 1 -> CustomCrops.plugin.getCropManager().growModeOne(world.getName()); + case 2 -> CustomCrops.plugin.getCropManager().growModeTwo(world.getName()); + case 3 -> CustomCrops.plugin.getCropManager().growModeThree(world.getName()); + case 4 -> CustomCrops.plugin.getCropManager().growModeFour(world.getName()); } }); Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.plugin, ()->{ switch (ConfigReader.Config.growMode){ - case 1 -> plugin.getSprinklerManager().workModeOne(world.getName()); - case 2 -> plugin.getSprinklerManager().workModeTwo(world.getName()); - case 3 -> plugin.getSprinklerManager().workModeThree(world.getName()); - case 4 -> plugin.getSprinklerManager().workModeFour(world.getName()); + case 1 -> CustomCrops.plugin.getSprinklerManager().workModeOne(world.getName()); + case 2 -> CustomCrops.plugin.getSprinklerManager().workModeTwo(world.getName()); + case 3 -> CustomCrops.plugin.getSprinklerManager().workModeThree(world.getName()); + case 4 -> CustomCrops.plugin.getSprinklerManager().workModeFour(world.getName()); } }, ConfigReader.Config.timeToGrow); } diff --git a/src/main/java/net/momirealms/customcrops/utils/UpdateConfig.java b/src/main/java/net/momirealms/customcrops/utils/ConfigUtil.java similarity index 65% rename from src/main/java/net/momirealms/customcrops/utils/UpdateConfig.java rename to src/main/java/net/momirealms/customcrops/utils/ConfigUtil.java index 9366754..e8bb443 100644 --- a/src/main/java/net/momirealms/customcrops/utils/UpdateConfig.java +++ b/src/main/java/net/momirealms/customcrops/utils/ConfigUtil.java @@ -12,11 +12,11 @@ import net.momirealms.customcrops.helper.Log; import java.io.File; import java.io.IOException; -public class UpdateConfig { +public class ConfigUtil { public static void update(){ try { - YamlDocument.create(new File(CustomCrops.instance.getDataFolder(), "config.yml"), CustomCrops.instance.getResource("config.yml"), GeneralSettings.DEFAULT, LoaderSettings.builder().setAutoUpdate(true).build(), DumperSettings.DEFAULT, UpdaterSettings.builder().setVersioning(new BasicVersioning("config-version")).build()); + YamlDocument.create(new File(CustomCrops.plugin.getDataFolder(), "config.yml"), CustomCrops.plugin.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/customcrops/utils/BackUp.java b/src/main/java/net/momirealms/customcrops/utils/FileUtil.java similarity index 97% rename from src/main/java/net/momirealms/customcrops/utils/BackUp.java rename to src/main/java/net/momirealms/customcrops/utils/FileUtil.java index d268a3a..b9d3b6f 100644 --- a/src/main/java/net/momirealms/customcrops/utils/BackUp.java +++ b/src/main/java/net/momirealms/customcrops/utils/FileUtil.java @@ -28,7 +28,7 @@ import java.util.Arrays; import java.util.Date; import java.util.List; -public class BackUp { +public class FileUtil { /** * 备份全部文件 @@ -44,7 +44,7 @@ public class BackUp { File data = new File(CustomCrops.plugin.getDataFolder(), "data"+ File.separatorChar + fileName + ".yml"); File backUp = new File(CustomCrops.plugin.getDataFolder(), "backups"+ File.separatorChar + format.format(date) + File.separatorChar + fileName + ".yml"); try { - BackUp.backUp(data, backUp); + FileUtil.backUp(data, backUp); } catch (IOException e) { e.printStackTrace(); CustomCrops.plugin.getLogger().warning(fileName + ".yml备份出错!"); diff --git a/src/main/java/net/momirealms/customcrops/utils/HoloUtil.java b/src/main/java/net/momirealms/customcrops/utils/HoloUtil.java index 45927aa..9b7c91d 100644 --- a/src/main/java/net/momirealms/customcrops/utils/HoloUtil.java +++ b/src/main/java/net/momirealms/customcrops/utils/HoloUtil.java @@ -38,7 +38,7 @@ import java.util.*; public class HoloUtil { - public static HashSet cache = new HashSet<>(); + public static HashMap cache = new HashMap<>(); /** * 对指定玩家展示在指定位置的盔甲架 * @param text 文本 @@ -48,6 +48,10 @@ public class HoloUtil { */ public static void showHolo(String text, Player player, Location location, int duration){ + if (cache.get(location) != null){ + removeHolo(player, cache.get(location)); + } + PacketContainer packet1 = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY); int id = new Random().nextInt(1000000000); @@ -73,7 +77,7 @@ public class HoloUtil { wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, serializer2), mask2); packet2.getModifier().write(0,id); packet2.getWatchableCollectionModifier().write(0, wrappedDataWatcher.getWatchableObjects()); - cache.add(location); + cache.put(location, id); try { ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet1); ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet2); diff --git a/src/main/java/net/momirealms/customcrops/utils/IAFurniture.java b/src/main/java/net/momirealms/customcrops/utils/IAFurnitureUtil.java similarity index 67% rename from src/main/java/net/momirealms/customcrops/utils/IAFurniture.java rename to src/main/java/net/momirealms/customcrops/utils/IAFurnitureUtil.java index f8e32f5..5d9d1e2 100644 --- a/src/main/java/net/momirealms/customcrops/utils/IAFurniture.java +++ b/src/main/java/net/momirealms/customcrops/utils/IAFurnitureUtil.java @@ -20,11 +20,9 @@ package net.momirealms.customcrops.utils; import dev.lone.itemsadder.api.CustomFurniture; import net.momirealms.customcrops.ConfigReader; import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; -public class IAFurniture { +public class IAFurnitureUtil { /** * 在指定位置放置家具 @@ -39,19 +37,19 @@ public class IAFurniture { * 判断指定位置的盔甲架是不是洒水器 * 仅限加载中的区块 * @param location 位置 - * @param world 世界 * @return 是/否 */ - public static boolean getFromLocation(Location location, World world){ - for(Entity entity : world.getNearbyEntities(location,0,0,0)){ - if(entity instanceof ArmorStand armorStand){ - if(CustomFurniture.byAlreadySpawned(armorStand) != null){ - if(ConfigReader.SPRINKLERS.get(CustomFurniture.byAlreadySpawned(armorStand).getId()) != null){ - return true; - } - } - } + public static String getFromLocation(Location location){ + for(Entity entity : location.getWorld().getNearbyEntities(location,0,0,0)){ + CustomFurniture furniture = CustomFurniture.byAlreadySpawned(entity); + if(furniture != null) return furniture.getNamespacedID(); } - return false; + return null; + } + + public static boolean isSprinkler(Location location){ + String furniture = getFromLocation(location); + if (furniture != null) return ConfigReader.SPRINKLERS.get(furniture) != null; + else return false; } } \ No newline at end of file diff --git a/src/main/resources/basic.yml b/src/main/resources/basic.yml index f0ae695..d500c6a 100644 --- a/src/main/resources/basic.yml +++ b/src/main/resources/basic.yml @@ -1,4 +1,3 @@ -#=============================================================# #ItemsAdder items namespacedID basic: pot: customcrops:pot @@ -6,7 +5,9 @@ basic: greenhouse-glass: customcrops:greenhouse_glass dead-crop: customcrops:crop_stage_death soil-detector: customcrops:soil_detector -#=============================================================# + + + water-can: watering_can_1: item: customcrops:watering_can_1 @@ -30,7 +31,9 @@ water-can: max: 6 width: 3 length: 5 -#=============================================================# + + + lore: #Should lore be changed when using watering-can watering-can: @@ -46,7 +49,9 @@ lore: full: '뀁뀃' empty: '뀁뀄' right: '뀁뀅' -#=============================================================# + + + sprinkler: sprinkler_1: range: 1 @@ -58,5 +63,4 @@ sprinkler: range: 2 max-water: 7 3Ditem: customcrops:sprinkler_2 - 2Ditem: customcrops:sprinkler_2_item -#=============================================================# \ No newline at end of file + 2Ditem: customcrops:sprinkler_2_item \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index f381f6d..981ee9b 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,10 +1,12 @@ #Don't change -config-version: 2 +config-version: 3 + + config: - #=============================================================# #english spanish chinese lang: english - #=============================================================# + + integration: #integration to prevent other players' grief Residence: false @@ -21,7 +23,11 @@ config: mcMMO: false MMOCore: false EcoSkills: false - #=============================================================# + #integration to sync seasons + RealisticSeasons: false + + + #Mode 1: # Crops in loaded chunks will grow #Mode 2: @@ -55,13 +61,17 @@ config: #This is useful for per player per world server. #In this mode, whitelist world can only have one as the standard of time & season judgment. all-world-grow: false - #=============================================================# + + + quality: #If disabled, you need to configurate the loot in ItemsAdder config enable: true #Default ratio default-ratio: 17/2/1 - #=============================================================# + + + #Water Amount to refill when using water bucket sprinkler-refill: 2 #Water Amount to refill with a sigle click to water block @@ -70,13 +80,17 @@ config: water-can-add-water-to-sprinkler: true #Should particles be displayed when using watering can? water-particles: true - #=============================================================# + + + #Will bone meal accelerate the growth of crop bone-meal: enable: true chance: 0.5 success-particle: VILLAGER_HAPPY - #=============================================================# + + + #Should we limit the max amount of crops and sprinkler in one chunk #Recommended to enable because ItemsAdder might throw StackOverFlow #when there are too many custom blocks in one chunk @@ -84,7 +98,9 @@ config: enable: true crop: 64 sprinkler: 8 - #=============================================================# + + + #can player harvest crops with right click? #if set "false" crops can't be harvested repeatedly right-click-harvest: true @@ -94,5 +110,4 @@ config: #Should player be prevented from planting if wrong season prevent-plant-if-wrong-season: true #Should notify player of the wrong season? - should-notify-if-wrong-season: true - #=============================================================# \ No newline at end of file + should-notify-if-wrong-season: true \ No newline at end of file diff --git a/src/main/resources/fertilizer.yml b/src/main/resources/fertilizer.yml index d482620..c940fd2 100644 --- a/src/main/resources/fertilizer.yml +++ b/src/main/resources/fertilizer.yml @@ -27,7 +27,9 @@ speed: times: 14 item: customcrops:speed_3 before-plant: true -#=============================================================# + + + #Pot have a small chance to retain its water after crops grow retaining: retaining_1: @@ -50,7 +52,9 @@ retaining: times: 28 item: customcrops:retaining_3 before-plant: false -#=============================================================# + + + #When haveresting, players have a higher chance to get high quality crops. quality: quality_1: @@ -72,5 +76,4 @@ quality: times: 28 chance: 2/2/1 item: customcrops:quality_3 - before-plant: true -#=============================================================# \ No newline at end of file + before-plant: true \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index ffc5cab..5ba13bd 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -21,6 +21,7 @@ softdepend: - MMOCore - EcoSkills - CrashClaim + - RealisticSeasons commands: customcrops: usage: /customcrops diff --git a/src/main/resources/season.yml b/src/main/resources/season.yml index 41c1d90..a822089 100644 --- a/src/main/resources/season.yml +++ b/src/main/resources/season.yml @@ -4,8 +4,11 @@ season: enable: true auto-season-change: + #If you enabled RealisticSeasons Integration + #keep this true enable: true #duration of each season + #would not take effect if enabled RealisticSeasons Integration duration: 28 greenhouse: