9
0
mirror of https://github.com/Xiao-MoMi/Custom-Crops.git synced 2025-12-22 08:29:35 +00:00
This commit is contained in:
Xiao-MoMi
2022-08-18 00:26:33 +08:00
parent c0dd8830a4
commit 47dc7a0f7d
43 changed files with 527 additions and 694 deletions

View File

@@ -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! Watering-can also has its max storage and effective range. 1x1 1x3 3x3 and even 9x99 is supported!
### OverWeight ### 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 ### Quality
Crops have three qualities, if you don't want this feature just disable it in config. Crops have three qualities, if you don't want this feature just disable it in config.

View File

@@ -5,7 +5,7 @@ plugins {
group = 'net.momirealms' group = 'net.momirealms'
version = '1.5.26.3' version = '1.5.26.4'
repositories { repositories {
mavenCentral() mavenCentral()

View File

@@ -18,12 +18,17 @@
package net.momirealms.customcrops; package net.momirealms.customcrops;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.momirealms.customcrops.fertilizer.Fertilizer; import net.momirealms.customcrops.fertilizer.Fertilizer;
import net.momirealms.customcrops.fertilizer.QualityCrop; import net.momirealms.customcrops.fertilizer.QualityCrop;
import net.momirealms.customcrops.fertilizer.RetainingSoil; import net.momirealms.customcrops.fertilizer.RetainingSoil;
import net.momirealms.customcrops.fertilizer.SpeedGrow; import net.momirealms.customcrops.fertilizer.SpeedGrow;
import net.momirealms.customcrops.helper.Log;
import net.momirealms.customcrops.integrations.protection.*; import net.momirealms.customcrops.integrations.protection.*;
import net.momirealms.customcrops.integrations.skill.*; 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.Biome;
import net.momirealms.customcrops.requirements.Permission; import net.momirealms.customcrops.requirements.Permission;
import net.momirealms.customcrops.requirements.Requirement; import net.momirealms.customcrops.requirements.Requirement;
@@ -41,20 +46,18 @@ import java.util.*;
public class ConfigReader { public class ConfigReader {
public static HashMap<String, CropInstance> CROPS = new HashMap<>(); public static HashMap<String, Crop> CROPS = new HashMap<>();
public static HashMap<String, Fertilizer> FERTILIZERS = new HashMap<>(); public static HashMap<String, Fertilizer> FERTILIZERS = new HashMap<>();
public static HashMap<String, WateringCan> CANS = new HashMap<>(); public static HashMap<String, WateringCan> CANS = new HashMap<>();
public static HashMap<String, Sprinkler> SPRINKLERS = new HashMap<>(); public static HashMap<String, Sprinkler> SPRINKLERS = new HashMap<>();
public static YamlConfiguration getConfig(String configName) { public static YamlConfiguration getConfig(String configName) {
File file = new File(CustomCrops.plugin.getDataFolder(), configName); File file = new File(CustomCrops.plugin.getDataFolder(), configName);
if (!file.exists()) { if (!file.exists()) CustomCrops.plugin.saveResource(configName, false);
CustomCrops.plugin.saveResource(configName, false);
}
return YamlConfiguration.loadConfiguration(file); return YamlConfiguration.loadConfiguration(file);
} }
public static void ReloadConfig(){ public static void reloadConfig(){
Sounds.loadSound(); Sounds.loadSound();
Config.loadConfig(); Config.loadConfig();
Season.loadSeason(); Season.loadSeason();
@@ -93,16 +96,16 @@ public class ConfigReader {
public static boolean nwSeason; public static boolean nwSeason;
public static boolean needEmptyHand; public static boolean needEmptyHand;
public static boolean boneMeal; public static boolean boneMeal;
public static boolean realisticSeason;
public static Particle boneMealSuccess; public static Particle boneMealSuccess;
public static double boneMealChance; public static double boneMealChance;
public static double quality_1; public static double quality_1;
public static double quality_2; public static double quality_2;
public static SkillXP skillXP; public static SkillXP skillXP;
public static int version; public static String version;
public static void loadConfig(){ public static void loadConfig(){
//存读基本配置文件
CustomCrops.plugin.saveDefaultConfig(); CustomCrops.plugin.saveDefaultConfig();
CustomCrops.plugin.reloadConfig(); CustomCrops.plugin.reloadConfig();
FileConfiguration config = CustomCrops.plugin.getConfig(); 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()); boneMealSuccess = Particle.valueOf(config.getString("config.bone-meal.success-particle", "VILLAGER_HAPPY").toUpperCase());
} }
//数量与高度限制
enableLimit = config.getBoolean("config.limit.enable",true); enableLimit = config.getBoolean("config.limit.enable",true);
if (enableLimit){ if (enableLimit){
cropLimit = config.getInt("config.limit.crop",64); cropLimit = config.getInt("config.limit.crop",64);
sprinklerLimit = config.getInt("config.limit.sprinkler",16); sprinklerLimit = config.getInt("config.limit.sprinkler",16);
} }
if (Bukkit.getServer().getClass().getPackage().getName().contains("16") || Bukkit.getServer().getClass().getPackage().getName().contains("17")){
yMin = 0; String serverVersion = Bukkit.getServer().getClass().getPackage().getName();
yMax = 256; if (serverVersion.contains("16") || serverVersion.contains("17")){
} yMin = 0; yMax = 256;
if (Bukkit.getServer().getClass().getPackage().getName().contains("18") || Bukkit.getServer().getClass().getPackage().getName().contains("19")){ }else {
yMin = -64; yMin = -64; yMax = 320;
yMax = 320;
} }
//农作物品质
quality = config.getBoolean("config.quality.enable",true); quality = config.getBoolean("config.quality.enable",true);
if (quality){ if (quality){
String[] split = StringUtils.split(config.getString("config.quality.default-ratio","17/2/1"), "/"); 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); sprinklerRefill = config.getInt("config.sprinkler-refill",2);
waterCanRefill = config.getInt("config.water-can-refill",1); 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); canAddWater = config.getBoolean("config.water-can-add-water-to-sprinkler",true);
if (allWorld){ if (allWorld){
if (config.getStringList("config.whitelist-worlds").size() > 1){ if (config.getStringList("config.whitelist-worlds").size() > 1) AdventureManager.consoleMessage("<red>[CustomCrops] Only one whitelist world is allowed when \"all-world-grow\" enabled!");
referenceWorld = config.getStringList("config.whitelist-worlds").get(0); referenceWorld = config.getStringList("config.whitelist-worlds").get(0);
AdventureManager.consoleMessage("<red>[CustomCrops] Only one whitelist world is allowed when \"all-world-grow\" enabled!");
}else {
referenceWorld = config.getStringList("config.whitelist-worlds").get(0);
}
} }
//农作物生长的白名单世界
worlds = new ArrayList<>(); worlds = new ArrayList<>();
worldNames = config.getStringList("config.whitelist-worlds"); worldNames = config.getStringList("config.whitelist-worlds");
worldNames.forEach(worldName -> { worldNames.forEach(worldName -> {
World world = Bukkit.getWorld(worldName); World world = Bukkit.getWorld(worldName);
if (world == null){ if (world == null) AdventureManager.consoleMessage("<red>[CustomCrops] World " + worldName + " doesn't exist");
AdventureManager.consoleMessage("<red>[CustomCrops] World " + worldName + " doesn't exist"); else worlds.add(world);
}else {
worlds.add(world);
}
}); });
//处理插件兼容性
integration = new ArrayList<>(); integration = new ArrayList<>();
if(config.getBoolean("config.integration.Residence",false)){ if (config.getBoolean("config.integration.Residence",false)){
if(Bukkit.getPluginManager().getPlugin("Residence") == null){ if (Bukkit.getPluginManager().getPlugin("Residence") == null) Log.warn("Failed to initialize Residence!");
CustomCrops.plugin.getLogger().warning("Failed to initialize Residence!"); else {integration.add(new Residence());hookMessage("Residence");}
}else {
integration.add(new Residence());
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>Residence <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.Kingdoms",false)){ if (config.getBoolean("config.integration.Kingdoms",false)){
if(Bukkit.getPluginManager().getPlugin("Kingdoms") == null){ if (Bukkit.getPluginManager().getPlugin("Kingdoms") == null) Log.warn("Failed to initialize Kingdoms!");
CustomCrops.plugin.getLogger().warning("Failed to initialize Kingdoms!"); else {integration.add(new KingdomsX());hookMessage("Kingdoms");}
}else {
integration.add(new KingdomsX());
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>KingdomsX <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.WorldGuard",false)){ if (config.getBoolean("config.integration.WorldGuard",false)){
if(Bukkit.getPluginManager().getPlugin("WorldGuard") == null){ if (Bukkit.getPluginManager().getPlugin("WorldGuard") == null) Log.warn("Failed to initialize WorldGuard!");
CustomCrops.plugin.getLogger().warning("Failed to initialize WorldGuard!"); else {integration.add(new WorldGuard());hookMessage("WorldGuard");}
}else {
integration.add(new WorldGuard());
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>WorldGuard <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.GriefDefender",false)){ if (config.getBoolean("config.integration.GriefDefender",false)){
if(Bukkit.getPluginManager().getPlugin("GriefDefender") == null){ if(Bukkit.getPluginManager().getPlugin("GriefDefender") == null) Log.warn("Failed to initialize GriefDefender!");
CustomCrops.plugin.getLogger().warning("Failed to initialize GriefDefender!"); else {integration.add(new GriefDefender());hookMessage("GriefDefender");}
}else {
integration.add(new GriefDefender());
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>GriefDefender <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.PlotSquared",false)){ if (config.getBoolean("config.integration.PlotSquared",false)){
if(Bukkit.getPluginManager().getPlugin("PlotSquared") == null){ if(Bukkit.getPluginManager().getPlugin("PlotSquared") == null) Log.warn("Failed to initialize PlotSquared!");
CustomCrops.plugin.getLogger().warning("Failed to initialize PlotSquared!"); else {integration.add(new PlotSquared());hookMessage("PlotSquared");}
}else {
integration.add(new PlotSquared());
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>PlotSquared <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.Towny",false)){ if (config.getBoolean("config.integration.Towny",false)){
if(Bukkit.getPluginManager().getPlugin("Towny") == null){ if (Bukkit.getPluginManager().getPlugin("Towny") == null) Log.warn("Failed to initialize Towny!");
CustomCrops.plugin.getLogger().warning("Failed to initialize Towny!"); else {integration.add(new Towny());hookMessage("Towny");}
}else {
integration.add(new Towny());
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>Towny <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.Lands",false)){ if (config.getBoolean("config.integration.Lands",false)){
if(Bukkit.getPluginManager().getPlugin("Lands") == null){ if (Bukkit.getPluginManager().getPlugin("Lands") == null) Log.warn("Failed to initialize Lands!");
CustomCrops.plugin.getLogger().warning("Failed to initialize Lands!"); else {integration.add(new Lands());hookMessage("Lands");}
}else {
integration.add(new Lands());
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>Lands <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.GriefPrevention",false)){ if (config.getBoolean("config.integration.GriefPrevention",false)){
if(Bukkit.getPluginManager().getPlugin("GriefPrevention") == null){ if (Bukkit.getPluginManager().getPlugin("GriefPrevention") == null) Log.warn("Failed to initialize GriefPrevention!");
CustomCrops.plugin.getLogger().warning("Failed to initialize GriefPrevention!"); else {integration.add(new GriefPrevention());hookMessage("GriefPrevention");}
}else {
integration.add(new GriefPrevention());
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>GriefPrevention <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.CrashClaim",false)){ if (config.getBoolean("config.integration.CrashClaim",false)){
if(Bukkit.getPluginManager().getPlugin("CrashClaim") == null){ if (Bukkit.getPluginManager().getPlugin("CrashClaim") == null) Log.warn("Failed to initialize CrashClaim!");
CustomCrops.plugin.getLogger().warning("Failed to initialize CrashClaim!"); else {integration.add(new CrashClaim());hookMessage("CrashClaim");}
}else { }
integration.add(new CrashClaim());
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>CrashClaim <color:#FFEBCD>Hooked!"); 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; skillXP = null;
if (config.getBoolean("config.integration.mcMMO",false)){
if(config.getBoolean("config.integration.mcMMO",false)){ if (Bukkit.getPluginManager().getPlugin("mcMMO") == null) Log.warn("Failed to initialize mcMMO!");
if(Bukkit.getPluginManager().getPlugin("mcMMO") == null){ else {skillXP = new mcMMO();hookMessage("mcMMO");}
CustomCrops.plugin.getLogger().warning("Failed to initialize mcMMO!");
}else {
skillXP = new mcMMO();
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>mcMMO <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.AureliumSkills",false)){ if (config.getBoolean("config.integration.AureliumSkills",false)){
if(Bukkit.getPluginManager().getPlugin("AureliumSkills") == null){ if (Bukkit.getPluginManager().getPlugin("AureliumSkills") == null) Log.warn("Failed to initialize AureliumSkills!");
CustomCrops.plugin.getLogger().warning("Failed to initialize AureliumSkills!"); else {skillXP = new Aurelium();hookMessage("AureliumSkills");}
}else {
skillXP = new Aurelium();
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>AureliumSkills <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.MMOCore",false)){ if(config.getBoolean("config.integration.MMOCore",false)){
if(Bukkit.getPluginManager().getPlugin("MMOCore") == null){ if(Bukkit.getPluginManager().getPlugin("MMOCore") == null) Log.warn("Failed to initialize MMOCore!");
CustomCrops.plugin.getLogger().warning("Failed to initialize MMOCore!"); else {skillXP = new MMOCore();hookMessage("MMOCore");}
}else {
skillXP = new MMOCore();
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>MMOCore <color:#FFEBCD>Hooked!");
}
} }
if(config.getBoolean("config.integration.EcoSkills",false)){ if(config.getBoolean("config.integration.EcoSkills",false)){
if(Bukkit.getPluginManager().getPlugin("EcoSkills") == null){ if(Bukkit.getPluginManager().getPlugin("EcoSkills") == null) Log.warn("Failed to initialize EcoSkills!");
CustomCrops.plugin.getLogger().warning("Failed to initialize EcoSkills!"); else {skillXP = new EcoSkill();hookMessage("EcoSkills");}
}else {
skillXP = new EcoSkill();
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>EcoSkills <color:#FFEBCD>Hooked!");
}
} }
} }
} }
@@ -309,12 +254,14 @@ public class ConfigReader {
public static List<String> waterLore; public static List<String> waterLore;
public static void loadBasic(){ public static void loadBasic(){
YamlConfiguration config = getConfig("basic.yml"); YamlConfiguration config = getConfig("basic.yml");
pot = config.getString("basic.pot","customcrops:pot"); pot = config.getString("basic.pot","customcrops:pot");
watered_pot = config.getString("basic.watered-pot","customcrops:watered_pot"); watered_pot = config.getString("basic.watered-pot","customcrops:watered_pot");
glass = config.getString("basic.greenhouse-glass","customcrops:greenhouse_glass"); glass = config.getString("basic.greenhouse-glass","customcrops:greenhouse_glass");
dead = config.getString("basic.dead-crop","customcrops:crop_stage_death"); 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); hasWaterLore = config.getBoolean("lore.watering-can.enable",false);
if (hasWaterLore){ if (hasWaterLore){
@@ -328,17 +275,14 @@ public class ConfigReader {
CANS.clear(); CANS.clear();
if (config.contains("water-can")){ if (config.contains("water-can")){
config.getConfigurationSection("water-can").getKeys(false).forEach(key -> { 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");
int width = config.getInt("water-can." + key + ".width"); if (width % 2 == 0){
if (width % 2 == 0){ AdventureManager.consoleMessage("<red>[CustomCrops] Watering Can " + key + "'s width should be odd!</red>");
AdventureManager.consoleMessage("<red>[CustomCrops] Watering Can " + key + "'s width should be odd!</red>"); return;
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("<red>[CustomCrops] Watering Can " + key + "'s key should be the same</red>");
} }
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("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><white>" + CANS.size() + " <color:#FFEBCD>cans loaded!"); AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><white>" + CANS.size() + " <color:#FFEBCD>cans loaded!");
@@ -346,16 +290,13 @@ public class ConfigReader {
SPRINKLERS.clear(); SPRINKLERS.clear();
if (config.contains("sprinkler")){ if (config.contains("sprinkler")){
config.getConfigurationSection("sprinkler").getKeys(false).forEach(key -> { 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"));
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(config.getString("sprinkler." + key + ".3Ditem")); sprinklerData.setNamespacedID_2(threeD);
String twoD = config.getString("sprinkler." + key + ".2Ditem"); String twoD = config.getString("sprinkler." + key + ".2Ditem");
sprinklerData.setNamespacedID_1(twoD); sprinklerData.setNamespacedID_1(twoD);
SPRINKLERS.put(key, sprinklerData); SPRINKLERS.put(threeD, sprinklerData);
SPRINKLERS.put(StringUtils.split(twoD,":")[1], sprinklerData); SPRINKLERS.put(twoD, sprinklerData);
}else {
AdventureManager.consoleMessage("<red>[CustomCrops] Sprinkler " + key + "'s key should be the same with ItemsAdder 3D sprinkler's key</red>");
}
}); });
} }
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><white>" + SPRINKLERS.size()/2 + "<color:#FFEBCD> sprinklers loaded!"); AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><white>" + SPRINKLERS.size()/2 + "<color:#FFEBCD> sprinklers loaded!");
@@ -371,25 +312,17 @@ public class ConfigReader {
public static int duration; public static int duration;
public static void loadSeason(){ public static void loadSeason(){
YamlConfiguration config = getConfig("season.yml"); YamlConfiguration config = getConfig("season.yml");
enable = config.getBoolean("season.enable",false); enable = config.getBoolean("season.enable",false);
if (enable){ if (enable){
if (Config.growMode == 4){ if (Config.growMode == 4) AdventureManager.consoleMessage("<red>[CustomCrops] Warining: It's not advised to enable season in mode 4</red>");
AdventureManager.consoleMessage("<red>[CustomCrops] Warining: It's not advised to enable season in mode 4</red>");
}
greenhouse = config.getBoolean("season.greenhouse.enable",false); greenhouse = config.getBoolean("season.greenhouse.enable",false);
if (greenhouse) { if (greenhouse) range = config.getInt("season.greenhouse.range",7);
range = config.getInt("season.greenhouse.range",7);
}
seasonChange = config.getBoolean("season.auto-season-change.enable",false); seasonChange = config.getBoolean("season.auto-season-change.enable",false);
duration = config.getInt("season.auto-season-change.duration",28); duration = config.getInt("season.auto-season-change.duration",28);
if (seasonChange) { if (seasonChange) AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><color:#FFEBCD>Season Change mode: <gold>Auto");
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><color:#FFEBCD>Season Change mode: <gold>Auto"); else AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><color:#FFEBCD>Season Change mode: <gold>Command");
}else {
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><color:#FFEBCD>Season Change mode: <gold>Command");
}
} }
} }
} }
@@ -495,30 +428,26 @@ public class ConfigReader {
YamlConfiguration config = getConfig("crops.yml"); YamlConfiguration config = getConfig("crops.yml");
Set<String> keys = config.getConfigurationSection("crops").getKeys(false); Set<String> keys = config.getConfigurationSection("crops").getKeys(false);
keys.forEach(key -> { keys.forEach(key -> {
CropInstance cropInstance; Crop cropInstance;
if (config.contains("crops." + key + ".amount")){ if (config.contains("crops." + key + ".amount")){
String[] split = StringUtils.split(config.getString("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 { }else {
AdventureManager.consoleMessage("<red>[CustomCrops] You forget to set " + key +"'s amount!</red>"); AdventureManager.consoleMessage("<red>[CustomCrops] You forget to set " + key +"'s amount!</red>");
return; 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.setGiant(config.getString("crops." + key + ".gigantic.block"));
cropInstance.setGiantChance(config.getDouble("crops." + key + ".gigantic.chance")); 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")); 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")); 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")); 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")); cropInstance.setSkillXP(config.getDouble("crops." + key + ".skill-xp"));
}
if (config.contains("crops." + key + ".requirements")){ if (config.contains("crops." + key + ".requirements")){
List<Requirement> requirements = new ArrayList<>(); List<Requirement> requirements = new ArrayList<>();
config.getConfigurationSection("crops." + key + ".requirements").getValues(false).forEach((requirement, value) -> { config.getConfigurationSection("crops." + key + ".requirements").getValues(false).forEach((requirement, value) -> {
@@ -531,23 +460,12 @@ public class ConfigReader {
}); });
cropInstance.setRequirements(requirements); 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){ if (Config.quality){
cropInstance.setQuality_1(config.getString("crops." + key + ".quality.1")); cropInstance.setQuality_1(config.getString("crops." + key + ".quality.1"));
cropInstance.setQuality_2(config.getString("crops." + key + ".quality.2")); cropInstance.setQuality_2(config.getString("crops." + key + ".quality.2"));
cropInstance.setQuality_3(config.getString("crops." + key + ".quality.3")); 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", false));
cropInstance.setDropIALoot(config.getBoolean("crops." + key + ".drop-ia-loots")); }else {cropInstance.setDropIALoot(false);}
}else {
cropInstance.setDropIALoot(false);
}
}else {
cropInstance.setDropIALoot(false);
}
CROPS.put(key, cropInstance); CROPS.put(key, cropInstance);
}); });
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><white>" + CROPS.size() + " <color:#FFEBCD>crops loaded!"); AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><white>" + CROPS.size() + " <color:#FFEBCD>crops loaded!");
@@ -558,26 +476,27 @@ public class ConfigReader {
YamlConfiguration config = getConfig("fertilizer.yml"); YamlConfiguration config = getConfig("fertilizer.yml");
if (config.contains("speed")){ if (config.contains("speed")){
config.getConfigurationSection("speed").getKeys(false).forEach(key -> { 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")); 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())); speedGrow.setParticle(Particle.valueOf(config.getString("speed." + key + ".particle").toUpperCase()));
} FERTILIZERS.put(id, speedGrow);
FERTILIZERS.put(StringUtils.split(config.getString("speed." + key + ".item"), ":")[1], speedGrow);
}); });
} }
if (config.contains("retaining")){ if (config.contains("retaining")){
config.getConfigurationSection("retaining").getKeys(false).forEach(key -> { 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")); 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())); retainingSoil.setParticle(Particle.valueOf(config.getString("retaining." + key + ".particle").toUpperCase()));
} FERTILIZERS.put(id, retainingSoil);
FERTILIZERS.put(StringUtils.split(config.getString("retaining." + key + ".item"), ":")[1], retainingSoil);
}); });
} }
if (config.contains("quality")){ if (config.contains("quality")){
config.getConfigurationSection("quality").getKeys(false).forEach(key -> { 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"), "/"); String[] split = StringUtils.split(config.getString("quality." + key + ".chance"), "/");
int[] weight = new int[3]; int[] weight = new int[3];
weight[0] = Integer.parseInt(split[0]); weight[0] = Integer.parseInt(split[0]);
@@ -585,10 +504,9 @@ public class ConfigReader {
weight[2] = Integer.parseInt(split[2]); weight[2] = Integer.parseInt(split[2]);
QualityCrop qualityCrop = new QualityCrop(key, config.getInt("quality." + key + ".times"), weight, config.getBoolean("quality." + key + ".before-plant")); QualityCrop qualityCrop = new QualityCrop(key, config.getInt("quality." + key + ".times"), weight, config.getBoolean("quality." + key + ".before-plant"));
qualityCrop.setName(config.getString("quality." + key + ".name")); 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())); qualityCrop.setParticle(Particle.valueOf(config.getString("quality." + key + ".particle").toUpperCase()));
} FERTILIZERS.put(id, qualityCrop);
FERTILIZERS.put(StringUtils.split(config.getString("quality." + key + ".item"), ":")[1], qualityCrop);
}); });
} }
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><white>" + FERTILIZERS.size() + " <color:#FFEBCD>fertilizers loaded!"); AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><white>" + FERTILIZERS.size() + " <color:#FFEBCD>fertilizers loaded!");
@@ -597,65 +515,51 @@ public class ConfigReader {
public static class Sounds{ public static class Sounds{
public static Key waterPotKey; public static Key waterPotKey;
public static net.kyori.adventure.sound.Sound.Source waterPotSource; public static Sound.Source waterPotSource;
public static Key addWaterToCanKey; public static Key addWaterToCanKey;
public static net.kyori.adventure.sound.Sound.Source addWaterToCanSource; public static Sound.Source addWaterToCanSource;
public static Key addWaterToSprinklerKey; public static Key addWaterToSprinklerKey;
public static net.kyori.adventure.sound.Sound.Source addWaterToSprinklerSource; public static Sound.Source addWaterToSprinklerSource;
public static Key placeSprinklerKey; public static Key placeSprinklerKey;
public static net.kyori.adventure.sound.Sound.Source placeSprinklerSource; public static Sound.Source placeSprinklerSource;
public static Key plantSeedKey; public static Key plantSeedKey;
public static net.kyori.adventure.sound.Sound.Source plantSeedSource; public static Sound.Source plantSeedSource;
public static Key useFertilizerKey; public static Key useFertilizerKey;
public static net.kyori.adventure.sound.Sound.Source useFertilizerSource; public static Sound.Source useFertilizerSource;
public static Key harvestKey; public static Key harvestKey;
public static net.kyori.adventure.sound.Sound.Source harvestSource; public static Sound.Source harvestSource;
public static Key boneMealKey; public static Key boneMealKey;
public static net.kyori.adventure.sound.Sound.Source boneMealSource; public static Sound.Source boneMealSource;
public static void loadSound(){ public static void loadSound(){
YamlConfiguration config = getConfig("sounds.yml"); YamlConfiguration config = getConfig("sounds.yml");
waterPotKey = Key.key(config.getString("water-pot.sound", "minecraft:block.water.ambient")); 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")); 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")); 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")); 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")); 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")); 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")); 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")); 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(){ public static void tryEnableJedis(){
YamlConfiguration configuration = ConfigReader.getConfig("redis.yml"); 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.initializeRedis(configuration);
JedisUtil.useRedis = true; }
}else {
JedisUtil.useRedis = false; private static void hookMessage(String plugin){
} AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><gold>" + plugin + " <color:#FFEBCD>Hooked!");
} }
} }

View File

@@ -21,7 +21,10 @@ import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.momirealms.customcrops.commands.Executor; import net.momirealms.customcrops.commands.Executor;
import net.momirealms.customcrops.commands.Completer; import net.momirealms.customcrops.commands.Completer;
import net.momirealms.customcrops.datamanager.*; 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.helper.LibraryLoader;
import net.momirealms.customcrops.hook.Placeholders;
import net.momirealms.customcrops.listener.*; import net.momirealms.customcrops.listener.*;
import net.momirealms.customcrops.timer.CropTimer; import net.momirealms.customcrops.timer.CropTimer;
import net.momirealms.customcrops.utils.*; import net.momirealms.customcrops.utils.*;
@@ -60,10 +63,11 @@ public final class CustomCrops extends JavaPlugin {
@Override @Override
public void onEnable() { public void onEnable() {
plugin = this;
adventure = BukkitAudiences.create(plugin); adventure = BukkitAudiences.create(plugin);
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><color:#FFEBCD>Running on " + Bukkit.getVersion()); AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><color:#FFEBCD>Running on " + Bukkit.getVersion());
ConfigReader.ReloadConfig(); ConfigReader.reloadConfig();
if(Bukkit.getPluginManager().getPlugin("PlaceHolderAPI") != null){ if(Bukkit.getPluginManager().getPlugin("PlaceHolderAPI") != null){
placeholders = new Placeholders(); placeholders = new Placeholders();
placeholders.register(); 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")).setExecutor(new Executor(this));
Objects.requireNonNull(Bukkit.getPluginCommand("customcrops")).setTabCompleter(new Completer()); Objects.requireNonNull(Bukkit.getPluginCommand("customcrops")).setTabCompleter(new Completer());
//公用事件
Bukkit.getPluginManager().registerEvents(new ItemSpawn(), this); Bukkit.getPluginManager().registerEvents(new ItemSpawn(), this);
Bukkit.getPluginManager().registerEvents(new JoinAndQuit(), this);
Bukkit.getPluginManager().registerEvents(new RightClick(), this); Bukkit.getPluginManager().registerEvents(new RightClick(), this);
Bukkit.getPluginManager().registerEvents(new BreakBlock(), this); Bukkit.getPluginManager().registerEvents(new BreakBlock(), this);
Bukkit.getPluginManager().registerEvents(new JoinAndQuit(), this);
Bukkit.getPluginManager().registerEvents(new BreakFurniture(), this); Bukkit.getPluginManager().registerEvents(new BreakFurniture(), this);
Bukkit.getPluginManager().registerEvents(new InteractEntity(this), this); Bukkit.getPluginManager().registerEvents(new InteractEntity(this), this);
@@ -93,10 +99,10 @@ public final class CustomCrops extends JavaPlugin {
this.sprinklerManager.loadData(); this.sprinklerManager.loadData();
this.potManager = new PotManager(); this.potManager = new PotManager();
this.potManager.loadData(); this.potManager.loadData();
this.cropTimer = new CropTimer(this); this.cropTimer = new CropTimer();
checkIAConfig(); checkIAConfig();
if (ConfigReader.Config.version != 2){ if (!Objects.equals(ConfigReader.Config.version, "3")){
UpdateConfig.update(); ConfigUtil.update();
} }
AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><color:#F5DEB3>Plugin Enabled!"); AdventureManager.consoleMessage("<gradient:#ff206c:#fdee55>[CustomCrops] </gradient><color:#F5DEB3>Plugin Enabled!");
} }
@@ -129,7 +135,7 @@ public final class CustomCrops extends JavaPlugin {
} }
getLogger().info("Backing Up..."); getLogger().info("Backing Up...");
BackUp.backUpData(); FileUtil.backUpData();
getLogger().info("Done."); getLogger().info("Done.");
if (cropTimer != null) { if (cropTimer != null) {

View File

@@ -20,7 +20,7 @@ package net.momirealms.customcrops.commands;
import net.momirealms.customcrops.utils.AdventureManager; import net.momirealms.customcrops.utils.AdventureManager;
import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.ConfigReader;
import net.momirealms.customcrops.CustomCrops; import net.momirealms.customcrops.CustomCrops;
import net.momirealms.customcrops.utils.BackUp; import net.momirealms.customcrops.utils.FileUtil;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
@@ -53,7 +53,7 @@ public class Executor implements CommandExecutor {
switch (args[0]){ switch (args[0]){
case "reload" -> { case "reload" -> {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
ConfigReader.ReloadConfig(); ConfigReader.reloadConfig();
if(sender instanceof Player){ if(sender instanceof Player){
AdventureManager.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.reload.replace("{time}", String.valueOf(System.currentTimeMillis() - time))); AdventureManager.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.reload.replace("{time}", String.valueOf(System.currentTimeMillis() - time)));
}else { }else {
@@ -139,7 +139,7 @@ public class Executor implements CommandExecutor {
} }
} }
case "backup" -> { case "backup" -> {
BackUp.backUpData(); FileUtil.backUpData();
if (sender instanceof Player player){ if (sender instanceof Player player){
AdventureManager.playerMessage(player,ConfigReader.Message.prefix + ConfigReader.Message.backUp); AdventureManager.playerMessage(player,ConfigReader.Message.prefix + ConfigReader.Message.backUp);
}else { }else {

View File

@@ -26,9 +26,9 @@ import net.momirealms.customcrops.CustomCrops;
import net.momirealms.customcrops.fertilizer.Fertilizer; import net.momirealms.customcrops.fertilizer.Fertilizer;
import net.momirealms.customcrops.fertilizer.RetainingSoil; import net.momirealms.customcrops.fertilizer.RetainingSoil;
import net.momirealms.customcrops.fertilizer.SpeedGrow; 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.JedisUtil;
import net.momirealms.customcrops.utils.SimpleLocation; import net.momirealms.customcrops.objects.SimpleLocation;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
@@ -309,7 +309,7 @@ public class CropManager {
} }
//农作物实例不存在 //农作物实例不存在
String[] cropNameList = StringUtils.split(id,"_"); String[] cropNameList = StringUtils.split(id,"_");
CropInstance cropInstance = ConfigReader.CROPS.get(cropNameList[0]); Crop cropInstance = ConfigReader.CROPS.get(cropNameList[0]);
if (cropInstance == null){ if (cropInstance == null){
return true; return true;
} }

View File

@@ -24,10 +24,8 @@ import net.momirealms.customcrops.fertilizer.Fertilizer;
import net.momirealms.customcrops.fertilizer.QualityCrop; import net.momirealms.customcrops.fertilizer.QualityCrop;
import net.momirealms.customcrops.fertilizer.RetainingSoil; import net.momirealms.customcrops.fertilizer.RetainingSoil;
import net.momirealms.customcrops.fertilizer.SpeedGrow; 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.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.configuration.MemorySection; import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;

View File

@@ -17,6 +17,7 @@
package net.momirealms.customcrops.datamanager; package net.momirealms.customcrops.datamanager;
import net.momirealms.customcrops.hook.RealisticSeason;
import net.momirealms.customcrops.utils.AdventureManager; import net.momirealms.customcrops.utils.AdventureManager;
import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.ConfigReader;
import net.momirealms.customcrops.CustomCrops; import net.momirealms.customcrops.CustomCrops;
@@ -80,13 +81,17 @@ public class SeasonManager{
* @param world 世界 * @param world 世界
*/ */
public void getSeason(World world) { public void getSeason(World world) {
int season = (int) ((world.getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) / ConfigReader.Season.duration; if (ConfigReader.Config.realisticSeason){
switch (season) { SEASON.put(world.getName(), RealisticSeason.getSeason(world));
case 0 -> SEASON.put(world.getName(), "spring"); }else {
case 1 -> SEASON.put(world.getName(), "summer"); int season = (int) ((world.getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) / ConfigReader.Season.duration;
case 2 -> SEASON.put(world.getName(), "autumn"); switch (season) {
case 3 -> SEASON.put(world.getName(), "winter"); case 0 -> SEASON.put(world.getName(), "spring");
default -> AdventureManager.consoleMessage("<red>[CustomCrops] 自动季节计算错误!</red>"); case 1 -> SEASON.put(world.getName(), "summer");
case 2 -> SEASON.put(world.getName(), "autumn");
case 3 -> SEASON.put(world.getName(), "winter");
default -> AdventureManager.consoleMessage("<red>[CustomCrops] 自动季节计算错误!</red>");
}
} }
} }

View File

@@ -19,6 +19,8 @@ package net.momirealms.customcrops.datamanager;
import dev.lone.itemsadder.api.CustomBlock; import dev.lone.itemsadder.api.CustomBlock;
import net.momirealms.customcrops.listener.JoinAndQuit; 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.utils.*;
import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.ConfigReader;
import net.momirealms.customcrops.CustomCrops; import net.momirealms.customcrops.CustomCrops;
@@ -136,7 +138,7 @@ public class SprinklerManager {
bukkitScheduler.runTask(CustomCrops.plugin, ()->{ bukkitScheduler.runTask(CustomCrops.plugin, ()->{
int water = (int) map.get("water"); int water = (int) map.get("water");
int range = (int) Optional.ofNullable(map.get("range")).orElse(0); 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); data.set(worldName + "." + chunk + "." + key, null);
return; return;
} }
@@ -246,7 +248,7 @@ public class SprinklerManager {
String[] coordinate = StringUtils.split(key, ","); 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); 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, ()->{ bukkitScheduler.runTask(CustomCrops.plugin, ()->{
if(!IAFurniture.getFromLocation(location, world)){ if(!IAFurnitureUtil.isSprinkler(location)){
data.set(worldName + "." + chunk + "." + key, null); data.set(worldName + "." + chunk + "." + key, null);
return; return;
} }

View File

@@ -15,7 +15,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package net.momirealms.customcrops.utils; package net.momirealms.customcrops.hook;
import me.clip.placeholderapi.expansion.PlaceholderExpansion; import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.ConfigReader;
@@ -40,12 +40,13 @@ public class Placeholders extends PlaceholderExpansion{
@Override @Override
public @NotNull String getVersion() { public @NotNull String getVersion() {
return "1.2"; return "1.3";
} }
@Override @Override
public String onRequest(OfflinePlayer player, String params) { public String onRequest(OfflinePlayer player, String params) {
if (params.equalsIgnoreCase("season")){ if (params.equalsIgnoreCase("season")){
if (!ConfigReader.Season.enable) return "null";
return Optional.ofNullable(SeasonManager.SEASON.get(player.getPlayer().getWorld().getName())).orElse(ConfigReader.Message.noSeason) return Optional.ofNullable(SeasonManager.SEASON.get(player.getPlayer().getWorld().getName())).orElse(ConfigReader.Message.noSeason)
.replace("spring", ConfigReader.Message.spring) .replace("spring", ConfigReader.Message.spring)
.replace("summer", ConfigReader.Message.summer) .replace("summer", ConfigReader.Message.summer)
@@ -53,6 +54,7 @@ public class Placeholders extends PlaceholderExpansion{
.replace("winter", ConfigReader.Message.winter); .replace("winter", ConfigReader.Message.winter);
} }
if (params.startsWith("season_")){ if (params.startsWith("season_")){
if (!ConfigReader.Season.enable) return "null";
return SeasonManager.SEASON.get(params.substring(7)) return SeasonManager.SEASON.get(params.substring(7))
.replace("spring", ConfigReader.Message.spring) .replace("spring", ConfigReader.Message.spring)
.replace("summer", ConfigReader.Message.summer) .replace("summer", ConfigReader.Message.summer)
@@ -60,21 +62,21 @@ public class Placeholders extends PlaceholderExpansion{
.replace("winter", ConfigReader.Message.winter); .replace("winter", ConfigReader.Message.winter);
} }
if (params.equalsIgnoreCase("nextseason")){ if (params.equalsIgnoreCase("nextseason")){
if (!ConfigReader.Config.worlds.contains(player.getPlayer().getWorld())){ if (!ConfigReader.Season.enable) return "null";
return ConfigReader.Message.noSeason; 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)); return String.valueOf(ConfigReader.Season.duration - ((int) ((player.getPlayer().getWorld().getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) % ConfigReader.Season.duration));
} }
if (params.startsWith("nextseason_")){ 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)); 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 (params.equalsIgnoreCase("current")){
if (!ConfigReader.Config.worlds.contains(player.getPlayer().getWorld())){ if (!ConfigReader.Season.enable) return "null";
return ConfigReader.Message.noSeason; 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); return String.valueOf((int) ((player.getPlayer().getWorld().getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) % ConfigReader.Season.duration + 1);
} }
if (params.startsWith("current_")){ 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 String.valueOf(((int) (Bukkit.getWorld(params.substring(8)).getFullTime() / 24000L) % (ConfigReader.Season.duration * 4)) % ConfigReader.Season.duration+ 1);
} }
return null; return null;

View File

@@ -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";
}
}

View File

@@ -44,10 +44,9 @@ public class KingdomsX implements Integration {
if (kp.getKingdom() != null) { if (kp.getKingdom() != null) {
Kingdom kingdom = kp.getKingdom(); Kingdom kingdom = kp.getKingdom();
return kingdom != cropKingdom; return kingdom != cropKingdom;
} else {
return false;
} }
else return false;
} }
return true; else return true;
} }
} }

View File

@@ -29,20 +29,14 @@ public class Lands implements Integration{
@Override @Override
public boolean canBreak(Location location, Player player) { public boolean canBreak(Location location, Player player) {
Area area = new LandsIntegration(CustomCrops.plugin).getAreaByLoc(location); Area area = new LandsIntegration(CustomCrops.plugin).getAreaByLoc(location);
if (area != null){ if (area != null) return area.hasFlag(player, Flags.BLOCK_BREAK, false);
return area.hasFlag(player, Flags.BLOCK_BREAK, false); else return true;
}else {
return true;
}
} }
@Override @Override
public boolean canPlace(Location location, Player player) { public boolean canPlace(Location location, Player player) {
Area area = new LandsIntegration(CustomCrops.plugin).getAreaByLoc(location); Area area = new LandsIntegration(CustomCrops.plugin).getAreaByLoc(location);
if (area != null){ if (area != null) return area.hasFlag(player, Flags.BLOCK_PLACE, false);
return area.hasFlag(player, Flags.BLOCK_PLACE, false); else return true;
}else {
return true;
}
} }
} }

View File

@@ -35,10 +35,7 @@ public class PlotSquared implements Integration {
private boolean isAllowed(org.bukkit.Location location, Player player) { private boolean isAllowed(org.bukkit.Location location, Player player) {
Location plotLoc = Location.at(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); Location plotLoc = Location.at(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ());
if (plotLoc.isPlotRoad()) return false; if (plotLoc.isPlotRoad()) return false;
if (plotLoc.getPlotArea() != null){ if (plotLoc.getPlotArea() != null) return plotLoc.getPlotArea().getPlot(plotLoc).isAdded(player.getUniqueId());
return plotLoc.getPlotArea().getPlot(plotLoc).isAdded(player.getUniqueId()); else return true;
}else {
return true;
}
} }
} }

View File

@@ -40,9 +40,8 @@ public class WorldGuard implements Integration {
if (hasRegion(world, BukkitAdapter.asBlockVector(location))){ if (hasRegion(world, BukkitAdapter.asBlockVector(location))){
RegionQuery query = platform.getRegionContainer().createQuery(); RegionQuery query = platform.getRegionContainer().createQuery();
return query.testBuild(BukkitAdapter.adapt(location), localPlayer, Flags.BUILD); return query.testBuild(BukkitAdapter.adapt(location), localPlayer, Flags.BUILD);
}else {
return true;
} }
else return true;
} }
@Override @Override
@@ -53,9 +52,8 @@ public class WorldGuard implements Integration {
if (hasRegion(world, BukkitAdapter.asBlockVector(location))){ if (hasRegion(world, BukkitAdapter.asBlockVector(location))){
RegionQuery query = platform.getRegionContainer().createQuery(); RegionQuery query = platform.getRegionContainer().createQuery();
return query.testBuild(BukkitAdapter.adapt(location), localPlayer, Flags.BLOCK_BREAK); return query.testBuild(BukkitAdapter.adapt(location), localPlayer, Flags.BLOCK_BREAK);
}else {
return true;
} }
else return true;
} }
private boolean hasRegion(World world, BlockVector3 vector){ private boolean hasRegion(World world, BlockVector3 vector){

View File

@@ -24,28 +24,22 @@ import org.bukkit.Location;
public class CropsPerChunk { public class CropsPerChunk {
public static boolean isLimited(Location location){ public static boolean isLimited(Location location){
if(!ConfigReader.Config.enableLimit){ if (!ConfigReader.Config.enableLimit) return false;
return false;
}
int n = 1; int n = 1;
Location chunkLocation = new Location(location.getWorld(),location.getChunk().getX()*16,ConfigReader.Config.yMin,location.getChunk().getZ()*16); Location chunkLocation = new Location(location.getWorld(),location.getChunk().getX()*16,ConfigReader.Config.yMin,location.getChunk().getZ()*16);
Label_out: Label_out:
for (int i = 0; i < 16; ++i) { for (int i = 0; i < 16; ++i)
for (int j = 0; j < 16; ++j) { for (int j = 0; j < 16; ++j) {
Location square = chunkLocation.clone().add(i, 0.0, j); Location square = chunkLocation.clone().add(i, 0.0, j);
for (int k = ConfigReader.Config.yMin; k <= ConfigReader.Config.yMax; ++k) { for (int k = ConfigReader.Config.yMin; k <= ConfigReader.Config.yMax; ++k) {
square.add(0.0, 1.0, 0.0); square.add(0.0, 1.0, 0.0);
CustomBlock customBlock = CustomBlock.byAlreadyPlaced(square.getBlock()); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(square.getBlock());
if(customBlock != null){ if(customBlock != null)
if (customBlock.getNamespacedID().contains("_stage_")) { if (customBlock.getNamespacedID().contains("_stage_"))
if (n++ > ConfigReader.Config.cropLimit) { if (n++ > ConfigReader.Config.cropLimit)
break Label_out; break Label_out;
}
}
}
} }
} }
}
return n > ConfigReader.Config.cropLimit; return n > ConfigReader.Config.cropLimit;
} }
} }

View File

@@ -18,33 +18,26 @@
package net.momirealms.customcrops.limits; package net.momirealms.customcrops.limits;
import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.ConfigReader;
import net.momirealms.customcrops.utils.IAFurniture; import net.momirealms.customcrops.utils.IAFurnitureUtil;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World;
public class SprinklersPerChunk { public class SprinklersPerChunk {
public static boolean isLimited(Location location){ public static boolean isLimited(Location location){
if(!ConfigReader.Config.enableLimit){ if (!ConfigReader.Config.enableLimit) return false;
return false;
}
int n = 1; int n = 1;
Location chunkLocation = new Location(location.getWorld(),location.getChunk().getX()*16,ConfigReader.Config.yMin,location.getChunk().getZ()*16); Location chunkLocation = new Location(location.getWorld(),location.getChunk().getX()*16, ConfigReader.Config.yMin,location.getChunk().getZ()*16);
World world = location.getWorld();
Label_out: Label_out:
for (int i = 0; i < 16; ++i) { for (int i = 0; i < 16; ++i)
for (int j = 0; j < 16; ++j) { for (int j = 0; j < 16; ++j) {
Location square = chunkLocation.clone().add(i + 0.5, 0.5, j + 0.5); Location square = chunkLocation.clone().add(i + 0.5, 0.5, j + 0.5);
for (int k = ConfigReader.Config.yMin; k <= ConfigReader.Config.yMax; ++k) { for (int k = ConfigReader.Config.yMin; k <= ConfigReader.Config.yMax; ++k) {
square.add(0.0, 1.0, 0.0); square.add(0.0, 1.0, 0.0);
if(IAFurniture.getFromLocation(square, world)){ if(IAFurnitureUtil.isSprinkler(square))
if (n++ > ConfigReader.Config.sprinklerLimit) { if (n++ > ConfigReader.Config.sprinklerLimit)
break Label_out; break Label_out;
}
}
} }
} }
}
return n > ConfigReader.Config.sprinklerLimit; return n > ConfigReader.Config.sprinklerLimit;
} }
} }

View File

@@ -26,8 +26,8 @@ import net.momirealms.customcrops.datamanager.PotManager;
import net.momirealms.customcrops.fertilizer.Fertilizer; import net.momirealms.customcrops.fertilizer.Fertilizer;
import net.momirealms.customcrops.fertilizer.QualityCrop; import net.momirealms.customcrops.fertilizer.QualityCrop;
import net.momirealms.customcrops.integrations.protection.Integration; import net.momirealms.customcrops.integrations.protection.Integration;
import net.momirealms.customcrops.utils.CropInstance; import net.momirealms.customcrops.objects.Crop;
import net.momirealms.customcrops.utils.SimpleLocation; import net.momirealms.customcrops.objects.SimpleLocation;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
@@ -51,77 +51,51 @@ public class BreakBlock implements Listener {
if(namespacedId.contains("_stage_")){ if(namespacedId.contains("_stage_")){
Player player = event.getPlayer(); Player player = event.getPlayer();
Location location = event.getBlock().getLocation(); Location location = event.getBlock().getLocation();
for (Integration integration : ConfigReader.Config.integration){ for (Integration integration : ConfigReader.Config.integration)
if(!integration.canBreak(location, player)) return; 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); event.setCancelled(true);
CustomBlock.place(namespacedId, location); CustomBlock.place(namespacedId, location);
CustomBlock.byAlreadyPlaced(location.getBlock()).getLoot().forEach(itemStack -> { CustomBlock.byAlreadyPlaced(location.getBlock()).getLoot().forEach(itemStack -> location.getWorld().dropItem(location.clone().add(0.5,0.2,0.5), itemStack));
location.getWorld().dropItem(location.clone().add(0.5,0.2,0.5), itemStack);
});
CustomBlock.remove(location); CustomBlock.remove(location);
return; 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], "_"); String[] cropNameList = StringUtils.split(StringUtils.split(namespacedId, ":")[1], "_");
int nextStage = Integer.parseInt(cropNameList[2]) + 1; int nextStage = Integer.parseInt(cropNameList[2]) + 1;
if (CustomBlock.getInstance(StringUtils.chop(namespacedId) + nextStage) == null) { if (CustomBlock.getInstance(StringUtils.chop(namespacedId) + nextStage) == null) {
Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, ()-> { Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, ()-> {
if (location.getBlock().getType() != Material.AIR) return; 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(); ThreadLocalRandom current = ThreadLocalRandom.current();
int random = current.nextInt(cropInstance.getMin(), cropInstance.getMax() + 1); int random = current.nextInt(cropInstance.getMin(), cropInstance.getMax() + 1);
Location itemLoc = location.clone().add(0.5,0.2,0.5); Location itemLoc = location.clone().add(0.5,0.2,0.5);
World world = location.getWorld(); World world = location.getWorld();
Fertilizer fertilizer = PotManager.Cache.get(SimpleLocation.fromLocation(location.clone().subtract(0,1,0)));
List<String> commands = cropInstance.getCommands(); List<String> commands = cropInstance.getCommands();
if (commands != null){ Fertilizer fertilizer = PotManager.Cache.get(SimpleLocation.fromLocation(location.clone().subtract(0,1,0)));
Bukkit.getScheduler().callSyncMethod(CustomCrops.plugin, ()-> { if (commands != null)
for (String command : commands){ Bukkit.getScheduler().runTask(CustomCrops.plugin, ()-> {
for (String command : commands)
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName())); Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName()));
}
return null;
}); });
} if (ConfigReader.Config.skillXP != null && cropInstance.getSkillXP() != 0)
if (ConfigReader.Config.skillXP != null && cropInstance.getSkillXP() != 0){ Bukkit.getScheduler().runTask(CustomCrops.plugin, ()-> ConfigReader.Config.skillXP.addXp(player, cropInstance.getSkillXP()));
Bukkit.getScheduler().callSyncMethod(CustomCrops.plugin, ()-> {
ConfigReader.Config.skillXP.addXp(player, cropInstance.getSkillXP());
return null;
});
}
if (fertilizer != null){ if (fertilizer != null){
if (fertilizer instanceof QualityCrop qualityCrop){ if (fertilizer instanceof QualityCrop qualityCrop){
int[] weights = qualityCrop.getChance(); int[] weights = qualityCrop.getChance();
double weightTotal = weights[0] + weights[1] + weights[2]; double weightTotal = weights[0] + weights[1] + weights[2];
double rank_1 = weights[0]/(weightTotal); Bukkit.getScheduler().runTask(CustomCrops.plugin, ()-> {
double rank_2 = 1 - weights[1]/(weightTotal);
Bukkit.getScheduler().callSyncMethod(CustomCrops.plugin, ()-> {
for (int i = 0; i < random; i++){ for (int i = 0; i < random; i++){
double ran = Math.random(); double ran = Math.random();
if (ran < rank_1){ if (ran < weights[0]/(weightTotal)) world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_1()).getItemStack());
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 if(ran > rank_2){ else world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_3()).getItemStack());
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 { else Bukkit.getScheduler().runTask(CustomCrops.plugin, ()-> normalDrop(cropInstance, random, itemLoc, world));
Bukkit.getScheduler().callSyncMethod(CustomCrops.plugin, ()-> {
normalDrop(cropInstance, random, itemLoc, world);
return null;
});
} }
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)); PotManager.Cache.remove(SimpleLocation.fromLocation(location));
World world = location.getWorld(); World world = location.getWorld();
Block blockUp = location.add(0,1,0).getBlock(); 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(!integration.canBreak(location, event.getPlayer())) return;
}
if(CustomBlock.byAlreadyPlaced(blockUp) != null){ if(CustomBlock.byAlreadyPlaced(blockUp) != null){
CustomBlock customBlock = CustomBlock.byAlreadyPlaced(blockUp); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(blockUp);
String cropNamespacedId = customBlock.getNamespacedID(); String cropNamespacedId = customBlock.getNamespacedID();
@@ -143,7 +116,7 @@ public class BreakBlock implements Listener {
String[] cropNameList = StringUtils.split(StringUtils.split(cropNamespacedId, ":")[1], "_"); String[] cropNameList = StringUtils.split(StringUtils.split(cropNamespacedId, ":")[1], "_");
int nextStage = Integer.parseInt(cropNameList[2]) + 1; int nextStage = Integer.parseInt(cropNameList[2]) + 1;
if (CustomBlock.getInstance(StringUtils.chop(cropNamespacedId) + nextStage) == null) { 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(); ThreadLocalRandom current = ThreadLocalRandom.current();
int random = current.nextInt(cropInstance.getMin(), cropInstance.getMax() + 1); int random = current.nextInt(cropInstance.getMin(), cropInstance.getMax() + 1);
Location itemLoc = location.clone().add(0.5,0.2,0.5); 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){ if (fertilizer instanceof QualityCrop qualityCrop){
int[] weights = qualityCrop.getChance(); int[] weights = qualityCrop.getChance();
double weightTotal = weights[0] + weights[1] + weights[2]; 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++){ for (int i = 0; i < random; i++){
double ran = Math.random(); double ran = Math.random();
if (ran < rank_1){ if (ran < weights[0]/(weightTotal)) world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_1()).getItemStack());
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 if(ran > rank_2){ else world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_3()).getItemStack());
world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_2()).getItemStack());
}else {
world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_3()).getItemStack());
}
} }
} }
} }
else { else normalDrop(cropInstance, random, itemLoc, world);
normalDrop(cropInstance, random, itemLoc, world);
}
return; return;
} }
} }
for (ItemStack itemStack : customBlock.getLoot()) { for (ItemStack itemStack : customBlock.getLoot())
world.dropItem(location.clone().add(0.5, 0.2, 0.5), itemStack); world.dropItem(location.clone().add(0.5, 0.2, 0.5), itemStack);
}
CustomBlock.remove(location); CustomBlock.remove(location);
} }
} }
@@ -188,7 +152,7 @@ public class BreakBlock implements Listener {
* @param itemLoc 掉落物位置 * @param itemLoc 掉落物位置
* @param world 世界 * @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++){ for (int i = 0; i < random; i++){
double ran = Math.random(); double ran = Math.random();
if (ran < ConfigReader.Config.quality_1){ if (ran < ConfigReader.Config.quality_1){

View File

@@ -3,9 +3,8 @@ package net.momirealms.customcrops.listener;
import dev.lone.itemsadder.api.Events.FurnitureBreakEvent; import dev.lone.itemsadder.api.Events.FurnitureBreakEvent;
import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.ConfigReader;
import net.momirealms.customcrops.datamanager.SprinklerManager; import net.momirealms.customcrops.datamanager.SprinklerManager;
import net.momirealms.customcrops.utils.SimpleLocation; import net.momirealms.customcrops.objects.SimpleLocation;
import net.momirealms.customcrops.utils.Sprinkler; import net.momirealms.customcrops.objects.Sprinkler;
import org.apache.commons.lang.StringUtils;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
@@ -13,7 +12,7 @@ public class BreakFurniture implements Listener {
@EventHandler @EventHandler
public void onBreakFurniture(FurnitureBreakEvent event){ 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){ if (config != null){
SimpleLocation simpleLocation = SimpleLocation.fromLocation(event.getBukkitEntity().getLocation()); SimpleLocation simpleLocation = SimpleLocation.fromLocation(event.getBukkitEntity().getLocation());
SprinklerManager.Cache.remove(simpleLocation); SprinklerManager.Cache.remove(simpleLocation);

View File

@@ -19,29 +19,25 @@ package net.momirealms.customcrops.listener;
import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTItem; 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 dev.lone.itemsadder.api.Events.FurnitureInteractEvent;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.ConfigReader;
import net.momirealms.customcrops.CustomCrops; import net.momirealms.customcrops.CustomCrops;
import net.momirealms.customcrops.datamanager.SprinklerManager; 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 net.momirealms.customcrops.utils.*;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Optional;
public class InteractEntity implements Listener { public class InteractEntity implements Listener {
@@ -55,13 +51,11 @@ public class InteractEntity implements Listener {
@EventHandler @EventHandler
public void onEntityInteract(FurnitureInteractEvent event){ 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){ if(config != null){
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
Player player = event.getPlayer(); Player player = event.getPlayer();
if (time - (coolDown.getOrDefault(player, time - 200)) < 200) { if (time - (coolDown.getOrDefault(player, time - 200)) < 200) return;
return;
}
coolDown.put(player, time); coolDown.put(player, time);
ItemStack itemStack = player.getInventory().getItemInMainHand(); ItemStack itemStack = player.getInventory().getItemInMainHand();
Location location = event.getBukkitEntity().getLocation(); Location location = event.getBukkitEntity().getLocation();
@@ -77,17 +71,13 @@ public class InteractEntity implements Listener {
if (sprinkler != null){ if (sprinkler != null){
currentWater = sprinkler.getWater(); currentWater = sprinkler.getWater();
currentWater += ConfigReader.Config.sprinklerRefill; currentWater += ConfigReader.Config.sprinklerRefill;
if (currentWater > maxWater){ if (currentWater > maxWater) currentWater = maxWater;
currentWater = maxWater;
}
sprinkler.setWater(currentWater); sprinkler.setWater(currentWater);
}else { }else {
String path = world + "." + x / 16 + "," + z / 16 + "." + x + "," + location.getBlockY() + "," + z ; String path = world + "." + x / 16 + "," + z / 16 + "." + x + "," + location.getBlockY() + "," + z ;
currentWater = plugin.getSprinklerManager().data.getInt(path+ ".water"); currentWater = plugin.getSprinklerManager().data.getInt(path+ ".water");
currentWater += ConfigReader.Config.sprinklerRefill; currentWater += ConfigReader.Config.sprinklerRefill;
if (currentWater > maxWater){ if (currentWater > maxWater) currentWater = maxWater;
currentWater = maxWater;
}
plugin.getSprinklerManager().data.set(path + ".water", currentWater); plugin.getSprinklerManager().data.set(path + ".water", currentWater);
plugin.getSprinklerManager().data.set(path + ".range", config.getRange()); plugin.getSprinklerManager().data.set(path + ".range", config.getRange());
} }
@@ -101,36 +91,40 @@ public class InteractEntity implements Listener {
NBTCompound nbtCompound = nbtItem.getCompound("itemsadder"); NBTCompound nbtCompound = nbtItem.getCompound("itemsadder");
if (nbtCompound != null) { if (nbtCompound != null) {
String id = nbtCompound.getString("id"); String id = nbtCompound.getString("id");
Optional<WateringCan> can = Optional.ofNullable(ConfigReader.CANS.get(id)); String namespace = nbtCompound.getString("namespace");
if (can.isPresent()) { WateringCan wateringCan = ConfigReader.CANS.get(namespace + ":" + id);
WateringCan wateringCan = can.get(); if (wateringCan != null) {
water--; nbtItem.setInteger("WaterAmount", --water);
nbtItem.setInteger("WaterAmount", water);
AdventureManager.playerSound(player, ConfigReader.Sounds.addWaterToSprinklerSource, ConfigReader.Sounds.addWaterToSprinklerKey); AdventureManager.playerSound(player, ConfigReader.Sounds.addWaterToSprinklerSource, ConfigReader.Sounds.addWaterToSprinklerKey);
if (sprinkler != null){ if (sprinkler != null){
currentWater = sprinkler.getWater(); currentWater = sprinkler.getWater();
currentWater++; currentWater++;
if (currentWater > maxWater){ if (currentWater > maxWater) currentWater = maxWater;
currentWater = maxWater;
}
sprinkler.setWater(currentWater); sprinkler.setWater(currentWater);
}else { }else {
String path = world + "." + x / 16 + "," + z / 16 + "." + x + "," + location.getBlockY() + "," + z + ".water"; String path = world + "." + x / 16 + "," + z / 16 + "." + x + "," + location.getBlockY() + "," + z + ".water";
currentWater = plugin.getSprinklerManager().data.getInt(path); currentWater = plugin.getSprinklerManager().data.getInt(path);
currentWater++; currentWater++;
if (currentWater > maxWater){ if (currentWater > maxWater) currentWater = maxWater;
currentWater = maxWater;
}
plugin.getSprinklerManager().data.set(path, currentWater); plugin.getSprinklerManager().data.set(path, currentWater);
} }
if (ConfigReader.Message.hasWaterInfo){ if (ConfigReader.Message.hasWaterInfo){
String string = ConfigReader.Message.waterLeft + ConfigReader.Message.waterFull.repeat(water) + AdventureManager.playerActionbar(player,
ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water) + ConfigReader.Message.waterRight; (ConfigReader.Message.waterLeft +
AdventureManager.playerActionbar(player, string.replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water))); 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){ if (ConfigReader.Basic.hasWaterLore){
String string = (ConfigReader.Basic.waterLeft + ConfigReader.Basic.waterFull.repeat(water) + String string =
ConfigReader.Basic.waterEmpty.repeat(wateringCan.getMax() - water) + ConfigReader.Basic.waterRight).replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water)); (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<String> lores = nbtItem.getCompound("display").getStringList("Lore"); List<String> lores = nbtItem.getCompound("display").getStringList("Lore");
lores.clear(); lores.clear();
ConfigReader.Basic.waterLore.forEach(lore -> lores.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(lore.replace("{water_info}", string))))); 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()); itemStack.setItemMeta(nbtItem.getItem().getItemMeta());
} }
} }
}else {
currentWater = getCurrentWater(location, world, x, z, sprinkler);
} }
else currentWater = getCurrentWater(location, world, x, z, sprinkler);
} }
else { else currentWater = getCurrentWater(location, world, x, z, sprinkler);
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);
}
} }
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) { private int getCurrentWater(Location location, String world, int x, int z, Sprinkler sprinkler) {
int currentWater; int currentWater;
if (sprinkler != null){ if (sprinkler != null) currentWater = sprinkler.getWater();
currentWater = sprinkler.getWater(); else {
}else {
String path = world + "." + x / 16 + "," + z / 16 + "." + x + "," + location.getBlockY() + "," + z + ".water"; String path = world + "." + x / 16 + "," + z / 16 + "." + x + "," + location.getBlockY() + "," + z + ".water";
currentWater = plugin.getSprinklerManager().data.getInt(path); currentWater = plugin.getSprinklerManager().data.getInt(path);
} }

View File

@@ -27,13 +27,9 @@ public class ItemSpawn implements Listener {
@EventHandler @EventHandler
public void entitySpawn(EntitySpawnEvent event){ public void entitySpawn(EntitySpawnEvent event){
if(event.getEntity() instanceof Item item) { if(event.getEntity() instanceof Item item)
if(CustomStack.byItemStack(item.getItemStack()) != null){ if(CustomStack.byItemStack(item.getItemStack()) != null)
String id = CustomStack.byItemStack(item.getItemStack()).getId(); if(CustomStack.byItemStack(item.getItemStack()).getId().contains("_stage_"))
if(id.contains("_stage_")){
item.remove(); item.remove();
}
}
}
} }
} }

View File

@@ -14,19 +14,13 @@ public class JoinAndQuit implements Listener {
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent event){ public void onJoin(PlayerJoinEvent event){
if (JedisUtil.useRedis){ if (JedisUtil.useRedis) JedisUtil.addPlayer(event.getPlayer().getName());
JedisUtil.addPlayer(event.getPlayer().getName()); else onlinePlayers.add(event.getPlayer().getName());
}else {
onlinePlayers.add(event.getPlayer().getName());
}
} }
@EventHandler @EventHandler
public void onQuit(PlayerQuitEvent event){ public void onQuit(PlayerQuitEvent event){
if (JedisUtil.useRedis){ if (JedisUtil.useRedis) JedisUtil.remPlayer(event.getPlayer().getName());
JedisUtil.remPlayer(event.getPlayer().getName()); else onlinePlayers.remove(event.getPlayer().getName());
}else {
onlinePlayers.remove(event.getPlayer().getName());
}
} }
} }

View File

@@ -8,10 +8,8 @@ public class PapiReload implements Listener {
@EventHandler @EventHandler
public void onReload(me.clip.placeholderapi.events.ExpansionUnregisterEvent event){ public void onReload(me.clip.placeholderapi.events.ExpansionUnregisterEvent event){
if (CustomCrops.placeholders != null){ if (CustomCrops.placeholders != null)
if (event.getExpansion().equals(CustomCrops.placeholders)){ if (event.getExpansion().equals(CustomCrops.placeholders))
CustomCrops.placeholders.register(); CustomCrops.placeholders.register();
}
}
} }
} }

View File

@@ -35,6 +35,10 @@ import net.momirealms.customcrops.fertilizer.SpeedGrow;
import net.momirealms.customcrops.integrations.protection.Integration; import net.momirealms.customcrops.integrations.protection.Integration;
import net.momirealms.customcrops.limits.CropsPerChunk; import net.momirealms.customcrops.limits.CropsPerChunk;
import net.momirealms.customcrops.limits.SprinklersPerChunk; 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.PlantingCondition;
import net.momirealms.customcrops.requirements.Requirement; import net.momirealms.customcrops.requirements.Requirement;
import net.momirealms.customcrops.utils.*; import net.momirealms.customcrops.utils.*;
@@ -52,7 +56,6 @@ import org.bukkit.inventory.ItemStack;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
public class RightClick implements Listener { public class RightClick implements Listener {
@@ -63,9 +66,7 @@ public class RightClick implements Listener {
public void onInteract(PlayerInteractEvent event){ public void onInteract(PlayerInteractEvent event){
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
Player player = event.getPlayer(); Player player = event.getPlayer();
if (time - (coolDown.getOrDefault(player, time - 250)) < 250) { if (time - (coolDown.getOrDefault(player, time - 250)) < 250) return;
return;
}
coolDown.put(player, time); coolDown.put(player, time);
Action action = event.getAction(); Action action = event.getAction();
if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK){ 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"); NBTCompound nbtCompound = nbtItem.getCompound("itemsadder");
if (nbtCompound != null){ if (nbtCompound != null){
String id = nbtCompound.getString("id"); 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){ if (id.endsWith("_seeds") && action == Action.RIGHT_CLICK_BLOCK && event.getBlockFace() == BlockFace.UP){
String cropName = StringUtils.remove(id, "_seeds"); String cropName = StringUtils.remove(id, "_seeds");
Optional<CropInstance> crop = Optional.ofNullable(ConfigReader.CROPS.get(cropName)); Crop cropInstance = ConfigReader.CROPS.get(cropName);
if (crop.isPresent()){ if (cropInstance != null){
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block);
if (customBlock == null) return; if (customBlock == null) return;
String namespacedID = customBlock.getNamespacedID(); String namespacedID = customBlock.getNamespacedID();
if (namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)){ if (namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)){
Location location = block.getLocation().add(0,1,0); //已+1 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(!integration.canPlace(location, player)) return;
} if(IAFurnitureUtil.isSprinkler(location.clone().add(0.5, 0.5, 0.5))) return;
if(IAFurniture.getFromLocation(location.clone().add(0.5, 0.5, 0.5), location.getWorld())){
return;
}
CropInstance cropInstance = crop.get();
PlantingCondition plantingCondition = new PlantingCondition(player, location); PlantingCondition plantingCondition = new PlantingCondition(player, location);
if (cropInstance.getRequirements() != null){ if (cropInstance.getRequirements() != null)
for (Requirement requirement : cropInstance.getRequirements()){ for (Requirement requirement : cropInstance.getRequirements())
if (!requirement.canPlant(plantingCondition)) return; if (!requirement.canPlant(plantingCondition)) return;
}
}
Label_out: Label_out:
if (ConfigReader.Season.enable && cropInstance.getSeasons() != null){ if (ConfigReader.Season.enable && cropInstance.getSeasons() != null){
if (!ConfigReader.Config.allWorld){ if (!ConfigReader.Config.allWorld){
for (String season : cropInstance.getSeasons()) { for (String season : cropInstance.getSeasons())
if (season.equals(SeasonManager.SEASON.get(location.getWorld().getName()))){ if (season.equals(SeasonManager.SEASON.get(location.getWorld().getName())))
break Label_out; break Label_out;
}
}
}else { }else {
for(String season : cropInstance.getSeasons()){ for(String season : cropInstance.getSeasons())
if (season.equals(SeasonManager.SEASON.get(ConfigReader.Config.referenceWorld))) { if (season.equals(SeasonManager.SEASON.get(ConfigReader.Config.referenceWorld)))
break Label_out; break Label_out;
}
}
} }
if(ConfigReader.Season.greenhouse){ if(ConfigReader.Season.greenhouse){
for(int i = 1; i <= ConfigReader.Season.range; i++){ for(int i = 1; i <= ConfigReader.Season.range; i++){
CustomBlock cb = CustomBlock.byAlreadyPlaced(location.clone().add(0,i,0).getBlock()); CustomBlock cb = CustomBlock.byAlreadyPlaced(location.clone().add(0,i,0).getBlock());
if (cb != null){ if (cb != null)
if(cb.getNamespacedID().equalsIgnoreCase(ConfigReader.Basic.glass)){ if(cb.getNamespacedID().equalsIgnoreCase(ConfigReader.Basic.glass))
break Label_out; break Label_out;
}
}
} }
} }
if (ConfigReader.Config.nwSeason){ if (ConfigReader.Config.nwSeason) AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.badSeason);
AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.badSeason); if (ConfigReader.Config.pwSeason) return;
}
if (ConfigReader.Config.pwSeason){
return;
}
}
if (location.getBlock().getType() != Material.AIR){
return;
} }
if (location.getBlock().getType() != Material.AIR) return;
if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1);
if (CropsPerChunk.isLimited(location)){ if (CropsPerChunk.isLimited(location)){
AdventureManager.playerMessage(player,ConfigReader.Message.prefix + ConfigReader.Message.crop_limit.replace("{max}", String.valueOf(ConfigReader.Config.cropLimit))); AdventureManager.playerMessage(player,ConfigReader.Message.prefix + ConfigReader.Message.crop_limit.replace("{max}", String.valueOf(ConfigReader.Config.cropLimit)));
return; return;
} }
if (player.getGameMode() != GameMode.CREATIVE){
itemStack.setAmount(itemStack.getAmount() - 1);
}
CropManager.Cache.put(location, player.getName()); 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); AdventureManager.playerSound(player, ConfigReader.Sounds.plantSeedSource, ConfigReader.Sounds.plantSeedKey);
return;
} }
}else { }else AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.not_configed);
AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.not_configed);
}
return; return;
} }
WateringCan wateringCan = ConfigReader.CANS.get(id); WateringCan wateringCan = ConfigReader.CANS.get(itemNID);
if (wateringCan != null){ if (wateringCan != null){
int water = nbtItem.getInteger("WaterAmount"); int water = nbtItem.getInteger("WaterAmount");
List<Block> lineOfSight = player.getLineOfSight(null, 5); List<Block> lineOfSight = player.getLineOfSight(null, 5);
@@ -158,27 +138,30 @@ public class RightClick implements Listener {
if (block.getType() == Material.WATER) { if (block.getType() == Material.WATER) {
if (wateringCan.getMax() > water){ if (wateringCan.getMax() > water){
water += ConfigReader.Config.waterCanRefill; water += ConfigReader.Config.waterCanRefill;
if (water > wateringCan.getMax()){ if (water > wateringCan.getMax()) water = wateringCan.getMax();
water = wateringCan.getMax();
}
nbtItem.setInteger("WaterAmount", water); nbtItem.setInteger("WaterAmount", water);
player.getWorld().playSound(player.getLocation(), Sound.ITEM_BUCKET_FILL,1,1); player.getWorld().playSound(player.getLocation(), Sound.ITEM_BUCKET_FILL,1,1);
if (ConfigReader.Message.hasWaterInfo)
if (ConfigReader.Message.hasWaterInfo){ AdventureManager.playerActionbar(player,
String string = ConfigReader.Message.waterLeft + ConfigReader.Message.waterFull.repeat(water) + (ConfigReader.Message.waterLeft +
ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water) + ConfigReader.Message.waterRight; ConfigReader.Message.waterFull.repeat(water) +
AdventureManager.playerActionbar(player, string.replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(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){ 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<String> lores = nbtItem.getCompound("display").getStringList("Lore"); List<String> lores = nbtItem.getCompound("display").getStringList("Lore");
lores.clear(); 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))))); ConfigReader.Basic.waterLore.forEach(lore -> lores.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(lore.replace("{water_info}", string)))));
} }
if (ConfigReader.Config.hasParticle){ 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);
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()); itemStack.setItemMeta(nbtItem.getItem().getItemMeta());
} }
return; return;
@@ -188,41 +171,57 @@ public class RightClick implements Listener {
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block);
if (customBlock == null) return; if (customBlock == null) return;
for (Integration integration : ConfigReader.Config.integration){ for (Integration integration : ConfigReader.Config.integration)
if(!integration.canPlace(block.getLocation(), player)) return; if(!integration.canPlace(block.getLocation(), player)) return;
}
String namespacedID = customBlock.getNamespacedID(); String namespacedID = customBlock.getNamespacedID();
if ((namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)) && event.getBlockFace() == BlockFace.UP){ if ((namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)) && event.getBlockFace() == BlockFace.UP){
nbtItem.setInteger("WaterAmount", water - 1); nbtItem.setInteger("WaterAmount", water - 1);
AdventureManager.playerSound(player, ConfigReader.Sounds.waterPotSource, ConfigReader.Sounds.waterPotKey); AdventureManager.playerSound(player, ConfigReader.Sounds.waterPotSource, ConfigReader.Sounds.waterPotKey);
waterPot(wateringCan.getWidth(), wateringCan.getLength(), block.getLocation(), player.getLocation().getYaw()); waterPot(wateringCan.getWidth(), wateringCan.getLength(), block.getLocation(), player.getLocation().getYaw());
if (ConfigReader.Message.hasWaterInfo){ if (ConfigReader.Message.hasWaterInfo)
String string = ConfigReader.Message.waterLeft + ConfigReader.Message.waterFull.repeat(water - 1) + AdventureManager.playerActionbar(player,
ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water + 1) + ConfigReader.Message.waterRight; (ConfigReader.Message.waterLeft +
AdventureManager.playerActionbar(player, string.replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water -1))); 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){ 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<String> lores = nbtItem.getCompound("display").getStringList("Lore"); List<String> lores = nbtItem.getCompound("display").getStringList("Lore");
lores.clear(); 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))))); ConfigReader.Basic.waterLore.forEach(lore -> lores.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(lore.replace("{water_info}", string)))));
} }
itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); itemStack.setItemMeta(nbtItem.getItem().getItemMeta());
} else if (namespacedID.contains("_stage_")){ }
else if (namespacedID.contains("_stage_")){
nbtItem.setInteger("WaterAmount", water - 1); nbtItem.setInteger("WaterAmount", water - 1);
AdventureManager.playerSound(player, ConfigReader.Sounds.waterPotSource, ConfigReader.Sounds.waterPotKey); AdventureManager.playerSound(player, ConfigReader.Sounds.waterPotSource, ConfigReader.Sounds.waterPotKey);
waterPot(wateringCan.getWidth(), wateringCan.getLength(), block.getLocation().subtract(0,1,0), player.getLocation().getYaw()); waterPot(wateringCan.getWidth(), wateringCan.getLength(), block.getLocation().subtract(0,1,0), player.getLocation().getYaw());
if (ConfigReader.Message.hasWaterInfo){ if (ConfigReader.Message.hasWaterInfo)
String string = ConfigReader.Message.waterLeft + ConfigReader.Message.waterFull.repeat(water - 1) + AdventureManager.playerActionbar(player,
ConfigReader.Message.waterEmpty.repeat(wateringCan.getMax() - water + 1) + ConfigReader.Message.waterRight; (ConfigReader.Message.waterLeft +
AdventureManager.playerActionbar(player, string.replace("{max_water}", String.valueOf(wateringCan.getMax())).replace("{water}", String.valueOf(water -1))); 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){ 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<String> lores = nbtItem.getCompound("display").getStringList("Lore"); List<String> lores = nbtItem.getCompound("display").getStringList("Lore");
lores.clear(); 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))))); ConfigReader.Basic.waterLore.forEach(lore -> lores.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(lore.replace("{water_info}", string)))));
} }
itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); itemStack.setItemMeta(nbtItem.getItem().getItemMeta());
@@ -235,9 +234,8 @@ public class RightClick implements Listener {
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block);
if (customBlock == null) return; if (customBlock == null) return;
for (Integration integration : ConfigReader.Config.integration){ for (Integration integration : ConfigReader.Config.integration)
if(!integration.canPlace(block.getLocation(), player)) return; if(!integration.canPlace(block.getLocation(), player)) return;
}
String namespacedID = customBlock.getNamespacedID(); String namespacedID = customBlock.getNamespacedID();
if (namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)){ if (namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)){
CustomBlock customBlockUp = CustomBlock.byAlreadyPlaced(block.getLocation().clone().add(0,1,0).getBlock()); 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); AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.beforePlant);
return; return;
}else { }else {
if (player.getGameMode() != GameMode.CREATIVE){ if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1);
itemStack.setAmount(itemStack.getAmount() - 1);
}
AdventureManager.playerSound(player, ConfigReader.Sounds.useFertilizerSource, ConfigReader.Sounds.useFertilizerKey); AdventureManager.playerSound(player, ConfigReader.Sounds.useFertilizerSource, ConfigReader.Sounds.useFertilizerKey);
addFertilizer(fertilizerConfig, block.getLocation()); addFertilizer(fertilizerConfig, block.getLocation());
} }
}else { }else {
if (player.getGameMode() != GameMode.CREATIVE){ if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1);
itemStack.setAmount(itemStack.getAmount() - 1);
}
AdventureManager.playerSound(player, ConfigReader.Sounds.useFertilizerSource, ConfigReader.Sounds.useFertilizerKey); AdventureManager.playerSound(player, ConfigReader.Sounds.useFertilizerSource, ConfigReader.Sounds.useFertilizerKey);
addFertilizer(fertilizerConfig, block.getLocation()); addFertilizer(fertilizerConfig, block.getLocation());
} }
}else if (namespacedID.contains("_stage_")){ }else if (namespacedID.contains("_stage_")){
if (!fertilizerConfig.isBefore()){ if (!fertilizerConfig.isBefore()){
if (player.getGameMode() != GameMode.CREATIVE){ if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1);
itemStack.setAmount(itemStack.getAmount() - 1);
}
addFertilizer(fertilizerConfig, block.getLocation().subtract(0,1,0)); addFertilizer(fertilizerConfig, block.getLocation().subtract(0,1,0));
AdventureManager.playerSound(player, ConfigReader.Sounds.useFertilizerSource, ConfigReader.Sounds.useFertilizerKey); AdventureManager.playerSound(player, ConfigReader.Sounds.useFertilizerSource, ConfigReader.Sounds.useFertilizerKey);
}else { }else {
@@ -273,49 +265,46 @@ public class RightClick implements Listener {
} }
return; 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){ if (sprinkler != null && action == Action.RIGHT_CLICK_BLOCK && event.getBlockFace() == BlockFace.UP){
Location location = event.getClickedBlock().getLocation(); Location location = event.getClickedBlock().getLocation();
for (Integration integration : ConfigReader.Config.integration){ for (Integration integration : ConfigReader.Config.integration)
if (!integration.canPlace(location, player)) return; if (!integration.canPlace(location, player)) return;
} if (IAFurnitureUtil.isSprinkler(location.clone().add(0.5, 1.5, 0.5))) return;
if(IAFurniture.getFromLocation(location.clone().add(0.5, 1.5, 0.5), location.getWorld())){ if (SprinklersPerChunk.isLimited(location)){
return;
}
if(SprinklersPerChunk.isLimited(location)){
AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.sprinkler_limit.replace("{max}", String.valueOf(ConfigReader.Config.sprinklerLimit))); AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.sprinkler_limit.replace("{max}", String.valueOf(ConfigReader.Config.sprinklerLimit)));
return; return;
} }
Sprinkler sprinklerData = new Sprinkler(sprinkler.getRange(), 0); Sprinkler sprinklerData = new Sprinkler(sprinkler.getRange(), 0);
sprinklerData.setPlayer(player.getName()); sprinklerData.setPlayer(player.getName());
if (player.getGameMode() != GameMode.CREATIVE){ if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1);
itemStack.setAmount(itemStack.getAmount() - 1);
}
SimpleLocation simpleLocation = SimpleLocation.fromLocation(location.add(0,1,0)); SimpleLocation simpleLocation = SimpleLocation.fromLocation(location.add(0,1,0));
SprinklerManager.Cache.put(simpleLocation, sprinklerData); SprinklerManager.Cache.put(simpleLocation, sprinklerData);
SprinklerManager.RemoveCache.remove(simpleLocation); 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); AdventureManager.playerSound(player, ConfigReader.Sounds.placeSprinklerSource, ConfigReader.Sounds.placeSprinklerKey);
return; 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(); Block block = event.getClickedBlock();
CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block);
if (customBlock == null) return; if (customBlock == null) return;
for (Integration integration : ConfigReader.Config.integration){ for (Integration integration : ConfigReader.Config.integration) if(!integration.canPlace(block.getLocation(), player)) return;
if(!integration.canPlace(block.getLocation(), player)) return;
}
String namespacedID = customBlock.getNamespacedID(); String namespacedID = customBlock.getNamespacedID();
if (namespacedID.contains("_stage_")){ if (namespacedID.contains("_stage_")){
Location location = block.getLocation().subtract(0,1,0); Location location = block.getLocation().subtract(0,1,0);
Fertilizer fertilizer = PotManager.Cache.get(SimpleLocation.fromLocation(location)); Fertilizer fertilizer = PotManager.Cache.get(SimpleLocation.fromLocation(location));
if (fertilizer != null){ if (fertilizer != null){
Fertilizer config = ConfigReader.FERTILIZERS.get(fertilizer.getKey()); Fertilizer config = ConfigReader.FERTILIZERS.get(fertilizer.getKey());
String name = config.getName(); if (config == null) return;
int max_times = config.getTimes(); HoloUtil.showHolo(
if(!HoloUtil.cache.contains(location.add(0.5, ConfigReader.Message.cropOffset, 0.5))) { ConfigReader.Message.cropText
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); .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)){ }else if(namespacedID.equals(ConfigReader.Basic.pot) || namespacedID.equals(ConfigReader.Basic.watered_pot)){
Location location = block.getLocation(); Location location = block.getLocation();
@@ -324,9 +313,14 @@ public class RightClick implements Listener {
Fertilizer config = ConfigReader.FERTILIZERS.get(fertilizer.getKey()); Fertilizer config = ConfigReader.FERTILIZERS.get(fertilizer.getKey());
String name = config.getName(); String name = config.getName();
int max_times = config.getTimes(); int max_times = config.getTimes();
if(!HoloUtil.cache.contains(location.add(0.5,ConfigReader.Message.cropOffset,0.5))){ HoloUtil.showHolo(
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); 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(); Block block = event.getClickedBlock();
CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block);
if (customBlock == null) return; if (customBlock == null) return;
for (Integration integration : ConfigReader.Config.integration){ for (Integration integration : ConfigReader.Config.integration)
if(!integration.canPlace(block.getLocation(), player)) return; if(!integration.canPlace(block.getLocation(), player)) return;
}
String namespacedID = customBlock.getNamespacedID(); String namespacedID = customBlock.getNamespacedID();
if (namespacedID.contains("_stage_") && !namespacedID.equals(ConfigReader.Basic.dead)){ if (namespacedID.contains("_stage_") && !namespacedID.equals(ConfigReader.Basic.dead)){
int nextStage = Integer.parseInt(namespacedID.substring(namespacedID.length()-1)) + 1; int nextStage = Integer.parseInt(namespacedID.substring(namespacedID.length()-1)) + 1;
String next = StringUtils.chop(namespacedID) + nextStage; String next = StringUtils.chop(namespacedID) + nextStage;
if (CustomBlock.getInstance(next) != null){ if (CustomBlock.getInstance(next) != null){
Location location = block.getLocation(); Location location = block.getLocation();
if (player.getGameMode() != GameMode.CREATIVE){ if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1);
itemStack.setAmount(itemStack.getAmount() - 1);
}
AdventureManager.playerSound(player, ConfigReader.Sounds.boneMealSource, ConfigReader.Sounds.boneMealKey); AdventureManager.playerSound(player, ConfigReader.Sounds.boneMealSource, ConfigReader.Sounds.boneMealKey);
if (Math.random() < ConfigReader.Config.boneMealChance){ if (Math.random() < ConfigReader.Config.boneMealChance){
CustomBlock.remove(location); 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); 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); rightClickHarvest(event.getClickedBlock(), player);
}
} }
} }
@@ -375,62 +364,43 @@ public class RightClick implements Listener {
Location location = block.getLocation(); Location location = block.getLocation();
CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block);
if (customBlock == null) return; if (customBlock == null) return;
for (Integration integration : ConfigReader.Config.integration){ for (Integration integration : ConfigReader.Config.integration)
if (!integration.canBreak(location, player)) return; if (!integration.canBreak(location, player)) return;
}
String namespacedID = customBlock.getNamespacedID(); String namespacedID = customBlock.getNamespacedID();
if (namespacedID.contains("_stage_")){ if (namespacedID.contains("_stage_")){
if(namespacedID.equals(ConfigReader.Basic.dead)) return; if(namespacedID.equals(ConfigReader.Basic.dead)) return;
String[] cropNameList = StringUtils.split(customBlock.getId(), "_"); String[] cropNameList = StringUtils.split(customBlock.getId(), "_");
int nextStage = Integer.parseInt(cropNameList[2]) + 1; int nextStage = Integer.parseInt(cropNameList[2]) + 1;
if (CustomBlock.getInstance(StringUtils.chop(namespacedID) + nextStage) == null) { 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){ if (ConfigReader.Config.quality){
ThreadLocalRandom current = ThreadLocalRandom.current(); ThreadLocalRandom current = ThreadLocalRandom.current();
int random = current.nextInt(cropInstance.getMin(), cropInstance.getMax() + 1); int random = current.nextInt(cropInstance.getMin(), cropInstance.getMax() + 1);
World world = location.getWorld(); World world = location.getWorld();
Location itemLoc = location.clone().add(0.5,0.2,0.5); 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<String> commands = cropInstance.getCommands(); List<String> commands = cropInstance.getCommands();
if (commands != null){ if (commands != null)
for (String command : commands){ for (String command : commands)
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName())); 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 != null){
if (fertilizer instanceof QualityCrop qualityCrop){ if (fertilizer instanceof QualityCrop qualityCrop){
int[] weights = qualityCrop.getChance(); int[] weights = qualityCrop.getChance();
double weightTotal = weights[0] + weights[1] + weights[2]; 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++){ for (int i = 0; i < random; i++){
double ran = Math.random(); double ran = Math.random();
if (ran < rank_1){ if (ran < weights[0]/(weightTotal)) world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_1()).getItemStack());
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 if(ran > rank_2){ else world.dropItem(itemLoc, CustomStack.getInstance(cropInstance.getQuality_3()).getItemStack());
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 { else BreakBlock.normalDrop(cropInstance, random, itemLoc, world);
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 customBlock.getLoot().forEach(loot-> location.getWorld().dropItem(location.clone().add(0.5,0.2,0.5), loot));
CustomBlock.remove(location); CustomBlock.remove(location);
AdventureManager.playerSound(player, ConfigReader.Sounds.harvestSource, ConfigReader.Sounds.harvestKey); AdventureManager.playerSound(player, ConfigReader.Sounds.harvestSource, ConfigReader.Sounds.harvestKey);
if(cropInstance.getReturnStage() != null){ 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()); RetainingSoil retainingSoil = new RetainingSoil(config.getKey(), config.getTimes(),config.getChance(), config.isBefore());
PotManager.Cache.put(SimpleLocation.fromLocation(location), retainingSoil); 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); 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 视角 * @param yaw 视角
*/ */
private void waterPot(int width, int length, Location location, float 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); 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; int extend = width / 2;
// -90~90 z+
// -180~-90 & 90-180 z-
// -180~0 x+
// 0~180 x-
if (yaw < 45 && yaw > -135) { if (yaw < 45 && yaw > -135) {
// -45 ~ 45
if (yaw > -45) { if (yaw > -45) {
for (int i = -extend; i <= extend; i++) { for (int i = -extend; i <= extend; i++) {
Location tempLoc = location.clone().add(i, 0, -1); Location tempLoc = location.clone().add(i, 0, -1);
@@ -500,7 +463,6 @@ public class RightClick implements Listener {
} }
} }
} }
// -135 ~ -45
else { else {
for (int i = -extend; i <= extend; i++) { for (int i = -extend; i <= extend; i++) {
Location tempLoc = location.clone().add(-1, 0, i); Location tempLoc = location.clone().add(-1, 0, i);
@@ -518,7 +480,6 @@ public class RightClick implements Listener {
} }
} }
else { else {
// 45 ~ 135
if (yaw > 45 && yaw < 135) { if (yaw > 45 && yaw < 135) {
for (int i = -extend; i <= extend; i++) { for (int i = -extend; i <= extend; i++) {
Location tempLoc = location.clone().add(1, 0, i); Location tempLoc = location.clone().add(1, 0, i);
@@ -534,7 +495,6 @@ public class RightClick implements Listener {
} }
} }
} }
// -180 ~ -135 135~180
else { else {
for (int i = -extend; i <= extend; i++) { for (int i = -extend; i <= extend; i++) {
Location tempLoc = location.clone().add(i, 0, 1); Location tempLoc = location.clone().add(i, 0, 1);

View File

@@ -15,13 +15,13 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package net.momirealms.customcrops.utils; package net.momirealms.customcrops.objects;
import net.momirealms.customcrops.requirements.Requirement; import net.momirealms.customcrops.requirements.Requirement;
import java.util.List; import java.util.List;
public class CropInstance { public class Crop {
private double giantChance; private double giantChance;
private String giant; private String giant;
@@ -38,7 +38,7 @@ public class CropInstance {
private List<String> commands; private List<String> commands;
private double growChance; private double growChance;
public CropInstance(int min, int max){ public Crop(int min, int max){
this.min = min; this.min = min;
this.max = max; this.max = max;
} }

View File

@@ -15,7 +15,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package net.momirealms.customcrops.utils; package net.momirealms.customcrops.objects;
import org.bukkit.Location; import org.bukkit.Location;

View File

@@ -15,7 +15,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package net.momirealms.customcrops.utils; package net.momirealms.customcrops.objects;
public class Sprinkler { public class Sprinkler {

View File

@@ -15,7 +15,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package net.momirealms.customcrops.utils; package net.momirealms.customcrops.objects;
public record WateringCan(int max, int width, int length) { public record WateringCan(int max, int width, int length) {

View File

@@ -31,11 +31,9 @@ public record Biome(List<String> biomes) implements Requirement {
@Override @Override
public boolean canPlant(PlantingCondition plantingCondition) { public boolean canPlant(PlantingCondition plantingCondition) {
String currentBiome = plantingCondition.getLocation().getBlock().getBiome().getKey().toString(); String currentBiome = plantingCondition.getLocation().getBlock().getBiome().getKey().toString();
for (String biome : biomes) { for (String biome : biomes)
if (currentBiome.equalsIgnoreCase(biome)) { if (currentBiome.equalsIgnoreCase(biome))
return true; return true;
}
}
AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badBiome); AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badBiome);
return false; return false;
} }

View File

@@ -28,9 +28,7 @@ public record Permission(String permission) implements Requirement {
@Override @Override
public boolean canPlant(PlantingCondition plantingCondition) { public boolean canPlant(PlantingCondition plantingCondition) {
if (plantingCondition.getPlayer().hasPermission(permission)){ if (plantingCondition.getPlayer().hasPermission(permission)) return true;
return true;
}
AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badPerm); AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badPerm);
return false; return false;
} }

View File

@@ -31,9 +31,7 @@ public record World(List<String> worlds) implements Requirement {
@Override @Override
public boolean canPlant(PlantingCondition plantingCondition) { public boolean canPlant(PlantingCondition plantingCondition) {
org.bukkit.World world = plantingCondition.getLocation().getWorld(); org.bukkit.World world = plantingCondition.getLocation().getWorld();
if (worlds.contains(world.getName())){ if (worlds.contains(world.getName())) return true;
return true;
}
AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badWorld); AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badWorld);
return false; return false;
} }

View File

@@ -34,9 +34,7 @@ public record YPos(List<String> yPos) implements Requirement {
int y = (int) plantingCondition.getLocation().getY(); int y = (int) plantingCondition.getLocation().getY();
for (String range : yPos) { for (String range : yPos) {
String[] yMinMax = StringUtils.split(range, "~"); String[] yMinMax = StringUtils.split(range, "~");
if (y > Integer.parseInt(yMinMax[0]) && y < Integer.parseInt(yMinMax[1])) { if (y > Integer.parseInt(yMinMax[0]) && y < Integer.parseInt(yMinMax[1])) return true;
return true;
}
} }
AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badY); AdventureManager.playerMessage(plantingCondition.player(), ConfigReader.Message.prefix +ConfigReader.Message.badY);
return false; return false;

View File

@@ -26,14 +26,11 @@ public class CropTimer {
private final int taskID; private final int taskID;
public CropTimer(CustomCrops plugin) { public CropTimer() {
TimeCheck tc = new TimeCheck(plugin); TimeCheck tc = new TimeCheck();
BukkitTask task; BukkitTask task;
if (ConfigReader.Config.asyncCheck){ if (ConfigReader.Config.asyncCheck) task = tc.runTaskTimerAsynchronously(CustomCrops.plugin, 1,1);
task = tc.runTaskTimerAsynchronously(CustomCrops.plugin, 1,1); else task = tc.runTaskTimer(CustomCrops.plugin, 1,1);
}else {
task = tc.runTaskTimer(CustomCrops.plugin, 1,1);
}
this.taskID = task.getTaskId(); this.taskID = task.getTaskId();
} }

View File

@@ -24,44 +24,37 @@ import org.bukkit.scheduler.BukkitRunnable;
public class TimeCheck extends BukkitRunnable { public class TimeCheck extends BukkitRunnable {
private final CustomCrops plugin;
public TimeCheck(CustomCrops plugin){
this.plugin = plugin;
}
@Override @Override
public void run() { public void run() {
ConfigReader.Config.worlds.forEach(world ->{ ConfigReader.Config.worlds.forEach(world ->{
long time = world.getTime(); long time = world.getTime();
ConfigReader.Config.cropGrowTimeList.forEach(cropGrowTime -> { ConfigReader.Config.cropGrowTimeList.forEach(cropGrowTime -> {
if(time == 0){ if(time == 0)
if(ConfigReader.Season.enable && ConfigReader.Season.seasonChange){ if(ConfigReader.Season.enable && ConfigReader.Season.seasonChange)
plugin.getSeasonManager().getSeason(world); CustomCrops.plugin.getSeasonManager().getSeason(world);
}
}
if(time == cropGrowTime){ if(time == cropGrowTime){
if (ConfigReader.Config.allWorld){ if (ConfigReader.Config.allWorld){
Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> { Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> {
plugin.getCropManager().cropGrowAll(); CustomCrops.plugin.getCropManager().cropGrowAll();
}); });
Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.plugin, ()->{ Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.plugin, ()->{
plugin.getSprinklerManager().sprinklerWorkAll(); CustomCrops.plugin.getSprinklerManager().sprinklerWorkAll();
}, ConfigReader.Config.timeToGrow); }, ConfigReader.Config.timeToGrow);
}else { }else {
Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> { Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> {
switch (ConfigReader.Config.growMode){ switch (ConfigReader.Config.growMode){
case 1 -> plugin.getCropManager().growModeOne(world.getName()); case 1 -> CustomCrops.plugin.getCropManager().growModeOne(world.getName());
case 2 -> plugin.getCropManager().growModeTwo(world.getName()); case 2 -> CustomCrops.plugin.getCropManager().growModeTwo(world.getName());
case 3 -> plugin.getCropManager().growModeThree(world.getName()); case 3 -> CustomCrops.plugin.getCropManager().growModeThree(world.getName());
case 4 -> plugin.getCropManager().growModeFour(world.getName()); case 4 -> CustomCrops.plugin.getCropManager().growModeFour(world.getName());
} }
}); });
Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.plugin, ()->{ Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.plugin, ()->{
switch (ConfigReader.Config.growMode){ switch (ConfigReader.Config.growMode){
case 1 -> plugin.getSprinklerManager().workModeOne(world.getName()); case 1 -> CustomCrops.plugin.getSprinklerManager().workModeOne(world.getName());
case 2 -> plugin.getSprinklerManager().workModeTwo(world.getName()); case 2 -> CustomCrops.plugin.getSprinklerManager().workModeTwo(world.getName());
case 3 -> plugin.getSprinklerManager().workModeThree(world.getName()); case 3 -> CustomCrops.plugin.getSprinklerManager().workModeThree(world.getName());
case 4 -> plugin.getSprinklerManager().workModeFour(world.getName()); case 4 -> CustomCrops.plugin.getSprinklerManager().workModeFour(world.getName());
} }
}, ConfigReader.Config.timeToGrow); }, ConfigReader.Config.timeToGrow);
} }

View File

@@ -12,11 +12,11 @@ import net.momirealms.customcrops.helper.Log;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
public class UpdateConfig { public class ConfigUtil {
public static void update(){ public static void update(){
try { 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){ }catch (IOException e){
Log.warn(e.getMessage()); Log.warn(e.getMessage());
} }

View File

@@ -28,7 +28,7 @@ import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; 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 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"); File backUp = new File(CustomCrops.plugin.getDataFolder(), "backups"+ File.separatorChar + format.format(date) + File.separatorChar + fileName + ".yml");
try { try {
BackUp.backUp(data, backUp); FileUtil.backUp(data, backUp);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
CustomCrops.plugin.getLogger().warning(fileName + ".yml备份出错!"); CustomCrops.plugin.getLogger().warning(fileName + ".yml备份出错!");

View File

@@ -38,7 +38,7 @@ import java.util.*;
public class HoloUtil { public class HoloUtil {
public static HashSet<Location> cache = new HashSet<>(); public static HashMap<Location, Integer> cache = new HashMap<>();
/** /**
* 对指定玩家展示在指定位置的盔甲架 * 对指定玩家展示在指定位置的盔甲架
* @param text 文本 * @param text 文本
@@ -48,6 +48,10 @@ public class HoloUtil {
*/ */
public static void showHolo(String text, Player player, Location location, int duration){ 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); PacketContainer packet1 = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
int id = new Random().nextInt(1000000000); int id = new Random().nextInt(1000000000);
@@ -73,7 +77,7 @@ public class HoloUtil {
wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, serializer2), mask2); wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, serializer2), mask2);
packet2.getModifier().write(0,id); packet2.getModifier().write(0,id);
packet2.getWatchableCollectionModifier().write(0, wrappedDataWatcher.getWatchableObjects()); packet2.getWatchableCollectionModifier().write(0, wrappedDataWatcher.getWatchableObjects());
cache.add(location); cache.put(location, id);
try { try {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet1); ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet1);
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet2); ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet2);

View File

@@ -20,11 +20,9 @@ package net.momirealms.customcrops.utils;
import dev.lone.itemsadder.api.CustomFurniture; import dev.lone.itemsadder.api.CustomFurniture;
import net.momirealms.customcrops.ConfigReader; import net.momirealms.customcrops.ConfigReader;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
public class IAFurniture { public class IAFurnitureUtil {
/** /**
* 在指定位置放置家具 * 在指定位置放置家具
@@ -39,19 +37,19 @@ public class IAFurniture {
* 判断指定位置的盔甲架是不是洒水器 * 判断指定位置的盔甲架是不是洒水器
* 仅限加载中的区块 * 仅限加载中的区块
* @param location 位置 * @param location 位置
* @param world 世界
* @return / * @return /
*/ */
public static boolean getFromLocation(Location location, World world){ public static String getFromLocation(Location location){
for(Entity entity : world.getNearbyEntities(location,0,0,0)){ for(Entity entity : location.getWorld().getNearbyEntities(location,0,0,0)){
if(entity instanceof ArmorStand armorStand){ CustomFurniture furniture = CustomFurniture.byAlreadySpawned(entity);
if(CustomFurniture.byAlreadySpawned(armorStand) != null){ if(furniture != null) return furniture.getNamespacedID();
if(ConfigReader.SPRINKLERS.get(CustomFurniture.byAlreadySpawned(armorStand).getId()) != null){
return true;
}
}
}
} }
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;
} }
} }

View File

@@ -1,4 +1,3 @@
#=============================================================#
#ItemsAdder items namespacedID #ItemsAdder items namespacedID
basic: basic:
pot: customcrops:pot pot: customcrops:pot
@@ -6,7 +5,9 @@ basic:
greenhouse-glass: customcrops:greenhouse_glass greenhouse-glass: customcrops:greenhouse_glass
dead-crop: customcrops:crop_stage_death dead-crop: customcrops:crop_stage_death
soil-detector: customcrops:soil_detector soil-detector: customcrops:soil_detector
#=============================================================#
water-can: water-can:
watering_can_1: watering_can_1:
item: customcrops:watering_can_1 item: customcrops:watering_can_1
@@ -30,7 +31,9 @@ water-can:
max: 6 max: 6
width: 3 width: 3
length: 5 length: 5
#=============================================================#
lore: lore:
#Should lore be changed when using watering-can #Should lore be changed when using watering-can
watering-can: watering-can:
@@ -46,7 +49,9 @@ lore:
full: '뀁뀃' full: '뀁뀃'
empty: '뀁뀄' empty: '뀁뀄'
right: '뀁뀅</font>' right: '뀁뀅</font>'
#=============================================================#
sprinkler: sprinkler:
sprinkler_1: sprinkler_1:
range: 1 range: 1
@@ -58,5 +63,4 @@ sprinkler:
range: 2 range: 2
max-water: 7 max-water: 7
3Ditem: customcrops:sprinkler_2 3Ditem: customcrops:sprinkler_2
2Ditem: customcrops:sprinkler_2_item 2Ditem: customcrops:sprinkler_2_item
#=============================================================#

View File

@@ -1,10 +1,12 @@
#Don't change #Don't change
config-version: 2 config-version: 3
config: config:
#=============================================================#
#english spanish chinese #english spanish chinese
lang: english lang: english
#=============================================================#
integration: integration:
#integration to prevent other players' grief #integration to prevent other players' grief
Residence: false Residence: false
@@ -21,7 +23,11 @@ config:
mcMMO: false mcMMO: false
MMOCore: false MMOCore: false
EcoSkills: false EcoSkills: false
#=============================================================# #integration to sync seasons
RealisticSeasons: false
#Mode 1: #Mode 1:
# Crops in loaded chunks will grow # Crops in loaded chunks will grow
#Mode 2: #Mode 2:
@@ -55,13 +61,17 @@ config:
#This is useful for per player per world server. #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. #In this mode, whitelist world can only have one as the standard of time & season judgment.
all-world-grow: false all-world-grow: false
#=============================================================#
quality: quality:
#If disabled, you need to configurate the loot in ItemsAdder config #If disabled, you need to configurate the loot in ItemsAdder config
enable: true enable: true
#Default ratio #Default ratio
default-ratio: 17/2/1 default-ratio: 17/2/1
#=============================================================#
#Water Amount to refill when using water bucket #Water Amount to refill when using water bucket
sprinkler-refill: 2 sprinkler-refill: 2
#Water Amount to refill with a sigle click to water block #Water Amount to refill with a sigle click to water block
@@ -70,13 +80,17 @@ config:
water-can-add-water-to-sprinkler: true water-can-add-water-to-sprinkler: true
#Should particles be displayed when using watering can? #Should particles be displayed when using watering can?
water-particles: true water-particles: true
#=============================================================#
#Will bone meal accelerate the growth of crop #Will bone meal accelerate the growth of crop
bone-meal: bone-meal:
enable: true enable: true
chance: 0.5 chance: 0.5
success-particle: VILLAGER_HAPPY success-particle: VILLAGER_HAPPY
#=============================================================#
#Should we limit the max amount of crops and sprinkler in one chunk #Should we limit the max amount of crops and sprinkler in one chunk
#Recommended to enable because ItemsAdder might throw StackOverFlow #Recommended to enable because ItemsAdder might throw StackOverFlow
#when there are too many custom blocks in one chunk #when there are too many custom blocks in one chunk
@@ -84,7 +98,9 @@ config:
enable: true enable: true
crop: 64 crop: 64
sprinkler: 8 sprinkler: 8
#=============================================================#
#can player harvest crops with right click? #can player harvest crops with right click?
#if set "false" crops can't be harvested repeatedly #if set "false" crops can't be harvested repeatedly
right-click-harvest: true right-click-harvest: true
@@ -94,5 +110,4 @@ config:
#Should player be prevented from planting if wrong season #Should player be prevented from planting if wrong season
prevent-plant-if-wrong-season: true prevent-plant-if-wrong-season: true
#Should notify player of the wrong season? #Should notify player of the wrong season?
should-notify-if-wrong-season: true should-notify-if-wrong-season: true
#=============================================================#

View File

@@ -27,7 +27,9 @@ speed:
times: 14 times: 14
item: customcrops:speed_3 item: customcrops:speed_3
before-plant: true before-plant: true
#=============================================================#
#Pot have a small chance to retain its water after crops grow #Pot have a small chance to retain its water after crops grow
retaining: retaining:
retaining_1: retaining_1:
@@ -50,7 +52,9 @@ retaining:
times: 28 times: 28
item: customcrops:retaining_3 item: customcrops:retaining_3
before-plant: false before-plant: false
#=============================================================#
#When haveresting, players have a higher chance to get high quality crops. #When haveresting, players have a higher chance to get high quality crops.
quality: quality:
quality_1: quality_1:
@@ -72,5 +76,4 @@ quality:
times: 28 times: 28
chance: 2/2/1 chance: 2/2/1
item: customcrops:quality_3 item: customcrops:quality_3
before-plant: true before-plant: true
#=============================================================#

View File

@@ -21,6 +21,7 @@ softdepend:
- MMOCore - MMOCore
- EcoSkills - EcoSkills
- CrashClaim - CrashClaim
- RealisticSeasons
commands: commands:
customcrops: customcrops:
usage: /customcrops <args> usage: /customcrops <args>

View File

@@ -4,8 +4,11 @@ season:
enable: true enable: true
auto-season-change: auto-season-change:
#If you enabled RealisticSeasons Integration
#keep this true
enable: true enable: true
#duration of each season #duration of each season
#would not take effect if enabled RealisticSeasons Integration
duration: 28 duration: 28
greenhouse: greenhouse: