diff --git a/build.gradle b/build.gradle index 31107b2..0911cd3 100644 --- a/build.gradle +++ b/build.gradle @@ -4,48 +4,44 @@ plugins { } group = 'net.momirealms' -version = '2.2.9.1' +version = '3.0.0-beta1' repositories { mavenCentral() - maven {name = 'papermc-repo'; url = 'https://papermc.io/repo/repository/maven-public/'} + maven {name = "aliyun repo"; url = "https://maven.aliyun.com/repository/public/"} + maven {name = 'papermc repo'; url = 'https://papermc.io/repo/repository/maven-public/'} maven {name = 'sonatype'; url = 'https://oss.sonatype.org/content/groups/public/'} - maven {name = "sonatype-oss-snapshots1"; url = "https://s01.oss.sonatype.org/content/repositories/snapshots/"} - maven {name = "dmulloy2-repo"; url = "https://repo.dmulloy2.net/repository/public/"} - maven {name = "clip-repo"; url = 'https://repo.extendedclip.com/content/repositories/placeholderapi/'} - maven {name = "NBT-API"; url = "https://repo.codemc.org/repository/maven-public/"} - maven {name = "sk89q-repo"; url = "https://maven.enginehub.org/repo/"} - maven {name = "Lumine Releases"; url = "https://mvn.lumine.io/repository/maven-public"} - maven {name = "jitpack-repo"; url = "https://jitpack.io"} + maven {name = "dmulloy2 repo"; url = "https://repo.dmulloy2.net/repository/public/"} + maven {name = "clip repo"; url = 'https://repo.extendedclip.com/content/repositories/placeholderapi/'} + maven {name = "codemc repo"; url = "https://repo.codemc.org/repository/maven-public/"} + maven {name = "enginehub repo"; url = "https://maven.enginehub.org/repo/"} + maven {name = "Lumine repo"; url = "https://mvn.lumine.io/repository/maven-public"} + maven {name = "jitpack repo"; url = "https://jitpack.io"} maven {name = 'glaremasters repo'; url = 'https://repo.glaremasters.me/repository/towny/'} - maven {name = 'superior skyblock repo'; url = 'https://repo.bg-software.com/repository/api/'} - maven {name = 'bg-repo'; url = 'https://repo.bg-software.com/repository/api/'} - maven {name = "Lumine Releases"; url = "https://mvn.lumine.io/repository/maven-public"} + maven {name = 'bg-software repo'; url = 'https://repo.bg-software.com/repository/api/'} } dependencies { compileOnly ('dev.dejvokep:boosted-yaml:1.3') - compileOnly ('com.github.Archy-X:AureliumSkills:Beta1.3.6') + compileOnly ('com.github.Archy-X:AureliumSkills:Beta1.3.18') compileOnly ('commons-io:commons-io:2.11.0') compileOnly ('com.github.angeschossen:LandsAPI:6.26.18') compileOnly ('com.github.TechFortress:GriefPrevention:16.18') - compileOnly ('io.papermc.paper:paper-api:1.17.1-R0.1-SNAPSHOT') - compileOnly ('me.clip:placeholderapi:2.11.2') - compileOnly ('com.sk89q.worldguard:worldguard-bukkit:7.0.7') - compileOnly ('com.github.LoneDev6:api-itemsadder:3.2.3-r8') + compileOnly ('io.papermc.paper:paper-api:1.19.4-R0.1-SNAPSHOT') + compileOnly ('me.clip:placeholderapi:2.11.3') + compileOnly ('com.github.LoneDev6:api-itemsadder:3.4.1-r4') compileOnly ('io.lumine:Mythic-Dist:5.0.3-SNAPSHOT') - compileOnly ('com.palmergames.bukkit.towny:towny:0.98.2.0') - compileOnly ('com.willfp:EcoSkills:1.72.0') - compileOnly ('com.willfp:eco:6.38.3') - compileOnly ('com.bgsoftware:SuperiorSkyblockAPI:2022.9') - compileOnly ('com.github.Zrips:Jobs:4.17.2') - compileOnly ('com.willfp:EcoJobs:1.35.0') + compileOnly ('com.willfp:EcoSkills:2.2.6') + compileOnly ('com.willfp:eco:6.53.1') + compileOnly ('com.willfp:EcoJobs:3.2.5') + compileOnly('net.objecthunter:exp4j:0.4.8') compileOnly fileTree(dir:'libs',includes:['*.jar']) - implementation ('net.kyori:adventure-api:4.13.0') + implementation ('net.kyori:adventure-api:4.13.1') implementation ('net.kyori:adventure-platform-bukkit:4.3.0') - implementation ('net.kyori:adventure-text-minimessage:4.13.0') + implementation ('net.kyori:adventure-text-minimessage:4.13.1') implementation ("de.tr7zw:item-nbt-api:2.11.2") implementation ('org.bstats:bstats-bukkit:3.0.1') + implementation ('org.apache.commons:commons-pool2:2.11.1') implementation fileTree(dir:'libs',includes:['BiomeAPI.jar']) } @@ -82,7 +78,8 @@ shadowJar { relocate ('de.tr7zw', 'net.momirealms.customcrops.libs.de.tr7zw') relocate ('net.kyori', 'net.momirealms.customcrops.libs.net.kyori') relocate ('org.bstats', 'net.momirealms.customcrops.libs.org.bstats') - relocate 'net.momirealms.biomeapi', 'net.momirealms.customcrops.libs.net.momirealms.biomeapi' + relocate ('org.apache.commons.pool2', 'net.momirealms.customcrops.libs.org.apache.commons.pool2') + relocate ('net.momirealms.biomeapi', 'net.momirealms.customcrops.libs.net.momirealms.biomeapi') } tasks.register("delete", Delete).get().delete("build/libs/"+project.name+"-"+project.version+".jar") diff --git a/src/main/java/net/momirealms/customcrops/CustomCrops.java b/src/main/java/net/momirealms/customcrops/CustomCrops.java index f15b268..b86cfcc 100644 --- a/src/main/java/net/momirealms/customcrops/CustomCrops.java +++ b/src/main/java/net/momirealms/customcrops/CustomCrops.java @@ -19,131 +19,185 @@ package net.momirealms.customcrops; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; -import de.tr7zw.changeme.nbtapi.utils.VersionChecker; import net.kyori.adventure.platform.bukkit.BukkitAudiences; -import net.momirealms.customcrops.commands.PluginCommand; -import net.momirealms.customcrops.config.ConfigUtil; -import net.momirealms.customcrops.config.MainConfig; +import net.momirealms.customcrops.api.CustomCropsAPI; +import net.momirealms.customcrops.api.customplugin.Platform; +import net.momirealms.customcrops.api.customplugin.PlatformInterface; +import net.momirealms.customcrops.api.customplugin.PlatformManager; +import net.momirealms.customcrops.api.customplugin.itemsadder.ItemsAdderPluginImpl; +import net.momirealms.customcrops.api.customplugin.oraxen.OraxenPluginImpl; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.basic.MessageManager; +import net.momirealms.customcrops.api.object.crop.CropManager; +import net.momirealms.customcrops.api.object.pot.PotManager; +import net.momirealms.customcrops.api.object.fertilizer.FertilizerManager; +import net.momirealms.customcrops.api.object.season.SeasonManager; +import net.momirealms.customcrops.api.object.sprinkler.SprinklerManager; +import net.momirealms.customcrops.api.object.wateringcan.WateringCanManager; +import net.momirealms.customcrops.api.object.world.CCWorld; +import net.momirealms.customcrops.api.object.world.WorldDataManager; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.command.CustomCropsCommand; import net.momirealms.customcrops.helper.LibraryLoader; import net.momirealms.customcrops.helper.VersionHelper; -import net.momirealms.customcrops.integrations.papi.PlaceholderManager; -import net.momirealms.customcrops.integrations.protection.WorldGuardHook; -import net.momirealms.customcrops.managers.CropManager; -import net.momirealms.customcrops.integrations.quest.BattlePassCCQuest; -import net.momirealms.customcrops.integrations.quest.ClueScrollCCQuest; -import net.momirealms.customcrops.integrations.quest.NewBetonQuestCCQuest; -import net.momirealms.customcrops.integrations.quest.OldBetonQuestCCQuest; -import net.momirealms.customcrops.utils.AdventureUtil; +import net.momirealms.customcrops.integration.IntegrationManager; import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.PluginCommand; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; -import java.util.Objects; import java.util.TimeZone; public final class CustomCrops extends JavaPlugin { - public static BukkitAudiences adventure; - public static CustomCrops plugin; - public static ProtocolManager protocolManager; - - private PlaceholderManager placeholderManager; + private static BukkitAudiences adventure; + private static CustomCrops plugin; + private static ProtocolManager protocolManager; + private Platform platform; + private PlatformInterface platformInterface; private CropManager cropManager; + private IntegrationManager integrationManager; + private WorldDataManager worldDataManager; + private SprinklerManager sprinklerManager; + private WateringCanManager wateringCanManager; + private FertilizerManager fertilizerManager; + private SeasonManager seasonManager; + private PotManager potManager; + private ConfigManager configManager; + private MessageManager messageManager; + private PlatformManager platformManager; private VersionHelper versionHelper; - -// _ooOoo_ -// o8888888o -// 88" . "88 -// (| -_- |) -// O\ = /O -// ____/`---'\____ -// .' \\| |// `. -// / \\||| : |||// \ -// / _||||| -:- |||||_ \ -// | | \\\ - /'| | | -// | \_| `\`---'// |_/ | -// \ .-\__ `-. -'__/-. / -// ___`. .' /--.--\ `. .'___ -// ."" '< `.___\_<|>_/___.' _> \"". -// | | : `- \`. ;`. _/; .'/ / .' ; | -// \ \ `-. \_\_`. _.'_/_/ -' _.' / -// ================-.`___`-.__\ \___ /__.-'_.'_.-'================ -// `=--=-' -// 佛祖保佑 永无BUG 永不卡服 + private CustomCropsAPI customCropsAPI; @Override public void onLoad(){ plugin = this; - TimeZone timeZone = TimeZone.getDefault(); - String libRepo = timeZone.getID().startsWith("Asia") ? "https://maven.aliyun.com/repository/public/" : "https://repo.maven.apache.org/maven2/"; - LibraryLoader.load("dev.dejvokep","boosted-yaml","1.3",libRepo); - LibraryLoader.load("commons-io","commons-io","2.11.0",libRepo); - if (Bukkit.getPluginManager().getPlugin("WorldGuard") != null) { - WorldGuardHook.initialize(); - } + this.loadLibs(); } @Override public void onEnable() { - adventure = BukkitAudiences.create(plugin); + adventure = BukkitAudiences.create(this); protocolManager = ProtocolLibrary.getProtocolManager(); + AdventureUtils.consoleMessage("[CustomCrops] Running on " + Bukkit.getVersion()); + this.registerCommands(); + this.loadPlatform(); + + this.configManager = new ConfigManager(this); + this.messageManager = new MessageManager(this); this.versionHelper = new VersionHelper(this); - AdventureUtil.consoleMessage("[CustomCrops] Running on " + Bukkit.getVersion()); - VersionChecker.hideOk = true; - if (Bukkit.getPluginManager().getPlugin("ItemsAdder") != null) { - MainConfig.customPlugin = "itemsadder"; - AdventureUtil.consoleMessage("[CustomCrops] Custom Item Plugin Platform: <#BA55D3>ItemsAdder"); - } - else if (Bukkit.getPluginManager().getPlugin("Oraxen") != null) { - MainConfig.customPlugin = "oraxen"; - AdventureUtil.consoleMessage("[CustomCrops] Custom Item Plugin Platform: <#6495ED>Oraxen"); - } - else { - AdventureUtil.consoleMessage("[CustomCrops] You need either ItemsAdder or Oraxen as CustomCrops' dependency"); - Bukkit.getPluginManager().disablePlugin(CustomCrops.plugin); - return; + this.cropManager = new CropManager(this); + this.integrationManager = new IntegrationManager(this); + this.seasonManager = new SeasonManager(this); + this.worldDataManager = new WorldDataManager(this); + this.sprinklerManager = new SprinklerManager(this); + this.wateringCanManager = new WateringCanManager(this); + this.fertilizerManager = new FertilizerManager(this); + this.potManager = new PotManager(this); + this.platformManager = new PlatformManager(this); + this.customCropsAPI = new CustomCropsAPI(this); + + this.reload(); + + for (World world : Bukkit.getWorlds()) { + this.worldDataManager.loadWorld(world); } - ConfigUtil.reloadConfigs(); - this.registerQuests(); + AdventureUtils.consoleMessage("[CustomCrops] Plugin Enabled!"); + if (ConfigManager.enableBStats) new Metrics(this, 16593); + if (ConfigManager.checkUpdate) this.versionHelper.checkUpdate(); + } - PluginCommand pluginCommand = new PluginCommand(); - Objects.requireNonNull(Bukkit.getPluginCommand("customcrops")).setExecutor(pluginCommand); - Objects.requireNonNull(Bukkit.getPluginCommand("customcrops")).setTabCompleter(pluginCommand); + public void reload() { + this.configManager.unload(); + this.messageManager.unload(); + this.cropManager.unload(); + this.integrationManager.unload(); + this.worldDataManager.unload(); + this.sprinklerManager.unload(); + this.wateringCanManager.unload(); + this.fertilizerManager.unload(); + this.potManager.unload(); + this.seasonManager.unload(); + this.platformManager.unload(); - this.cropManager = new CropManager(); - - if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { - this.placeholderManager = new PlaceholderManager(); - } - - AdventureUtil.consoleMessage("[CustomCrops] Plugin Enabled!"); - - if (MainConfig.metrics) { - new Metrics(this, 16593); - } + this.configManager.load(); + this.messageManager.load(); + this.integrationManager.load(); + this.cropManager.load(); + this.worldDataManager.load(); + this.sprinklerManager.load(); + this.wateringCanManager.load(); + this.fertilizerManager.load(); + this.potManager.load(); + this.seasonManager.load(); + this.platformManager.load(); } @Override public void onDisable() { - if (adventure != null) { - adventure.close(); - } - if (this.placeholderManager != null) { - this.placeholderManager.unload(); - } - if (this.cropManager != null) { - this.cropManager.unload(); + if (adventure != null) adventure.close(); + if (this.cropManager != null) this.cropManager.unload(); + if (this.worldDataManager != null) this.worldDataManager.disable(); + if (this.seasonManager != null) this.seasonManager.unload(); + if (this.sprinklerManager != null) this.sprinklerManager.unload(); + if (this.wateringCanManager != null) this.wateringCanManager.unload(); + if (this.fertilizerManager != null) this.fertilizerManager.unload(); + if (this.platformManager != null) this.platformManager.unload(); + if (this.potManager != null) this.potManager.unload(); + if (this.messageManager != null) this.messageManager.unload(); + if (this.configManager != null) this.configManager.unload(); + if (this.integrationManager != null) this.integrationManager.unload(); + } + + private void loadLibs() { + TimeZone timeZone = TimeZone.getDefault(); + String libRepo = timeZone.getID().startsWith("Asia") ? "https://maven.aliyun.com/repository/public/" : "https://repo.maven.apache.org/maven2/"; + LibraryLoader.load("dev.dejvokep","boosted-yaml","1.3", libRepo); + LibraryLoader.load("commons-io","commons-io","2.11.0", libRepo); + LibraryLoader.load("net.objecthunter","exp4j","0.4.8", libRepo); + } + + private void registerCommands() { + CustomCropsCommand customCropsCommand = new CustomCropsCommand(); + PluginCommand pluginCommand = Bukkit.getPluginCommand("customcrops"); + if (pluginCommand != null) { + pluginCommand.setExecutor(customCropsCommand); + pluginCommand.setTabCompleter(customCropsCommand); } } - public PlaceholderManager getPlaceholderManager() { - return placeholderManager; + private void loadPlatform() { + PluginManager pluginManager = Bukkit.getPluginManager(); + if (pluginManager.isPluginEnabled("ItemsAdder")) { + this.platform = Platform.ItemsAdder; + this.platformInterface = new ItemsAdderPluginImpl(); + } + else if (pluginManager.isPluginEnabled("Oraxen")) { + this.platform = Platform.Oraxen; + this.platformInterface = new OraxenPluginImpl(); + } + if (this.platform == null) { + Bukkit.getPluginManager().disablePlugin(this); + AdventureUtils.consoleMessage("[CustomCrops] Please install ItemsAdder/Oraxen"); + } + else { + AdventureUtils.consoleMessage("[CustomCrops] Platform: " + platform.name()); + } } - public boolean hasPapi() { - return placeholderManager != null; + public static BukkitAudiences getAdventure() { + return adventure; + } + + public static CustomCrops getInstance() { + return plugin; + } + + public static ProtocolManager getProtocolManager() { + return protocolManager; } public CropManager getCropManager() { @@ -154,18 +208,55 @@ public final class CustomCrops extends JavaPlugin { return versionHelper; } - private void registerQuests() { - PluginManager pluginManager = Bukkit.getPluginManager(); - if (pluginManager.isPluginEnabled("ClueScrolls")) { - ClueScrollCCQuest quest = new ClueScrollCCQuest(); - Bukkit.getPluginManager().registerEvents(quest, plugin); - } - if (pluginManager.isPluginEnabled("BetonQuest")) { - if (Bukkit.getPluginManager().getPlugin("BetonQuest").getDescription().getVersion().startsWith("2")) NewBetonQuestCCQuest.register(); - else OldBetonQuestCCQuest.register(); - } - if (pluginManager.isPluginEnabled("BattlePass")) { - BattlePassCCQuest.register(); - } + public Platform getPlatform() { + return platform; + } + + public IntegrationManager getIntegrationManager() { + return integrationManager; + } + + public PlatformInterface getPlatformInterface() { + return platformInterface; + } + + public WorldDataManager getWorldDataManager() { + return worldDataManager; + } + + public SprinklerManager getSprinklerManager() { + return sprinklerManager; + } + + public PotManager getPotManager() { + return potManager; + } + + public WateringCanManager getWateringCanManager() { + return wateringCanManager; + } + + public FertilizerManager getFertilizerManager() { + return fertilizerManager; + } + + public SeasonManager getSeasonManager() { + return seasonManager; + } + + public ConfigManager getConfigManager() { + return configManager; + } + + public MessageManager getMessageManager() { + return messageManager; + } + + public PlatformManager getPlatformManager() { + return platformManager; + } + + public CustomCropsAPI getAPI() { + return customCropsAPI; } } diff --git a/src/main/java/net/momirealms/customcrops/api/CustomCropsAPI.java b/src/main/java/net/momirealms/customcrops/api/CustomCropsAPI.java new file mode 100644 index 0000000..d05e736 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/CustomCropsAPI.java @@ -0,0 +1,78 @@ +package net.momirealms.customcrops.api; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.customplugin.PlatformInterface; +import net.momirealms.customcrops.api.object.crop.CropConfig; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.season.CCSeason; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.Location; +import org.bukkit.inventory.ItemStack; + +public class CustomCropsAPI { + + private static CustomCropsAPI instance; + private final CustomCrops plugin; + + public CustomCropsAPI(CustomCrops plugin) { + this.plugin = plugin; + instance = this; + } + + public static CustomCropsAPI getInstance() { + return instance; + } + + public boolean isCrop(String stage_id) { + return plugin.getCropManager().getCropConfigByStage(stage_id) != null; + } + + public CropConfig getCropConfig(String crop_config_id) { + return plugin.getCropManager().getCropConfigByID(crop_config_id); + } + + public ItemStack buildItem(String id) { + return plugin.getIntegrationManager().build(id); + } + + public boolean removeCustomItem(Location location, ItemMode itemMode) { + if (itemMode == ItemMode.TRIPWIRE || itemMode == ItemMode.CHORUS) + return plugin.getPlatformInterface().removeCustomBlock(location); + else if (itemMode == ItemMode.ITEM_FRAME) + return plugin.getPlatformInterface().removeItemFrame(location); + else if (itemMode == ItemMode.ITEM_DISPLAY) + return plugin.getPlatformInterface().removeItemDisplay(location); + return false; + } + + public void placeCustomItem(Location location, String id, ItemMode itemMode) { + if (itemMode == ItemMode.TRIPWIRE) + plugin.getPlatformInterface().placeTripWire(location, id); + else if (itemMode == ItemMode.ITEM_FRAME) + plugin.getPlatformInterface().placeItemFrame(location, id); + else if (itemMode == ItemMode.ITEM_DISPLAY) + plugin.getPlatformInterface().placeItemDisplay(location, id); + else if (itemMode == ItemMode.CHORUS) + plugin.getPlatformInterface().placeChorus(location, id); + } + + public void changePotModel(SimpleLocation simpleLocation, Pot pot) { + Location location = simpleLocation.getBukkitLocation(); + if (location == null) return; + PlatformInterface platform = plugin.getPlatformInterface(); + if (platform.removeCustomBlock(location)) { + platform.placeNoteBlock(location, pot.isWet() ? pot.getConfig().getWetPot(pot.getFertilizer()) : pot.getConfig().getDryPot(pot.getFertilizer())); + } else { + CustomCrops.getInstance().getWorldDataManager().removePotData(simpleLocation); + } + } + + public boolean isGreenhouse(SimpleLocation simpleLocation) { + return plugin.getWorldDataManager().isGreenhouse(simpleLocation); + } + + public CCSeason getCurrentSeason(String world) { + return plugin.getIntegrationManager().getSeasonInterface().getSeason(world); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/crop/Crop.java b/src/main/java/net/momirealms/customcrops/api/crop/Crop.java deleted file mode 100644 index 7a70737..0000000 --- a/src/main/java/net/momirealms/customcrops/api/crop/Crop.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.api.crop; - -import net.momirealms.customcrops.api.utils.CCSeason; -import net.momirealms.customcrops.objects.GiganticCrop; -import net.momirealms.customcrops.objects.OtherLoot; -import net.momirealms.customcrops.objects.QualityLoot; -import net.momirealms.customcrops.objects.actions.ActionInterface; -import net.momirealms.customcrops.objects.requirements.RequirementInterface; - -public interface Crop { - - CCSeason[] getSeasons(); - - RequirementInterface[] getPlantRequirements(); - - RequirementInterface[] getHarvestRequirements(); - - String getReturnStage(); - - QualityLoot getQualityLoot(); - - GiganticCrop getGiganticCrop(); - - OtherLoot[] getOtherLoots(); - - ActionInterface[] getActions(); - - String getKey(); - - boolean canRotate(); - - int getMax_stage(); -} diff --git a/src/main/java/net/momirealms/customcrops/api/customplugin/Handler.java b/src/main/java/net/momirealms/customcrops/api/customplugin/Handler.java new file mode 100644 index 0000000..83dbc76 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/customplugin/Handler.java @@ -0,0 +1,33 @@ +package net.momirealms.customcrops.api.customplugin; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; + +public abstract class Handler extends Function implements Listener { + + protected PlatformManager platformManager; + + public Handler(PlatformManager platformManager) { + this.platformManager = platformManager; + } + + @Override + public void load() { + Bukkit.getPluginManager().registerEvents(this, CustomCrops.getInstance()); + } + + @Override + public void unload() { + HandlerList.unregisterAll(this); + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + platformManager.onInteractBlock(event); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/customplugin/Platform.java b/src/main/java/net/momirealms/customcrops/api/customplugin/Platform.java new file mode 100644 index 0000000..44b3fe9 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/customplugin/Platform.java @@ -0,0 +1,6 @@ +package net.momirealms.customcrops.api.customplugin; + +public enum Platform { + ItemsAdder, + Oraxen +} diff --git a/src/main/java/net/momirealms/customcrops/api/customplugin/PlatformInterface.java b/src/main/java/net/momirealms/customcrops/api/customplugin/PlatformInterface.java new file mode 100644 index 0000000..4c4541a --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/customplugin/PlatformInterface.java @@ -0,0 +1,96 @@ +package net.momirealms.customcrops.api.customplugin; + +import net.momirealms.customcrops.CustomCrops; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.ItemDisplay; +import org.bukkit.entity.ItemFrame; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; + +public interface PlatformInterface { + + boolean removeCustomBlock(Location location); + + @Nullable + String getCustomBlockID(Location location); + + @Nullable + ItemStack getItemStack(String id); + + @Nullable + ItemFrame placeItemFrame(Location location, String id); + + @Nullable + ItemDisplay placeItemDisplay(Location location, String id); + + void placeNoteBlock(Location location, String id); + + void placeTripWire(Location location, String id); + + @NotNull + String getBlockID(Block block); + + boolean doesItemExist(String id); + + void dropBlockLoot(Block block); + + boolean removeItemDisplay(Location location); + + void placeChorus(Location location, String id); + + Location getItemFrameLocation(Location location); + + @Nullable + String getCustomItemAt(Location location); + + default void removeCustomItemAt(Location location) { + removeCustomBlock(location); + removeItemFrame(location); + } + + @NotNull + String getItemID(@NotNull ItemStack itemStack); + + @Nullable + default ItemFrame getItemFrameAt(Location location) { + Collection itemFrames = getItemFrameLocation(location).getNearbyEntitiesByType(ItemFrame.class, 0, 0, 0); + int i = itemFrames.size(); + int j = 1; + for (ItemFrame itemFrame : itemFrames) { + if (j != i) { + // To prevent item frames stack in one block + itemFrame.remove(); + j++; + } + else return itemFrame; + } + return null; + } + + default boolean removeItemFrame(Location location) { + ItemFrame itemFrame = getItemFrameAt(location); + if (itemFrame != null) { + itemFrame.remove(); + return true; + } + return false; + } + + default boolean detectAnyThing(Location location) { + Block block = location.getBlock(); + if (block.getType() != Material.AIR) return true; + Collection entities = location.clone().add(0.5,0.5,0.5).getNearbyEntitiesByType(ItemFrame.class, 0.5, 0.5, 0.5); + return entities.size() != 0 || (CustomCrops.getInstance().getVersionHelper().isVersionNewerThan1_19_R3() && detectItemDisplay(location)); + } + + default boolean detectItemDisplay(Location location) { + Collection entities = location.clone().add(0.5,0.5,0.5).getNearbyEntitiesByType(ItemDisplay.class, 0.5, 0.5, 0.5); + return entities.size() != 0; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/customplugin/PlatformManager.java b/src/main/java/net/momirealms/customcrops/api/customplugin/PlatformManager.java new file mode 100644 index 0000000..d999933 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/customplugin/PlatformManager.java @@ -0,0 +1,709 @@ +package net.momirealms.customcrops.api.customplugin; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.CustomCropsAPI; +import net.momirealms.customcrops.api.customplugin.itemsadder.ItemsAdderHandler; +import net.momirealms.customcrops.api.customplugin.oraxen.OraxenHandler; +import net.momirealms.customcrops.api.object.BoneMeal; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.object.InteractWithItem; +import net.momirealms.customcrops.api.object.ItemType; +import net.momirealms.customcrops.api.object.fill.PassiveFillMethod; +import net.momirealms.customcrops.api.object.action.Action; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.basic.MessageManager; +import net.momirealms.customcrops.api.object.crop.CropConfig; +import net.momirealms.customcrops.api.object.crop.GrowingCrop; +import net.momirealms.customcrops.api.object.crop.StageConfig; +import net.momirealms.customcrops.api.object.fertilizer.Fertilizer; +import net.momirealms.customcrops.api.object.fertilizer.FertilizerConfig; +import net.momirealms.customcrops.api.object.fill.PositiveFillMethod; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.pot.PotConfig; +import net.momirealms.customcrops.api.object.requirement.CurrentState; +import net.momirealms.customcrops.api.object.requirement.Requirement; +import net.momirealms.customcrops.api.object.sprinkler.SprinklerConfig; +import net.momirealms.customcrops.api.object.wateringcan.WateringCanConfig; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import net.momirealms.customcrops.api.util.AdventureUtils; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Objects; + +public class PlatformManager extends Function { + + private final CustomCrops plugin; + private final Handler handler; + + public PlatformManager(CustomCrops plugin) { + this.plugin = plugin; + this.handler = switch (plugin.getPlatform()) { + case ItemsAdder -> new ItemsAdderHandler(this); + case Oraxen -> new OraxenHandler(this); + }; + } + + @Override + public void load() { + this.handler.load(); + } + + @Override + public void unload() { + this.handler.unload(); + } + + public void onBreakTripWire(Player player, Block block, String id, Cancellable event) { + if (event.isCancelled()) return; + onBreakSomething(player, block.getLocation(), id, event); + } + + public void onBreakNoteBlock(Player player, Block block, String id, Cancellable event) { + if (event.isCancelled()) return; + onBreakSomething(player, block.getLocation(), id, event); + } + + public void onBreakItemDisplay(Player player, Entity entity, String id, Cancellable event) { + if (event.isCancelled()) return; + onBreakSomething(player, entity.getLocation().getBlock().getLocation(), id, event); + } + + public void onBreakItemFrame(Player player, Entity entity, String id, Cancellable event) { + if (event.isCancelled()) return; + onBreakSomething(player, entity.getLocation().getBlock().getLocation(), id, event); + } + + public void onPlaceFurniture(Location location, String id) { + onPlaceSomething(location, id); + } + + public void onPlaceBlock(Location location, String id, Cancellable event) { + if (event.isCancelled()) return; + onPlaceSomething(location, id); + } + + public void onInteractBlock(PlayerInteractEvent event) { + if (event.getHand() != EquipmentSlot.HAND) return; + if (event.getAction() == org.bukkit.event.block.Action.RIGHT_CLICK_AIR) { + onInteractAir(event.getPlayer()); + } else if (event.getAction() == org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK) { + Block block = event.getClickedBlock(); + String id = plugin.getPlatformInterface().getBlockID(block); + assert block != null; + onInteractSomething(event.getPlayer(), block.getLocation(), id, event); + } + } + + public void onInteractFurniture(Player player, Entity entity, String id, Cancellable event) { + if (event.isCancelled()) return; + onInteractSomething(player, entity.getLocation().getBlock().getLocation(), id, event); + } + + @NotNull + public ItemType onInteractAir(Player player) { + ItemStack item_in_hand = player.getInventory().getItemInMainHand(); + String id = plugin.getPlatformInterface().getItemID(item_in_hand); + + if (onInteractWithWateringCan(player, id, item_in_hand)) { + return ItemType.WATERINGCAN; + } + + return ItemType.UNKNOWN; + } + + @NotNull + public ItemType onBreakSomething(Player player, Location location, String id, Cancellable event) { + + if (onBreakGlass(id, location)) { + return ItemType.GLASS; + } + + if (onBreakPot(player, id, location, event)) { + return ItemType.POT; + } + + if (onBreakCrop(player, id, location, event)) { + return ItemType.CROP; + } + + if (onBreakSprinkler(id, location)) { + return ItemType.SPRINKLER; + } + + if (onBreakScarecrow(id, location)) { + return ItemType.SCARECROW; + } + + return ItemType.UNKNOWN; + } + + @NotNull + public ItemType onPlaceSomething(Location location, String id) { + + if (onPlaceGlass(id, location)) { + return ItemType.GLASS; + } + + if (onPlacePot(id, location)) { + return ItemType.POT; + } + + if (onPlaceScarecrow(id, location)) { + return ItemType.SCARECROW; + } + + return ItemType.UNKNOWN; + } + + @NotNull ItemType onInteractSomething(Player player, Location location, String id, Cancellable event) { + + ItemStack item_in_hand = player.getInventory().getItemInMainHand(); + String item_in_hand_id = plugin.getPlatformInterface().getItemID(item_in_hand); + + if (onInteractWithSprinkler(player, location, item_in_hand, item_in_hand_id)) { + return ItemType.SPRINKLER; + } + + if (onInteractSprinkler(player, id, location, item_in_hand, item_in_hand_id)) { + return ItemType.SPRINKLER; + } + + if (onInteractPot(player, id, location, item_in_hand, item_in_hand_id)) { + return ItemType.POT; + } + + if (onInteractCrop(player, id, location, item_in_hand, item_in_hand_id)) { + return ItemType.CROP; + } + + if (onInteractWithWateringCan(player, item_in_hand_id, item_in_hand)) { + return ItemType.WATERINGCAN; + } + + return ItemType.UNKNOWN; + } + + public boolean onBreakGlass(String id, Location location) { + if (!id.equals(ConfigManager.greenhouseBlock)) { + return false; + } + + plugin.getWorldDataManager().removeGreenhouse(SimpleLocation.getByBukkitLocation(location)); + return true; + } + + public boolean onPlaceGlass(String id, Location location) { + if (!id.equals(ConfigManager.greenhouseBlock)) { + return false; + } + + plugin.getWorldDataManager().addGreenhouse(SimpleLocation.getByBukkitLocation(location)); + return true; + } + + public boolean onBreakScarecrow(String id, Location location) { + if (!id.equals(ConfigManager.scarecrow)) { + return false; + } + + plugin.getWorldDataManager().removeScarecrow(SimpleLocation.getByBukkitLocation(location)); + return true; + } + + public boolean onPlaceScarecrow(String id, Location location) { + if (!id.equals(ConfigManager.scarecrow)) { + return false; + } + + plugin.getWorldDataManager().addScarecrow(SimpleLocation.getByBukkitLocation(location)); + return true; + } + + private boolean onPlacePot(String id, Location location) { + String pot_id = plugin.getPotManager().getPotKeyByBlockID(id); + if (pot_id == null) return false; + + plugin.getWorldDataManager().addPotData(SimpleLocation.getByBukkitLocation(location), new Pot(pot_id, null, 0)); + return true; + } + + public boolean onInteractSprinkler(Player player, String id, Location location, ItemStack item_in_hand, String item_in_hand_id) { + SprinklerConfig sprinklerConfig = plugin.getSprinklerManager().getConfigByItemID(id); + if (sprinklerConfig == null) { + return false; + } + + // water + PassiveFillMethod[] passiveFillMethods = sprinklerConfig.getPassiveFillMethods(); + for (PassiveFillMethod passiveFillMethod : passiveFillMethods) { + if (passiveFillMethod.isRightItem(item_in_hand_id)) { + doPassiveFillAction(player, item_in_hand, passiveFillMethod, location.clone().add(0,0.2,0)); + plugin.getWorldDataManager().addWaterToSprinkler(SimpleLocation.getByBukkitLocation(location), passiveFillMethod.getAmount(), sprinklerConfig.getRange(), sprinklerConfig.getStorage()); + return true; + } + } + + WateringCanConfig wateringCanConfig = plugin.getWateringCanManager().getConfigByItemID(item_in_hand_id); + if (wateringCanConfig != null) { + String[] sprinkler_whitelist = wateringCanConfig.getSprinklerWhitelist(); + if (sprinkler_whitelist != null) { + outer: { + for (String sprinkler_allowed : sprinkler_whitelist) { + if (sprinkler_allowed.equals(plugin.getSprinklerManager().getConfigKeyByItemID(id))) { + break outer; + } + } + return true; + } + } + int current_water = plugin.getWateringCanManager().getCurrentWater(item_in_hand); + if (current_water <= 0) return true; + + //TODO API Events + + current_water--; + if (wateringCanConfig.hasActionBar()) { + AdventureUtils.playerActionbar(player, wateringCanConfig.getActionBarMsg(current_water)); + } + if (wateringCanConfig.getSound() != null) { + AdventureUtils.playerSound(player, wateringCanConfig.getSound()); + } + if (wateringCanConfig.getParticle() != null) { + location.getWorld().spawnParticle(wateringCanConfig.getParticle(), location.clone().add(0.5,0.4, 0.5),5,0.3,0.1,0.3); + } + + plugin.getWateringCanManager().setWater(item_in_hand, current_water, wateringCanConfig); + plugin.getWorldDataManager().addWaterToSprinkler(SimpleLocation.getByBukkitLocation(location), 1, sprinklerConfig.getRange(), sprinklerConfig.getStorage()); + return true; + } + + return true; + } + + private void doPassiveFillAction(Player player, ItemStack item_in_hand, PassiveFillMethod passiveFillMethod, Location location) { + if (player.getGameMode() != GameMode.CREATIVE) { + item_in_hand.setAmount(item_in_hand.getAmount() - 1); + ItemStack returned = passiveFillMethod.getReturnedItemStack(); + if (returned != null) { + player.getInventory().addItem(returned); + } + } + if (passiveFillMethod.getSound() != null) { + AdventureUtils.playerSound(player, passiveFillMethod.getSound()); + } + if (passiveFillMethod.getParticle() != null) { + location.getWorld().spawnParticle(passiveFillMethod.getParticle(), location.clone().add(0.5,0.4, 0.5),5,0.3,0.1,0.3); + } + } + + public boolean onInteractWithSprinkler(Player player, Location location, ItemStack item_in_hand, String item_in_hand_id) { + SprinklerConfig sprinklerConfig = plugin.getSprinklerManager().getConfigByItemID(item_in_hand_id); + if (sprinklerConfig == null) { + return false; + } + + Location sprinkler_loc = location.clone().add(0,1,0); + if (plugin.getPlatformInterface().detectAnyThing(sprinkler_loc)) return true; + + if (player.getGameMode() != GameMode.CREATIVE) item_in_hand.setAmount(item_in_hand.getAmount() - 1); + CustomCropsAPI.getInstance().placeCustomItem(sprinkler_loc, sprinklerConfig.getThreeD(), sprinklerConfig.getItemMode()); + if (sprinklerConfig.getSound() != null) { + AdventureUtils.playerSound(player, sprinklerConfig.getSound()); + } + return true; + } + + public boolean onInteractCrop(Player player, String id, Location location, ItemStack item_in_hand, String item_in_hand_id) { + CropConfig cropConfig = plugin.getCropManager().getCropConfigByStage(id); + if (cropConfig == null) { + return false; + } + + StageConfig stageConfig = plugin.getCropManager().getStageConfig(id); + if (stageConfig == null) { + return true; + } + + if (item_in_hand_id.equals("AIR")) { + Action[] actions = stageConfig.getInteractByHandActions(); + if (actions != null) { + for (Action action : actions) { + action.doOn(player, SimpleLocation.getByBukkitLocation(location), cropConfig.getCropMode()); + } + } + return true; + } + + WateringCanConfig wateringCanConfig = plugin.getWateringCanManager().getConfigByItemID(item_in_hand_id); + Pot potData = plugin.getWorldDataManager().getPotData(SimpleLocation.getByBukkitLocation(location).add(0,-1,0)); + if (wateringCanConfig != null && potData != null) { + String[] pot_whitelist = wateringCanConfig.getPotWhitelist(); + if (pot_whitelist != null) { + outer: { + for (String pot : pot_whitelist) { + if (pot.equals(potData.getPotKey())) { + break outer; + } + } + return true; + } + } + int current_water = plugin.getWateringCanManager().getCurrentWater(item_in_hand); + if (current_water <= 0) return true; + + //TODO API Events + + current_water--; + this.waterPot(wateringCanConfig.getWidth(), wateringCanConfig.getLength(), location.clone().subtract(0,1,0), player.getLocation().getYaw(), potData.getPotKey(), wateringCanConfig.getParticle()); + if (wateringCanConfig.hasActionBar()) { + AdventureUtils.playerActionbar(player, wateringCanConfig.getActionBarMsg(current_water)); + } + if (wateringCanConfig.getSound() != null) { + AdventureUtils.playerSound(player, wateringCanConfig.getSound()); + } + plugin.getWateringCanManager().setWater(item_in_hand, current_water, wateringCanConfig); + return true; + } + + BoneMeal[] boneMeals = cropConfig.getBoneMeals(); + if (boneMeals != null) { + for (BoneMeal boneMeal : boneMeals) { + if (boneMeal.isRightItem(item_in_hand_id)) { + if (plugin.getWorldDataManager().addCropPointAt(SimpleLocation.getByBukkitLocation(location), boneMeal.getPoint())) { + if (player.getGameMode() != GameMode.CREATIVE) { + item_in_hand.setAmount(item_in_hand.getAmount() - 1); + if (boneMeal.getReturned() != null) { + player.getInventory().addItem(boneMeal.getReturned()); + } + } + if (boneMeal.getParticle() != null) { + location.getWorld().spawnParticle(boneMeal.getParticle(), location.clone().add(0.5,0.5, 0.5),3,0.4,0.4,0.4); + } + if (boneMeal.getSound() != null) { + AdventureUtils.playerSound(player, boneMeal.getSound()); + } + } + return true; + } + } + } + + InteractWithItem[] interactActions = stageConfig.getInteractActions(); + if (interactActions != null) { + for (InteractWithItem interactWithItem : interactActions) { + if (interactWithItem.isRightItem(item_in_hand_id)) { + if (player.getGameMode() != GameMode.CREATIVE) { + if (interactWithItem.isConsumed()) { + item_in_hand.setAmount(item_in_hand.getAmount() - 1); + } + if (interactWithItem.getReturned() != null) { + player.getInventory().addItem(interactWithItem.getReturned()); + } + } + Action[] inAc = interactWithItem.getActions(); + if (inAc != null) { + for (Action action : inAc) { + action.doOn(player, SimpleLocation.getByBukkitLocation(location), cropConfig.getCropMode()); + } + } + return true; + } + } + } + return true; + } + + public boolean onInteractPot(Player player, String id, Location location, ItemStack item_in_hand, String item_in_hand_id) { + String pot_id = plugin.getPotManager().getPotKeyByBlockID(id); + if (pot_id == null) { + return false; + } + + PotConfig potConfig = plugin.getPotManager().getPotConfig(pot_id); + if (potConfig == null) { + return false; + } + + // water + PassiveFillMethod[] passiveFillMethods = potConfig.getPassiveFillMethods(); + for (PassiveFillMethod passiveFillMethod : passiveFillMethods) { + if (passiveFillMethod.isRightItem(item_in_hand_id)) { + doPassiveFillAction(player, item_in_hand, passiveFillMethod, location); + plugin.getWorldDataManager().addWaterToPot(SimpleLocation.getByBukkitLocation(location), passiveFillMethod.getAmount(), pot_id); + return true; + } + } + + CropConfig cropConfig = plugin.getCropManager().getCropConfigBySeed(item_in_hand_id); + if (cropConfig != null) { + String[] pot_whitelist = cropConfig.getBottom_blocks(); + outer: { + for (String bottom_block : pot_whitelist) { + if (bottom_block.equals(pot_id)) { + break outer; + } + } + AdventureUtils.playerMessage(player, MessageManager.prefix + MessageManager.unsuitablePot); + return true; + } + + Location crop_loc = location.clone().add(0,1,0); + Requirement[] requirements = cropConfig.getPlantRequirements(); + if (requirements != null) { + CurrentState currentState = new CurrentState(crop_loc, player); + for (Requirement requirement : requirements) { + if (!requirement.isConditionMet(currentState)) { + return true; + } + } + } + + if (plugin.getPlatformInterface().detectAnyThing(crop_loc)) return true; + if (ConfigManager.enableLimitation && plugin.getWorldDataManager().getChunkCropAmount(SimpleLocation.getByBukkitLocation(crop_loc)) >= ConfigManager.maxCropPerChunk) { + AdventureUtils.playerMessage(player, MessageManager.prefix + MessageManager.reachChunkLimit); + return true; + } + + if (player.getGameMode() != GameMode.CREATIVE) item_in_hand.setAmount(item_in_hand.getAmount() - 1); + player.swingMainHand(); + CustomCropsAPI.getInstance().placeCustomItem(crop_loc, Objects.requireNonNull(cropConfig.getStageConfig(0)).getModel(), cropConfig.getCropMode()); + plugin.getWorldDataManager().addCropData(SimpleLocation.getByBukkitLocation(crop_loc), new GrowingCrop(cropConfig.getKey(), 0)); + return true; + } + + // use fertilizer + FertilizerConfig fertilizerConfig = plugin.getFertilizerManager().getConfigByItemID(item_in_hand_id); + if (fertilizerConfig != null) { + if (fertilizerConfig.isBeforePlant() && plugin.getCropManager().containsStage(plugin.getPlatformInterface().getCustomItemAt(location.clone().add(0,1,0)))) { + AdventureUtils.playerMessage(player, MessageManager.prefix + MessageManager.beforePlant); + return true; + } + if (player.getGameMode() != GameMode.CREATIVE) item_in_hand.setAmount(item_in_hand.getAmount() - 1); + player.swingMainHand(); + if (fertilizerConfig.getSound() != null) { + AdventureUtils.playerSound(player, fertilizerConfig.getSound()); + } + if (fertilizerConfig.getParticle() != null) { + location.getWorld().spawnParticle(fertilizerConfig.getParticle(), location.clone().add(0.5,1.1,0.5), 5,0.25,0.1,0.25, 0); + } + plugin.getWorldDataManager().addFertilizerToPot(SimpleLocation.getByBukkitLocation(location), new Fertilizer(fertilizerConfig), pot_id); + return true; + } + + // use watering can + WateringCanConfig wateringCanConfig = plugin.getWateringCanManager().getConfigByItemID(item_in_hand_id); + if (wateringCanConfig != null) { + String[] pot_whitelist = wateringCanConfig.getPotWhitelist(); + if (pot_whitelist != null) { + outer: { + for (String pot : pot_whitelist) { + if (pot.equals(pot_id)) { + break outer; + } + } + return true; + } + } + + int current_water = plugin.getWateringCanManager().getCurrentWater(item_in_hand); + if (current_water <= 0) return true; + + //TODO API Events + + current_water--; + this.waterPot(wateringCanConfig.getWidth(), wateringCanConfig.getLength(), location, player.getLocation().getYaw(), pot_id, wateringCanConfig.getParticle()); + + if (wateringCanConfig.hasActionBar()) { + AdventureUtils.playerActionbar(player, wateringCanConfig.getActionBarMsg(current_water)); + } + if (wateringCanConfig.getSound() != null) { + AdventureUtils.playerSound(player, wateringCanConfig.getSound()); + } + + plugin.getWateringCanManager().setWater(item_in_hand, current_water, wateringCanConfig); + return true; + } + return true; + } + + public boolean onBreakPot(Player player, String id, Location location, Cancellable event) { + if (!plugin.getPotManager().containsPotBlock(id)) { + return false; + } + + Location above_loc = location.clone().add(0,1,0); + String above_id = plugin.getPlatformInterface().getCustomItemAt(above_loc); + // has item above + if (above_id != null) { + // is a crop + if (onBreakCrop(player, above_id, above_loc, event)) { + // The event might be cancelled if the player doesn't meet the break requirements + if (event.isCancelled()) { + return true; + } + plugin.getPlatformInterface().removeCustomItemAt(above_loc); + } + } + + plugin.getWorldDataManager().removePotData(SimpleLocation.getByBukkitLocation(location)); + return true; + } + + private boolean onBreakSprinkler(String id, Location location) { + if (!plugin.getSprinklerManager().containsSprinkler(id)) { + return false; + } + + plugin.getWorldDataManager().removeSprinklerData(SimpleLocation.getByBukkitLocation(location)); + return true; + } + + private boolean onBreakCrop(Player player, String id, Location location, Cancellable event) { + if (plugin.getCropManager().isDeadCrop(id)) { + return true; + } + + CropConfig cropConfig = plugin.getCropManager().getCropConfigByStage(id); + if (cropConfig == null) return false; + + if (!canBreak(player, cropConfig, location)) { + event.setCancelled(true); + return true; + } + + if (player.getGameMode() != GameMode.CREATIVE) { + StageConfig stageConfig = plugin.getCropManager().getStageConfig(id); + if (stageConfig != null) { + Action[] breakActions = stageConfig.getBreakActions(); + if (breakActions != null) { + for (Action action : breakActions) { + action.doOn(player, SimpleLocation.getByBukkitLocation(location), cropConfig.getCropMode()); + } + } + } + } + + plugin.getWorldDataManager().removeCropData(SimpleLocation.getByBukkitLocation(location)); + return true; + } + + public boolean canBreak(Player player, CropConfig cropConfig, Location crop_loc) { + Requirement[] requirements = cropConfig.getBreakRequirements(); + if (requirements == null) return true; + CurrentState currentState = new CurrentState(crop_loc, player); + for (Requirement requirement : requirements) { + if (!requirement.isConditionMet(currentState)) { + return false; + } + } + return true; + } + + private void waterPot(int width, int length, Location location, float yaw, String id, @Nullable Particle particle){ + int extend = width / 2; + if (yaw < 45 && yaw > -135) { + if (yaw > -45) { + for (int i = -extend; i <= extend; i++) { + Location tempLoc = location.clone().add(i, 0, -1); + for (int j = 0; j < length; j++){ + tempLoc.add(0,0,1); + tryToWaterPot(tempLoc, id, particle); + } + } + } + else { + for (int i = -extend; i <= extend; i++) { + Location tempLoc = location.clone().add(-1, 0, i); + for (int j = 0; j < length; j++){ + tempLoc.add(1,0,0); + tryToWaterPot(tempLoc, id, particle); + } + } + } + } + else { + if (yaw > 45 && yaw < 135) { + for (int i = -extend; i <= extend; i++) { + Location tempLoc = location.clone().add(1, 0, i); + for (int j = 0; j < length; j++){ + tempLoc.subtract(1,0,0); + tryToWaterPot(tempLoc, id, particle); + } + } + } + else { + for (int i = -extend; i <= extend; i++) { + Location tempLoc = location.clone().add(i, 0, 1); + for (int j = 0; j < length; j++){ + tempLoc.subtract(0,0,1); + tryToWaterPot(tempLoc, id, particle); + } + } + } + } + } + + private void tryToWaterPot(Location location, String pot_id, @Nullable Particle particle) { + String blockID = plugin.getPlatformInterface().getBlockID(location.getBlock()); + String current_id = plugin.getPotManager().getPotKeyByBlockID(blockID); + if (current_id != null && current_id.equals(pot_id)) { + plugin.getWorldDataManager().addWaterToPot(SimpleLocation.getByBukkitLocation(location), 1, pot_id); + if (particle != null) + location.getWorld().spawnParticle(particle, location.clone().add(0.5,1, 0.5),3,0.1,0.1,0.1); + } + } + + public boolean onInteractWithWateringCan(Player player, String item_in_hand_id, ItemStack item_in_hand) { + WateringCanConfig wateringCanConfig = plugin.getWateringCanManager().getConfigByItemID(item_in_hand_id); + if (wateringCanConfig == null) { + return false; + } + + int current = plugin.getWateringCanManager().getCurrentWater(item_in_hand); + if (current >= wateringCanConfig.getStorage()) return true; + List lineOfSight = player.getLineOfSight(null, 5); + List blockIds = lineOfSight.stream().map(block -> plugin.getPlatformInterface().getBlockID(block)).toList(); + + int add = 0; + for (PositiveFillMethod positiveFillMethod : wateringCanConfig.getPositiveFillMethods()) { + if (positiveFillMethod.getType() == PositiveFillMethod.InteractType.BLOCK) { + int index = 0; + for (String blockId : blockIds) { + if (positiveFillMethod.getId().equals(blockId)) { + add = positiveFillMethod.getAmount(); + if (positiveFillMethod.getSound() != null) { + AdventureUtils.playerSound(player, positiveFillMethod.getSound()); + } + if (positiveFillMethod.getParticle() != null) { + Block block = lineOfSight.get(index); + block.getWorld().spawnParticle(positiveFillMethod.getParticle(), block.getLocation().add(0.5,1, 0.5),5,0.1,0.1,0.1); + } + break; + } + index++; + } + } + } + + if (add == 0) return true; + int finalWater = Math.min(wateringCanConfig.getStorage(), add + current); + plugin.getWateringCanManager().setWater(item_in_hand, finalWater, wateringCanConfig); + if (wateringCanConfig.hasActionBar()) { + AdventureUtils.playerActionbar(player, wateringCanConfig.getActionBarMsg(finalWater)); + } + return true; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/customplugin/itemsadder/ItemsAdderHandler.java b/src/main/java/net/momirealms/customcrops/api/customplugin/itemsadder/ItemsAdderHandler.java new file mode 100644 index 0000000..98f22ba --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/customplugin/itemsadder/ItemsAdderHandler.java @@ -0,0 +1,48 @@ +package net.momirealms.customcrops.api.customplugin.itemsadder; + +import dev.lone.itemsadder.api.Events.*; +import net.momirealms.customcrops.api.customplugin.Handler; +import net.momirealms.customcrops.api.customplugin.PlatformManager; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.event.EventHandler; + +public class ItemsAdderHandler extends Handler { + + public ItemsAdderHandler(PlatformManager platformManager) { + super(platformManager); + } + + @EventHandler + public void onBreakCustomBlock(CustomBlockBreakEvent event) { + Block block = event.getBlock(); + switch (block.getType()) { + case NOTE_BLOCK -> platformManager.onBreakNoteBlock(event.getPlayer(), event.getBlock(), event.getNamespacedID(), event); + case TRIPWIRE -> platformManager.onBreakTripWire(event.getPlayer(), event.getBlock(), event.getNamespacedID(), event); + } + } + + @EventHandler + public void onBreakFurniture(FurnitureBreakEvent event) { + Entity entity = event.getBukkitEntity(); + switch (entity.getType()) { + case ITEM_FRAME -> platformManager.onBreakItemFrame(event.getPlayer(), entity, event.getNamespacedID(), event); + case ITEM_DISPLAY -> platformManager.onBreakItemDisplay(event.getPlayer(), entity, event.getNamespacedID(), event); + } + } + + @EventHandler + public void onPlaceFurniture(FurniturePlaceSuccessEvent event) { + platformManager.onPlaceFurniture(event.getBukkitEntity().getLocation().getBlock().getLocation(), event.getNamespacedID()); + } + + @EventHandler + public void onPlaceCustomBlock(CustomBlockPlaceEvent event) { + platformManager.onPlaceBlock(event.getBlock().getLocation(), event.getNamespacedID(), event); + } + + @EventHandler + public void onInteractFurniture(FurnitureInteractEvent event) { + platformManager.onInteractFurniture(event.getPlayer(), event.getBukkitEntity(), event.getNamespacedID(), event); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/customplugin/itemsadder/ItemsAdderPluginImpl.java b/src/main/java/net/momirealms/customcrops/api/customplugin/itemsadder/ItemsAdderPluginImpl.java new file mode 100644 index 0000000..437e1b5 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/customplugin/itemsadder/ItemsAdderPluginImpl.java @@ -0,0 +1,134 @@ +package net.momirealms.customcrops.api.customplugin.itemsadder; + +import de.tr7zw.changeme.nbtapi.NBTCompound; +import de.tr7zw.changeme.nbtapi.NBTItem; +import dev.lone.itemsadder.api.CustomBlock; +import dev.lone.itemsadder.api.CustomFurniture; +import dev.lone.itemsadder.api.CustomStack; +import net.momirealms.customcrops.api.customplugin.PlatformInterface; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.ItemDisplay; +import org.bukkit.entity.ItemFrame; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ItemsAdderPluginImpl implements PlatformInterface { + + @Override + public boolean removeCustomBlock(Location location) { + return CustomBlock.remove(location); + } + + @Nullable + @Override + public String getCustomBlockID(Location location) { + CustomBlock customBlock = CustomBlock.byAlreadyPlaced(location.getBlock()); + return customBlock == null ? null : customBlock.getNamespacedID(); + } + + @Nullable + @Override + public ItemStack getItemStack(String id) { + CustomStack customStack = CustomStack.getInstance(id); + return customStack == null ? null : customStack.getItemStack(); + } + + @Nullable + @Override + public ItemFrame placeItemFrame(Location location, String id) { + CustomFurniture customFurniture = CustomFurniture.spawn(id, location.getBlock()); + Entity entity = customFurniture.getArmorstand(); + if (entity instanceof ItemFrame itemFrame) + return itemFrame; + else { + customFurniture.remove(false); + } + return null; + } + + @Nullable + @Override + public ItemDisplay placeItemDisplay(Location location, String id) { + //TODO Not implemented + return null; + } + + @Override + public void placeNoteBlock(Location location, String id) { + CustomBlock.place(id, location); + } + + @Override + public void placeTripWire(Location location, String id) { + CustomBlock.place(id, location); + } + + @NotNull + @Override + public String getBlockID(Block block) { + CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); + return customBlock == null ? block.getType().name() : customBlock.getNamespacedID(); + } + + @Override + public boolean doesItemExist(String id) { + return CustomStack.getInstance(id) != null; + } + + @Override + public void dropBlockLoot(Block block) { + CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block); + if (customBlock == null) return; + Location block_loc = block.getLocation(); + for (ItemStack itemStack : customBlock.getLoot()) { + block_loc.getWorld().dropItemNaturally(block_loc, itemStack); + } + } + + @Override + public boolean removeItemDisplay(Location location) { + //TODO Not implemented + return false; + } + + @Override + public void placeChorus(Location location, String id) { + CustomBlock.place(id, location); + } + + @Override + public Location getItemFrameLocation(Location location) { + return location.clone().add(0.5, 0.5, 0.5); + } + + @Nullable + @Override + public String getCustomItemAt(Location location) { + String block = getBlockID(location.getBlock()); + if (!block.equals("AIR")) return block; + + ItemFrame itemFrame = getItemFrameAt(location); + if (itemFrame != null) { + CustomFurniture customFurniture = CustomFurniture.byAlreadySpawned(itemFrame); + if (customFurniture != null) { + return customFurniture.getNamespacedID(); + } + } + return null; + } + + @NotNull + @Override + public String getItemID(@NotNull ItemStack itemStack) { + if (itemStack.getType() != Material.AIR) { + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound nbtCompound = nbtItem.getCompound("itemsadder"); + if (nbtCompound != null) return nbtCompound.getString("namespace") + ":" + nbtCompound.getString("id"); + } + return itemStack.getType().name(); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/customplugin/oraxen/OraxenHandler.java b/src/main/java/net/momirealms/customcrops/api/customplugin/oraxen/OraxenHandler.java new file mode 100644 index 0000000..28b2490 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/customplugin/oraxen/OraxenHandler.java @@ -0,0 +1,53 @@ +package net.momirealms.customcrops.api.customplugin.oraxen; + +import io.th0rgal.oraxen.api.events.*; +import net.momirealms.customcrops.api.customplugin.Handler; +import net.momirealms.customcrops.api.customplugin.PlatformManager; +import org.bukkit.entity.Entity; +import org.bukkit.event.EventHandler; + +public class OraxenHandler extends Handler { + + public OraxenHandler(PlatformManager platformManager) { + super(platformManager); + } + + @EventHandler + public void onBreakNoteBlock(OraxenNoteBlockBreakEvent event) { + platformManager.onBreakNoteBlock(event.getPlayer(), event.getBlock(), event.getMechanic().getItemID(), event); + } + + @EventHandler + public void onBreakStringBlock(OraxenStringBlockBreakEvent event) { + platformManager.onBreakTripWire(event.getPlayer(), event.getBlock(), event.getMechanic().getItemID(), event); + } + + @EventHandler + public void onBreakFurniture(OraxenFurnitureBreakEvent event) { + Entity entity = event.getBaseEntity(); + switch (entity.getType()) { + case ITEM_FRAME -> platformManager.onBreakItemFrame(event.getPlayer(), entity, event.getMechanic().getItemID(), event); + case ITEM_DISPLAY -> platformManager.onBreakItemDisplay(event.getPlayer(), entity, event.getMechanic().getItemID(), event); + } + } + + @EventHandler + public void onPlaceFurniture(OraxenFurniturePlaceEvent event) { + platformManager.onPlaceFurniture(event.getBaseEntity().getLocation().getBlock().getLocation(), event.getMechanic().getItemID()); + } + + @EventHandler + public void onPlaceStringBlock(OraxenStringBlockPlaceEvent event) { + platformManager.onPlaceBlock(event.getBlock().getLocation(), event.getMechanic().getItemID(), event); + } + + @EventHandler + public void onPlaceNoteBlock(OraxenNoteBlockPlaceEvent event) { + platformManager.onPlaceBlock(event.getBlock().getLocation(), event.getMechanic().getItemID(), event); + } + + @EventHandler + public void onInteractFurniture(OraxenFurnitureInteractEvent event) { + platformManager.onInteractFurniture(event.getPlayer(), event.getBaseEntity(), event.getMechanic().getItemID(), event); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/customplugin/oraxen/OraxenPluginImpl.java b/src/main/java/net/momirealms/customcrops/api/customplugin/oraxen/OraxenPluginImpl.java new file mode 100644 index 0000000..f309743 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/customplugin/oraxen/OraxenPluginImpl.java @@ -0,0 +1,154 @@ +package net.momirealms.customcrops.api.customplugin.oraxen; + +import de.tr7zw.changeme.nbtapi.NBTCompound; +import de.tr7zw.changeme.nbtapi.NBTItem; +import io.th0rgal.oraxen.api.OraxenBlocks; +import io.th0rgal.oraxen.api.OraxenFurniture; +import io.th0rgal.oraxen.api.OraxenItems; +import io.th0rgal.oraxen.items.ItemBuilder; +import io.th0rgal.oraxen.mechanics.Mechanic; +import io.th0rgal.oraxen.mechanics.provided.gameplay.block.BlockMechanic; +import io.th0rgal.oraxen.mechanics.provided.gameplay.block.BlockMechanicFactory; +import io.th0rgal.oraxen.mechanics.provided.gameplay.furniture.FurnitureFactory; +import io.th0rgal.oraxen.mechanics.provided.gameplay.furniture.FurnitureMechanic; +import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanicFactory; +import io.th0rgal.oraxen.mechanics.provided.gameplay.stringblock.StringBlockMechanicFactory; +import io.th0rgal.oraxen.utils.drops.Drop; +import net.momirealms.customcrops.api.customplugin.PlatformInterface; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Rotation; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Entity; +import org.bukkit.entity.ItemDisplay; +import org.bukkit.entity.ItemFrame; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class OraxenPluginImpl implements PlatformInterface { + + @Override + public boolean removeCustomBlock(Location location) { + return OraxenBlocks.remove(location, null); + } + + @Nullable + @Override + public String getCustomBlockID(Location location) { + Mechanic mechanic = OraxenBlocks.getOraxenBlock(location); + return mechanic == null ? null : mechanic.getItemID(); + } + + @Nullable + @Override + public ItemStack getItemStack(String id) { + ItemBuilder itemBuilder = OraxenItems.getItemById(id); + return itemBuilder == null ? null : itemBuilder.build(); + } + + @Nullable + @Override + public ItemFrame placeItemFrame(Location location, String id) { + FurnitureMechanic mechanic = (FurnitureMechanic) FurnitureFactory.getInstance().getMechanic(id); + Entity entity = mechanic.place(location, 0, Rotation.NONE, BlockFace.UP); + if (entity instanceof ItemFrame itemFrame) + return itemFrame; + else { + entity.remove(); + } + return null; + } + + @Nullable + @Override + public ItemDisplay placeItemDisplay(Location location, String id) { + FurnitureMechanic mechanic = (FurnitureMechanic) FurnitureFactory.getInstance().getMechanic(id); + Entity entity = mechanic.place(location); + if (entity instanceof ItemDisplay itemDisplay) + return itemDisplay; + else { + entity.remove(); + } + return null; + } + + @Override + public void placeNoteBlock(Location location, String id) { + NoteBlockMechanicFactory.setBlockModel(location.getBlock(), id); + } + + @Override + public void placeTripWire(Location location, String id) { + StringBlockMechanicFactory.setBlockModel(location.getBlock(), id); + } + + @NotNull + @Override + public String getBlockID(Block block) { + Mechanic mechanic = OraxenBlocks.getOraxenBlock(block.getBlockData()); + return mechanic == null ? block.getType().name() : mechanic.getItemID(); + } + + @Override + public boolean doesItemExist(String id) { + return OraxenItems.getItemById(id) != null; + } + + @Override + public void dropBlockLoot(Block block) { + BlockMechanic mechanic = BlockMechanicFactory.getBlockMechanic(block); + if (mechanic == null) return; + Drop drop = mechanic.getDrop(); + if (drop != null) + drop.spawns(block.getLocation(), new ItemStack(Material.AIR)); + } + + @Override + public boolean removeItemDisplay(Location location) { + //TODO Not implemented + return false; + } + + @Override + public void placeChorus(Location location, String id) { + //TODO Not implemented + } + + @Override + public Location getItemFrameLocation(Location location) { + return location.clone().add(0.5,0.03125,0.5); + } + + @Nullable + @Override + public String getCustomItemAt(Location location) { + String block = getBlockID(location.getBlock()); + if (!block.equals("AIR")) return block; + + ItemFrame itemFrame = getItemFrameAt(location); + if (itemFrame != null) { + FurnitureMechanic furnitureMechanic = OraxenFurniture.getFurnitureMechanic(itemFrame); + if (furnitureMechanic != null) { + return furnitureMechanic.getItemID(); + } + } + + return null; + } + + @NotNull + @Override + public String getItemID(@NotNull ItemStack itemStack) { + if (itemStack.getType() != Material.AIR) { + NBTItem nbtItem = new NBTItem(itemStack); + NBTCompound bukkitPublic = nbtItem.getCompound("PublicBukkitValues"); + if (bukkitPublic != null) { + String id = bukkitPublic.getString("oraxen:id"); + if (!id.equals("")) return id; + } + } + return itemStack.getType().name(); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/event/CropHarvestEvent.java b/src/main/java/net/momirealms/customcrops/api/event/CropHarvestEvent.java deleted file mode 100644 index 19ee73f..0000000 --- a/src/main/java/net/momirealms/customcrops/api/event/CropHarvestEvent.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.api.event; - -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.objects.fertilizer.Fertilizer; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class CropHarvestEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final Location location; - private final Crop crop; - private final Fertilizer fertilizer; - - public CropHarvestEvent(@NotNull Player who, Crop crop, Location location, @Nullable Fertilizer fertilizer) { - super(who); - this.crop = crop; - this.location = location; - this.cancelled = false; - this.fertilizer = fertilizer; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } - - /** - * Get the crop player is harvesting - * @return crop - */ - public Crop getCrop() { - return crop; - } - - public Location getLocation() { - return location; - } - - @Nullable - public Fertilizer getFertilizer() { - return fertilizer; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/event/CrowAttackEvent.java b/src/main/java/net/momirealms/customcrops/api/event/CrowAttackEvent.java deleted file mode 100644 index e482b54..0000000 --- a/src/main/java/net/momirealms/customcrops/api/event/CrowAttackEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.api.event; - -import org.bukkit.Location; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -public class CrowAttackEvent extends Event { - - private final Location location; - private static final HandlerList handlers = new HandlerList(); - - public CrowAttackEvent(Location location) { - this.location = location; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } - - public Location getLocation() { - return location; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/event/CustomWorldEvent.java b/src/main/java/net/momirealms/customcrops/api/event/CustomWorldEvent.java deleted file mode 100644 index ebd1691..0000000 --- a/src/main/java/net/momirealms/customcrops/api/event/CustomWorldEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package net.momirealms.customcrops.api.event; - -import net.momirealms.customcrops.objects.WorldState; -import org.bukkit.World; -import org.bukkit.event.HandlerList; -import org.bukkit.event.world.WorldEvent; -import org.jetbrains.annotations.NotNull; - -public class CustomWorldEvent extends WorldEvent { - - private static final HandlerList handlers = new HandlerList(); - private final WorldState state; - - public CustomWorldEvent(@NotNull World world, WorldState worldState) { - super(world); - this.state = worldState; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } - - public WorldState getState() { - return state; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/event/FertilizerUseEvent.java b/src/main/java/net/momirealms/customcrops/api/event/FertilizerUseEvent.java deleted file mode 100644 index 82ff701..0000000 --- a/src/main/java/net/momirealms/customcrops/api/event/FertilizerUseEvent.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.api.event; - -import net.momirealms.customcrops.objects.fertilizer.Fertilizer; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -public class FertilizerUseEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private Fertilizer fertilizer; - private final Location potLoc; - - public FertilizerUseEvent(@NotNull Player who, Fertilizer fertilizer, Location potLoc) { - super(who); - this.cancelled = false; - this.potLoc = potLoc; - this.fertilizer = fertilizer; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } - - /** - * Get the fertilizer player is using - * @return fertilizer - */ - public Fertilizer getFertilizer() { - return fertilizer; - } - - public void setFertilizer(Fertilizer fertilizer) { - this.fertilizer = fertilizer; - } - - public Location getPotLoc() { - return potLoc; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/event/SeedPlantEvent.java b/src/main/java/net/momirealms/customcrops/api/event/SeedPlantEvent.java deleted file mode 100644 index 8414375..0000000 --- a/src/main/java/net/momirealms/customcrops/api/event/SeedPlantEvent.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package net.momirealms.customcrops.api.event; - -import net.momirealms.customcrops.api.crop.Crop; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class SeedPlantEvent extends Event implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final Location seedLoc; - private final Crop crop; - private final Player player; - - public SeedPlantEvent(@Nullable Player who, Location seedLoc, Crop crop) { - this.player = who; - this.cancelled = false; - this.seedLoc = seedLoc; - this.crop = crop; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } - - public Location getSeedLoc() { - return seedLoc; - } - - public Crop getCrop() { - return crop; - } - - /** - * return null if this is not triggered by a player - */ - @Nullable - public Player getPlayer() { - return player; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/event/SprinklerPlaceEvent.java b/src/main/java/net/momirealms/customcrops/api/event/SprinklerPlaceEvent.java deleted file mode 100644 index fa1eaae..0000000 --- a/src/main/java/net/momirealms/customcrops/api/event/SprinklerPlaceEvent.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package net.momirealms.customcrops.api.event; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -public class SprinklerPlaceEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final Location location; - - public SprinklerPlaceEvent(@NotNull Player who, Location location) { - super(who); - this.cancelled = false; - this.location = location; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } - - public Location getLocation() { - return location; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/event/SurveyorUseEvent.java b/src/main/java/net/momirealms/customcrops/api/event/SurveyorUseEvent.java deleted file mode 100644 index a0c129d..0000000 --- a/src/main/java/net/momirealms/customcrops/api/event/SurveyorUseEvent.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package net.momirealms.customcrops.api.event; - -import net.momirealms.customcrops.objects.fertilizer.Fertilizer; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class SurveyorUseEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final Fertilizer fertilizer; - private final Location potLoc; - - public SurveyorUseEvent(@NotNull Player who, @Nullable Fertilizer fertilizer, Location potLoc) { - super(who); - this.cancelled = false; - this.fertilizer = fertilizer; - this.potLoc = potLoc; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } - - @Nullable - public Fertilizer getFertilizer() { - return fertilizer; - } - - public Location getPotLoc() { - return potLoc; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/event/WaterBucketFillSprinklerEvent.java b/src/main/java/net/momirealms/customcrops/api/event/WaterBucketFillSprinklerEvent.java deleted file mode 100644 index b56e09d..0000000 --- a/src/main/java/net/momirealms/customcrops/api/event/WaterBucketFillSprinklerEvent.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.momirealms.customcrops.api.event; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -public class WaterBucketFillSprinklerEvent extends PlayerEvent implements Cancellable { - - private final ItemStack itemStack; - private boolean cancelled; - private static final HandlerList handlers = new HandlerList(); - - public WaterBucketFillSprinklerEvent(@NotNull Player who, ItemStack itemStack) { - super(who); - this.itemStack = itemStack; - this.cancelled = false; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public @NotNull HandlerList getHandlers() { - return handlers; - } - - public ItemStack getItemStack() { - return itemStack; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/event/WaterCanFillSprinklerEvent.java b/src/main/java/net/momirealms/customcrops/api/event/WaterCanFillSprinklerEvent.java deleted file mode 100644 index b54c88a..0000000 --- a/src/main/java/net/momirealms/customcrops/api/event/WaterCanFillSprinklerEvent.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.api.event; - -import de.tr7zw.changeme.nbtapi.NBTItem; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -public class WaterCanFillSprinklerEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final NBTItem nbtItem; - - public WaterCanFillSprinklerEvent(@NotNull Player who, NBTItem nbtItem) { - super(who); - this.cancelled = false; - this.nbtItem = nbtItem; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } - - public NBTItem getNbtItem() { - return nbtItem; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/event/WaterPotEvent.java b/src/main/java/net/momirealms/customcrops/api/event/WaterPotEvent.java index dde2833..3046400 100644 --- a/src/main/java/net/momirealms/customcrops/api/event/WaterPotEvent.java +++ b/src/main/java/net/momirealms/customcrops/api/event/WaterPotEvent.java @@ -1,83 +1,4 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - package net.momirealms.customcrops.api.event; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -public class WaterPotEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final ItemStack itemStack; - private int currentWater; - private final Location location; - - /** - * ItemStack can be a water-bucket or a watering-can - */ - public WaterPotEvent(@NotNull Player who, Location location, ItemStack itemStack, int currentWater) { - super(who); - this.cancelled = false; - this.itemStack = itemStack; - this.currentWater = currentWater; - this.location = location; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } - - public ItemStack getItemStack() { - return itemStack; - } - - public int getCurrentWater() { - return currentWater; - } - - public void setCurrentWater(int currentWater) { - this.currentWater = currentWater; - } - - public Location getLocation() { - return location; - } +public class WaterPotEvent { } diff --git a/src/main/java/net/momirealms/customcrops/api/event/WateringCanFillEvent.java b/src/main/java/net/momirealms/customcrops/api/event/WateringCanFillEvent.java deleted file mode 100644 index b95dcab..0000000 --- a/src/main/java/net/momirealms/customcrops/api/event/WateringCanFillEvent.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.api.event; - -import de.tr7zw.changeme.nbtapi.NBTItem; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -public class WateringCanFillEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final NBTItem nbtItem; - private int currentWater; - - public WateringCanFillEvent(@NotNull Player who, NBTItem nbtItem, int currentWater) { - super(who); - this.cancelled = false; - this.nbtItem = nbtItem; - this.currentWater = currentWater; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } - - public NBTItem getNbtItem() { - return nbtItem; - } - - public int getCurrentWater() { - return currentWater; - } - - public void setCurrentWater(int currentWater) { - this.currentWater = currentWater; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/object/BoneMeal.java b/src/main/java/net/momirealms/customcrops/api/object/BoneMeal.java new file mode 100644 index 0000000..4a6e9e1 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/BoneMeal.java @@ -0,0 +1,55 @@ +package net.momirealms.customcrops.api.object; + +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.CustomCrops; +import org.bukkit.Particle; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; + +public class BoneMeal { + + private final String item; + private final String returned; + private final ArrayList> pairs; + private final Sound sound; + private final Particle particle; + + public BoneMeal(String item, @Nullable String returned, @NotNull ArrayList> pairs, @Nullable Sound sound, @Nullable Particle particle) { + this.item = item; + this.returned = returned; + this.pairs = pairs; + this.sound = sound; + this.particle = particle; + } + + public boolean isRightItem(String id) { + return item.equals(id); + } + + public ItemStack getReturned() { + if (returned == null) return null; + return CustomCrops.getInstance().getIntegrationManager().build(returned); + } + + public int getPoint() { + for (Pair pair : pairs) { + if (Math.random() < pair.left()) { + return pair.right(); + } + } + return 0; + } + + @Nullable + public Sound getSound() { + return sound; + } + + @Nullable + public Particle getParticle() { + return particle; + } +} diff --git a/src/main/java/net/momirealms/customcrops/managers/timer/CrowTask.java b/src/main/java/net/momirealms/customcrops/api/object/CrowTask.java similarity index 52% rename from src/main/java/net/momirealms/customcrops/managers/timer/CrowTask.java rename to src/main/java/net/momirealms/customcrops/api/object/CrowTask.java index f75c104..3b1e298 100644 --- a/src/main/java/net/momirealms/customcrops/managers/timer/CrowTask.java +++ b/src/main/java/net/momirealms/customcrops/api/object/CrowTask.java @@ -15,13 +15,14 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.managers.timer; +package net.momirealms.customcrops.api.object; +import com.willfp.eco.core.items.Items; import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.config.BasicItemConfig; -import net.momirealms.customcrops.utils.ArmorStandUtil; +import net.momirealms.customcrops.api.util.ArmorStandUtils; import org.bukkit.Location; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; @@ -31,46 +32,44 @@ public class CrowTask extends BukkitRunnable { private int timer; private final int entityID; - private final ArmorStandUtil armorStandUtil; private final Vector vectorDown; private final Vector vectorUp; private final Location from; private final Player player; private final float yaw; + private final ItemStack fly; + private final ItemStack stand; - - public CrowTask(Player player, Location crop, ArmorStandUtil armorStandUtil) { + public CrowTask(Player player, Location crop, String fly_model, String stand_model) { this.timer = 0; + this.fly = CustomCrops.getInstance().getIntegrationManager().build(fly_model); + this.stand = CustomCrops.getInstance().getIntegrationManager().build(stand_model); this.player = player; - this.armorStandUtil = armorStandUtil; this.entityID = new Random().nextInt(10000000); this.yaw = new Random().nextInt(361) - 180; this.from = crop.clone().add(10 * Math.sin((Math.PI * yaw)/180), 10, - 10 * Math.cos((Math.PI * yaw)/180)); Location relative = crop.clone().subtract(from); this.vectorDown = new Vector(relative.getX() / 100, -0.1, relative.getZ() / 100); this.vectorUp = new Vector(relative.getX() / 100, 0.1, relative.getZ() / 100); - CustomCrops.protocolManager.sendServerPacket(player, armorStandUtil.getSpawnPacket(entityID, from)); - CustomCrops.protocolManager.sendServerPacket(player, armorStandUtil.getMetaPacket(entityID)); - CustomCrops.protocolManager.sendServerPacket(player, armorStandUtil.getEquipPacket(entityID, armorStandUtil.getCropManager().getCustomInterface().getItemStack(BasicItemConfig.crowFly))); + CustomCrops.getProtocolManager().sendServerPacket(player, ArmorStandUtils.getSpawnPacket(entityID, from)); + CustomCrops.getProtocolManager().sendServerPacket(player, ArmorStandUtils.getMetaPacket(entityID)); + CustomCrops.getProtocolManager().sendServerPacket(player, ArmorStandUtils.getEquipPacket(entityID, fly)); } @Override public void run() { timer++; if (timer < 100) { - CustomCrops.protocolManager.sendServerPacket(player, armorStandUtil.getTeleportPacket(entityID, from.add(vectorDown), yaw)); - } - else if (timer == 100){ - CustomCrops.protocolManager.sendServerPacket(player, armorStandUtil.getEquipPacket(entityID, armorStandUtil.getCropManager().getCustomInterface().getItemStack(BasicItemConfig.crowLand))); - } - else if (timer == 150) { - CustomCrops.protocolManager.sendServerPacket(player, armorStandUtil.getEquipPacket(entityID, armorStandUtil.getCropManager().getCustomInterface().getItemStack(BasicItemConfig.crowFly))); - } - else if (timer > 150) { - CustomCrops.protocolManager.sendServerPacket(player, armorStandUtil.getTeleportPacket(entityID, from.add(vectorUp), yaw)); + CustomCrops.getProtocolManager().sendServerPacket(player, ArmorStandUtils.getTeleportPacket(entityID, from.add(vectorDown), yaw)); + } else if (timer == 100){ + CustomCrops.getProtocolManager().sendServerPacket(player, ArmorStandUtils.getEquipPacket(entityID, stand)); + } else if (timer == 150) { + CustomCrops.getProtocolManager().sendServerPacket(player, ArmorStandUtils.getEquipPacket(entityID, fly)); + } else if (timer > 150) { + CustomCrops.getProtocolManager().sendServerPacket(player, ArmorStandUtils.getTeleportPacket(entityID, from.add(vectorUp), yaw)); } if (timer > 300) { - CustomCrops.protocolManager.sendServerPacket(player, armorStandUtil.getDestroyPacket(entityID)); + CustomCrops.getProtocolManager().sendServerPacket(player, ArmorStandUtils.getDestroyPacket(entityID)); cancel(); } } diff --git a/src/main/java/net/momirealms/customcrops/api/object/Function.java b/src/main/java/net/momirealms/customcrops/api/object/Function.java new file mode 100644 index 0000000..c3657f6 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/Function.java @@ -0,0 +1,16 @@ +package net.momirealms.customcrops.api.object; + +public class Function { + + public void load() { + + } + + public void unload() { + + } + + public void disable() { + + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/InteractWithItem.java b/src/main/java/net/momirealms/customcrops/api/object/InteractWithItem.java new file mode 100644 index 0000000..ca1f6b1 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/InteractWithItem.java @@ -0,0 +1,42 @@ +package net.momirealms.customcrops.api.object; + +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.action.Action; +import org.bukkit.Particle; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class InteractWithItem { + + private final boolean consume; + private final String id; + private final String returned; + private final Action[] actions; + + public InteractWithItem(@NotNull String id, boolean consume, @Nullable String returned, @Nullable Action[] actions) { + this.consume = consume; + this.id = id; + this.returned = returned; + this.actions = actions; + } + + public boolean isRightItem(String item) { + return item.equals(id); + } + + @Nullable + public ItemStack getReturned() { + if (returned == null) return null; + return CustomCrops.getInstance().getIntegrationManager().build(returned); + } + + public boolean isConsumed() { + return consume; + } + + public Action[] getActions() { + return actions; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/ItemMode.java b/src/main/java/net/momirealms/customcrops/api/object/ItemMode.java new file mode 100644 index 0000000..41d5564 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/ItemMode.java @@ -0,0 +1,9 @@ +package net.momirealms.customcrops.api.object; + +public enum ItemMode { + + TRIPWIRE, + ITEM_FRAME, + ITEM_DISPLAY, + CHORUS +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/ItemType.java b/src/main/java/net/momirealms/customcrops/api/object/ItemType.java new file mode 100644 index 0000000..0913761 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/ItemType.java @@ -0,0 +1,11 @@ +package net.momirealms.customcrops.api.object; + +public enum ItemType { + + GLASS, + POT, + CROP, + SPRINKLER, + SCARECROW, + WATERINGCAN, UNKNOWN +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/Pair.java b/src/main/java/net/momirealms/customcrops/api/object/Pair.java new file mode 100644 index 0000000..67f2e72 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/Pair.java @@ -0,0 +1,8 @@ +package net.momirealms.customcrops.api.object; + +public record Pair(L left, R right) { + + public static Pair of(final L left, final R right) { + return new Pair<>(left, right); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/integrations/SkillInterface.java b/src/main/java/net/momirealms/customcrops/api/object/action/Action.java similarity index 67% rename from src/main/java/net/momirealms/customcrops/integrations/SkillInterface.java rename to src/main/java/net/momirealms/customcrops/api/object/action/Action.java index 160c2f9..82d4a82 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/SkillInterface.java +++ b/src/main/java/net/momirealms/customcrops/api/object/action/Action.java @@ -15,14 +15,15 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.integrations; +package net.momirealms.customcrops.api.object.action; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; -public interface SkillInterface { +public interface Action { - void addXp(Player player, double amount); + void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode); - int getLevel(Player player); - -} \ No newline at end of file +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/BreakImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/BreakImpl.java new file mode 100644 index 0000000..944abc1 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/BreakImpl.java @@ -0,0 +1,42 @@ +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.CustomCropsAPI; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.crop.StageConfig; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public class BreakImpl implements Action { + + private final boolean triggerAction; + private final String stage_id; + + public BreakImpl(boolean triggerAction, @Nullable String stage_id) { + this.triggerAction = triggerAction; + this.stage_id = stage_id; + } + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (crop_loc == null) return; + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + CustomCropsAPI.getInstance().removeCustomItem(crop_loc.getBukkitLocation(), itemMode); + CustomCrops.getInstance().getWorldDataManager().removeCropData(crop_loc); + return null; + }); + if (triggerAction && stage_id != null) { + StageConfig stageConfig = CustomCrops.getInstance().getCropManager().getStageConfig(stage_id); + if (stageConfig != null) { + Action[] actions = stageConfig.getBreakActions(); + if (actions != null) { + for (Action action : actions) { + action.doOn(player, crop_loc, itemMode); + } + } + } + } + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/ChainImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/ChainImpl.java new file mode 100644 index 0000000..8fddfcb --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/ChainImpl.java @@ -0,0 +1,26 @@ +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public class ChainImpl implements Action { + + private final Action[] actions; + private final double chance; + + public ChainImpl(Action[] actions, double chance) { + this.actions = actions; + this.chance = chance; + } + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (Math.random() < chance) { + for (Action action : actions) { + action.doOn(player, crop_loc, itemMode); + } + } + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/CommandActionImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/CommandActionImpl.java new file mode 100644 index 0000000..e929322 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/CommandActionImpl.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public record CommandActionImpl(String[] commands, double chance) implements Action { + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (player == null || Math.random() > chance) return; + for (String command : commands) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), + command.replace("{player}", player.getName()) + .replace("{x}", crop_loc == null ? "" : String.valueOf(crop_loc.getX())) + .replace("{y}", crop_loc == null ? "" : String.valueOf(crop_loc.getY())) + .replace("{z}", crop_loc == null ? "" : String.valueOf(crop_loc.getZ())) + .replace("{world}", player.getWorld().getName()) + ); + } + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/DropItemImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/DropItemImpl.java new file mode 100644 index 0000000..2f5a545 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/DropItemImpl.java @@ -0,0 +1,18 @@ +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.loot.Loot; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public record DropItemImpl(Loot[] loots) implements Action { + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (crop_loc == null) return; + for (Loot loot : loots) { + loot.drop(player, crop_loc.getBukkitLocation()); + } + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/JobXPImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/JobXPImpl.java new file mode 100644 index 0000000..d574eb9 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/JobXPImpl.java @@ -0,0 +1,19 @@ +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import net.momirealms.customcrops.integration.JobInterface; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public record JobXPImpl(double amount, double chance) implements Action { + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (player == null || Math.random() > chance) return; + JobInterface jobInterface = CustomCrops.getInstance().getIntegrationManager().getJobInterface(); + if (jobInterface == null) return; + jobInterface.addXp(player, amount); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/MessageActionImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/MessageActionImpl.java new file mode 100644 index 0000000..0c603b7 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/MessageActionImpl.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import net.momirealms.customcrops.api.util.AdventureUtils; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public record MessageActionImpl(String[] messages, double chance) implements Action { + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (player == null || Math.random() > chance) return; + for (String message : messages) { + AdventureUtils.playerMessage(player, + message.replace("{player}", player.getName()) + .replace("{world}", player.getWorld().getName()) + .replace("{x}", crop_loc == null ? "" : String.valueOf(crop_loc.getX())) + .replace("{y}", crop_loc == null ? "" : String.valueOf(crop_loc.getY())) + .replace("{z}", crop_loc == null ? "" : String.valueOf(crop_loc.getZ())) + ); + } + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/ParticleImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/ParticleImpl.java new file mode 100644 index 0000000..f4d8dc9 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/ParticleImpl.java @@ -0,0 +1,29 @@ +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public class ParticleImpl implements Action { + + private final Particle particle; + private final int amount; + private final double offset; + + public ParticleImpl(Particle particle, int amount, double offset) { + this.particle = particle; + this.amount = amount; + this.offset = offset; + } + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (crop_loc == null) return; + Location location = crop_loc.getBukkitLocation(); + if (location == null) return; + location.getWorld().spawnParticle(particle, location.clone().add(0.5,0.5,0.5), amount, offset, offset, offset); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/PotionEffectImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/PotionEffectImpl.java new file mode 100644 index 0000000..da27c9c --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/PotionEffectImpl.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.jetbrains.annotations.Nullable; + +public record PotionEffectImpl(PotionEffect potionEffect, double chance) implements Action { + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (player == null || Math.random() > chance) return; + player.addPotionEffect(potionEffect); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/ReplantImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/ReplantImpl.java new file mode 100644 index 0000000..a42c67a --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/ReplantImpl.java @@ -0,0 +1,49 @@ +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.CustomCropsAPI; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.basic.MessageManager; +import net.momirealms.customcrops.api.object.crop.CropConfig; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.crop.GrowingCrop; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import net.momirealms.customcrops.api.util.AdventureUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public class ReplantImpl implements Action { + + private final int point; + private final String crop; + private final String model; + + public ReplantImpl(int point, String model, String crop) { + this.point = point; + this.crop = crop; + this.model = model; + } + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + CropConfig cropConfig = CustomCrops.getInstance().getCropManager().getCropConfigByID(crop); + if (crop_loc != null && cropConfig != null) { + ItemMode newCMode = cropConfig.getCropMode(); + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + Location location = crop_loc.getBukkitLocation(); + if (location == null) return null; + if (ConfigManager.enableLimitation && CustomCrops.getInstance().getWorldDataManager().getChunkCropAmount(crop_loc) >= ConfigManager.maxCropPerChunk) { + if (player != null)AdventureUtils.playerMessage(player, MessageManager.prefix + MessageManager.reachChunkLimit); + return null; + } + if (!CustomCrops.getInstance().getPlatformInterface().detectAnyThing(location)) { + CustomCropsAPI.getInstance().placeCustomItem(location, model, newCMode); + CustomCrops.getInstance().getWorldDataManager().addCropData(crop_loc, new GrowingCrop(crop, point)); + } + return null; + }); + } + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/SkillXPImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/SkillXPImpl.java new file mode 100644 index 0000000..580a01b --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/SkillXPImpl.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import net.momirealms.customcrops.integration.SkillInterface; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public record SkillXPImpl(double amount, double chance) implements Action { + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (player == null || Math.random() > chance) return; + SkillInterface skillInterface = CustomCrops.getInstance().getIntegrationManager().getSkillInterface(); + if (skillInterface == null) return; + skillInterface.addXp(player, amount); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/objects/WrappedSound.java b/src/main/java/net/momirealms/customcrops/api/object/action/SoundActionImpl.java similarity index 52% rename from src/main/java/net/momirealms/customcrops/objects/WrappedSound.java rename to src/main/java/net/momirealms/customcrops/api/object/action/SoundActionImpl.java index 34f8b43..98c5825 100644 --- a/src/main/java/net/momirealms/customcrops/objects/WrappedSound.java +++ b/src/main/java/net/momirealms/customcrops/api/object/action/SoundActionImpl.java @@ -15,32 +15,21 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects; +package net.momirealms.customcrops.api.object.action; import net.kyori.adventure.key.Key; import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import net.momirealms.customcrops.api.util.AdventureUtils; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; -public class WrappedSound { +public record SoundActionImpl(String source, String sound, float volume, float pitch) implements Action { - private final Sound.Source source; - private final Key key; - private final boolean enable; - - public WrappedSound(Sound.Source source, Key key, boolean enable) { - this.source = source; - this.key = key; - this.enable = enable; - } - - public Sound.Source getSource() { - return source; - } - - public Key getKey() { - return key; - } - - public boolean isEnable() { - return enable; + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (player == null) return; + AdventureUtils.playerSound(player, Sound.Source.valueOf(source.toUpperCase()), Key.key(sound), volume, pitch); } } diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/VanillaXPImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/VanillaXPImpl.java new file mode 100644 index 0000000..3a13a72 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/VanillaXPImpl.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.action; + +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import net.momirealms.customcrops.api.util.AdventureUtils; +import org.bukkit.entity.ExperienceOrb; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public record VanillaXPImpl(int amount, boolean mending, double chance) implements Action { + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (player == null || Math.random() > chance) return; + if (CustomCrops.getInstance().getVersionHelper().isSpigot()) { + if (mending) { + player.getLocation().getWorld().spawn(player.getLocation(), ExperienceOrb.class, e -> e.setExperience(amount)); + } + else { + player.giveExp(amount); + AdventureUtils.playerSound(player, Sound.Source.PLAYER, Key.key("minecraft:entity.experience_orb.pickup"), 1, 1); + } + } + else { + player.giveExp(amount, mending); + AdventureUtils.playerSound(player, Sound.Source.PLAYER, Key.key("minecraft:entity.experience_orb.pickup"), 1, 1); + } + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/action/VariationImpl.java b/src/main/java/net/momirealms/customcrops/api/object/action/VariationImpl.java new file mode 100644 index 0000000..ff3f614 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/action/VariationImpl.java @@ -0,0 +1,60 @@ +package net.momirealms.customcrops.api.object.action; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.CustomCropsAPI; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.crop.VariationCrop; +import net.momirealms.customcrops.api.object.fertilizer.Variation; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public record VariationImpl(VariationCrop[] variationCrops) implements Action { + + @Override + public void doOn(@Nullable Player player, @Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (crop_loc == null) return; + double bonus = 0; + Pot pot = CustomCrops.getInstance().getWorldDataManager().getPotData(crop_loc.add(0,-1,0)); + if (pot != null && CustomCrops.getInstance().getFertilizerManager().getConfigByFertilizer(pot.getFertilizer()) instanceof Variation variation) { + bonus = variation.getChance(); + } + for (VariationCrop variationCrop : variationCrops) { + if (Math.random() < variationCrop.getChance() + bonus) { + doVariation(crop_loc, itemMode, variationCrop); + break; + } + } + } + + public boolean doOn(@Nullable SimpleLocation crop_loc, ItemMode itemMode) { + if (crop_loc == null) return false; + double bonus = 0; + Pot pot = CustomCrops.getInstance().getWorldDataManager().getPotData(crop_loc.add(0,-1,0)); + if (pot != null && CustomCrops.getInstance().getFertilizerManager().getConfigByFertilizer(pot.getFertilizer()) instanceof Variation variation) { + bonus = variation.getChance(); + } + for (VariationCrop variationCrop : variationCrops) { + if (Math.random() < variationCrop.getChance() + bonus) { + doVariation(crop_loc, itemMode, variationCrop); + return true; + } + } + return false; + } + + private void doVariation(@NotNull SimpleLocation crop_loc, ItemMode itemMode, VariationCrop variationCrop) { + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + Location location = crop_loc.getBukkitLocation(); + if (CustomCropsAPI.getInstance().removeCustomItem(location, itemMode)) { + CustomCropsAPI.getInstance().placeCustomItem(location, variationCrop.getId(), variationCrop.getCropMode()); + } + CustomCrops.getInstance().getWorldDataManager().removeCropData(crop_loc); + return null; + }); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/basic/ConfigManager.java b/src/main/java/net/momirealms/customcrops/api/object/basic/ConfigManager.java new file mode 100644 index 0000000..7a7bdca --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/basic/ConfigManager.java @@ -0,0 +1,98 @@ +package net.momirealms.customcrops.api.object.basic; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.api.util.ConfigUtils; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.util.HashSet; +import java.util.Objects; + +public class ConfigManager extends Function { + + public static String lang; + public static boolean enableBStats; + public static boolean checkUpdate; + public static boolean enableSkillBonus; + public static String bonusFormula; + public static int greenhouseRange; + public static boolean whiteListWorlds; + public static HashSet worldList; + public static String worldFolderPath; + public static boolean debug; + public static String greenhouseBlock; + public static String scarecrow; + public static boolean enableGreenhouse; + public static int pointGainInterval; + public static int corePoolSize; + public static double[] defaultRatio; + public static int maxPoolSize; + public static long keepAliveTime; + public static int seasonInterval; + public static boolean enableSeason; + public static boolean rsHook; + public static boolean enableScheduleSystem; + public static boolean syncSeason; + public static boolean autoSeasonChange; + public static String referenceWorld; + public static boolean enableLimitation; + public static int maxCropPerChunk; + public static boolean setUpMode; + + private final CustomCrops plugin; + + public ConfigManager(CustomCrops plugin) { + this.plugin = plugin; + } + + @Override + public void load() { + this.loadConfig(); + } + + private void loadConfig() { + ConfigUtils.update("config.yml"); + YamlConfiguration config = ConfigUtils.getConfig("config.yml"); + enableBStats = config.getBoolean("metrics"); + lang = config.getString("lang"); + debug = config.getBoolean("debug"); + setUpMode = config.getBoolean("set-up-mode", true); + loadWorlds(Objects.requireNonNull(config.getConfigurationSection("worlds"))); + loadScheduleSystem(Objects.requireNonNull(config.getConfigurationSection("schedule-system"))); + loadMechanic(Objects.requireNonNull(config.getConfigurationSection("mechanics"))); + loadOtherSetting(Objects.requireNonNull(config.getConfigurationSection("other-settings"))); + } + + private void loadWorlds(ConfigurationSection section) { + worldFolderPath = section.getString("folder", ""); + whiteListWorlds = section.getString("mode", "whitelist").equalsIgnoreCase("whitelist"); + worldList = new HashSet<>(section.getStringList("list")); + } + + private void loadScheduleSystem(ConfigurationSection section) { + enableScheduleSystem = section.getBoolean("enable"); + pointGainInterval = section.getInt("point-gain-interval", 1000); + corePoolSize = section.getInt("thread-pool-settings.corePoolSize", 2); + maxPoolSize = section.getInt("thread-pool-settings.maximumPoolSize", 4); + keepAliveTime = section.getInt("thread-pool-settings.keepAliveTime", 10); + } + + private void loadMechanic(ConfigurationSection section) { + defaultRatio = ConfigUtils.getQualityRatio(section.getString("default-quality-ratio", "17/2/1")); + enableSeason = section.getBoolean("season.enable", true); + syncSeason = section.getBoolean("season.sync-season.enable", false); + referenceWorld = section.getString("season.sync-season.reference"); + autoSeasonChange = section.getBoolean("season.auto-season-change.enable"); + seasonInterval = section.getInt("season.auto-season-change.duration", 28); + enableGreenhouse = section.getBoolean("season.greenhouse.enable", true); + greenhouseRange = section.getInt("season.greenhouse.range", 5); + greenhouseBlock = section.getString("season.greenhouse.block"); + } + + private void loadOtherSetting(ConfigurationSection section) { + enableSkillBonus = section.getBoolean("skill-bonus.enable", false); + bonusFormula = section.getString("skill-bonus.formula"); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/basic/MessageManager.java b/src/main/java/net/momirealms/customcrops/api/object/basic/MessageManager.java new file mode 100644 index 0000000..ab205bf --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/basic/MessageManager.java @@ -0,0 +1,69 @@ +package net.momirealms.customcrops.api.object.basic; + +import com.gmail.nossr50.mcmmo.acf.ACFUtil; +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.util.ConfigUtils; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; + +public class MessageManager extends Function { + + + private CustomCrops plugin; + + public static String prefix; + public static String reload; + public static String unavailableArgs; + public static String noConsole; + public static String notOnline; + public static String lackArgs; + public static String nonArgs; + public static String beforePlant; + public static String unsuitablePot; + public static String reachChunkLimit; + public static String spring; + public static String summer; + public static String autumn; + public static String winter; + public static String noPerm; + public static String noSeason; + public static String setSeason; + public static String setDate; + public static String worldNotExist; + public static String seasonNotExist; + + public MessageManager(CustomCrops plugin) { + this.plugin =plugin; + } + + @Override + public void load() { + this.loadMessage(); + } + + private void loadMessage() { + YamlConfiguration config = ConfigUtils.getConfig("messages" + File.separator + "messages_" + ConfigManager.lang + ".yml"); + prefix = config.getString("prefix","[CustomCrops] "); + reload = config.getString("reload", "Reloaded! Took {time}ms."); + unavailableArgs = config.getString("invalid-args", "Invalid arguments."); + noConsole = config.getString("no-console", "This command can only be executed by a player."); + notOnline = config.getString("not-online", "Player {player} is not online."); + lackArgs = config.getString("lack-args", "Arguments are insufficient."); + nonArgs = config.getString("not-none-args", "Not a none argument command."); + beforePlant = config.getString("before-plant", "This fertilizer can only be used before planting."); + unsuitablePot = config.getString("unsuitable-pot", "You can't plant the seed in this pot."); + reachChunkLimit = config.getString("reach-crop-limit", "The number of crops has reached the limitation."); + noPerm = config.getString("no-perm", "You don't have permission to do that."); + spring = config.getString("spring", "Spring"); + summer = config.getString("summer", "Summer"); + autumn = config.getString("autumn", "Autumn"); + winter = config.getString("winter", "Winter"); + noSeason = config.getString("no-season", "SEASON DISABLED IN THIS WORLD"); + setSeason = config.getString("set-season", "Successfully set {world}'s season to {season}."); + setDate = config.getString("set-date", "Successfully set {world}'s date to {date}."); + worldNotExist = config.getString("world-not-exist", "World {world} does not exist."); + seasonNotExist = config.getString("season-not-exist", "Season {season} does not exist."); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/condition/AndCondition.java b/src/main/java/net/momirealms/customcrops/api/object/condition/AndCondition.java new file mode 100644 index 0000000..90e5ab3 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/condition/AndCondition.java @@ -0,0 +1,24 @@ +package net.momirealms.customcrops.api.object.condition; + +import net.momirealms.customcrops.api.object.world.SimpleLocation; + +import java.util.List; + +public class AndCondition implements Condition { + + private final List deathConditions; + + public AndCondition(List deathConditions) { + this.deathConditions = deathConditions; + } + + @Override + public boolean isMet(SimpleLocation simpleLocation) { + for (Condition condition : deathConditions) { + if (!condition.isMet(simpleLocation)) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/condition/Condition.java b/src/main/java/net/momirealms/customcrops/api/object/condition/Condition.java new file mode 100644 index 0000000..b38ec0c --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/condition/Condition.java @@ -0,0 +1,8 @@ +package net.momirealms.customcrops.api.object.condition; + +import net.momirealms.customcrops.api.object.world.SimpleLocation; + +public interface Condition { + + boolean isMet(SimpleLocation simpleLocation); +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/condition/CrowAttack.java b/src/main/java/net/momirealms/customcrops/api/object/condition/CrowAttack.java new file mode 100644 index 0000000..a090671 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/condition/CrowAttack.java @@ -0,0 +1,35 @@ +package net.momirealms.customcrops.api.object.condition; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.CrowTask; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public class CrowAttack implements Condition { + + private final double chance; + private final String fly_model; + private final String stand_model; + + public CrowAttack(double chance, String fly_model, String stand_model) { + this.chance = chance; + this.fly_model = fly_model; + this.stand_model = stand_model; + } + + @Override + public boolean isMet(SimpleLocation simpleLocation) { + if (Math.random() > chance) return false; + Location location = simpleLocation.getBukkitLocation(); + if (location == null) return false; + Bukkit.getScheduler().runTask(CustomCrops.getInstance(), () -> { + for (Player player : location.getNearbyPlayers(48)) { + CrowTask crowTask = new CrowTask(player, location.clone().add(0.4,0,0.4), fly_model, stand_model); + crowTask.runTaskTimerAsynchronously(CustomCrops.getInstance(), 1, 1); + } + }); + return true; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/condition/DeathCondition.java b/src/main/java/net/momirealms/customcrops/api/object/condition/DeathCondition.java new file mode 100644 index 0000000..9a82488 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/condition/DeathCondition.java @@ -0,0 +1,42 @@ +package net.momirealms.customcrops.api.object.condition; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.CustomCropsAPI; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class DeathCondition { + + private final String dead_model; + private final Condition[] conditions; + + public DeathCondition(@Nullable String dead_model, @NotNull Condition[] conditions) { + this.dead_model = dead_model; + this.conditions = conditions; + } + + public boolean checkIfDead(SimpleLocation simpleLocation) { + for (Condition condition : conditions) { + if (condition.isMet(simpleLocation)) { + return true; + } + } + return false; + } + + public void applyDeadModel(SimpleLocation simpleLocation, ItemMode itemMode) { + Location location = simpleLocation.getBukkitLocation(); + if (location == null) return; + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + CustomCropsAPI.getInstance().removeCustomItem(location, itemMode); + if (dead_model != null) { + CustomCropsAPI.getInstance().placeCustomItem(location, dead_model, itemMode); + } + return null; + }); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/condition/OrCondition.java b/src/main/java/net/momirealms/customcrops/api/object/condition/OrCondition.java new file mode 100644 index 0000000..3857820 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/condition/OrCondition.java @@ -0,0 +1,24 @@ +package net.momirealms.customcrops.api.object.condition; + +import net.momirealms.customcrops.api.object.world.SimpleLocation; + +import java.util.List; + +public class OrCondition implements Condition { + + private final List deathConditions; + + public OrCondition(List deathConditions) { + this.deathConditions = deathConditions; + } + + @Override + public boolean isMet(SimpleLocation simpleLocation) { + for (Condition condition : deathConditions) { + if (condition.isMet(simpleLocation)) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/condition/Random.java b/src/main/java/net/momirealms/customcrops/api/object/condition/Random.java new file mode 100644 index 0000000..d9c5a90 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/condition/Random.java @@ -0,0 +1,17 @@ +package net.momirealms.customcrops.api.object.condition; + +import net.momirealms.customcrops.api.object.world.SimpleLocation; + +public class Random implements Condition { + + private final double chance; + + public Random(double chance) { + this.chance = chance; + } + + @Override + public boolean isMet(SimpleLocation simpleLocation) { + return Math.random() < chance; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/condition/RightSeason.java b/src/main/java/net/momirealms/customcrops/api/object/condition/RightSeason.java new file mode 100644 index 0000000..dcfb93f --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/condition/RightSeason.java @@ -0,0 +1,36 @@ +package net.momirealms.customcrops.api.object.condition; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.season.CCSeason; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import net.momirealms.customcrops.api.object.world.WorldDataManager; + +public class RightSeason implements Condition { + + private final CCSeason[] seasons; + + public RightSeason(CCSeason[] seasons) { + this.seasons = seasons; + } + + @Override + public boolean isMet(SimpleLocation simpleLocation) { + String world = simpleLocation.getWorldName(); + CCSeason current = CustomCrops.getInstance().getIntegrationManager().getSeasonInterface().getSeason(world); + for (CCSeason allowed : seasons) { + if (current == allowed) { + return true; + } + } + WorldDataManager worldDataManager = CustomCrops.getInstance().getWorldDataManager(); + if (ConfigManager.enableGreenhouse) { + for (int i = 0; i < ConfigManager.greenhouseRange; i++) { + if (worldDataManager.isGreenhouse(simpleLocation.add(0, i, 0))) { + return true; + } + } + } + return false; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/condition/WaterLessThan.java b/src/main/java/net/momirealms/customcrops/api/object/condition/WaterLessThan.java new file mode 100644 index 0000000..5b045d5 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/condition/WaterLessThan.java @@ -0,0 +1,21 @@ +package net.momirealms.customcrops.api.object.condition; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.world.SimpleLocation; + +public class WaterLessThan implements Condition { + + private final int amount; + + public WaterLessThan(int amount) { + this.amount = amount; + } + + @Override + public boolean isMet(SimpleLocation crop_loc) { + Pot pot = CustomCrops.getInstance().getWorldDataManager().getPotData(crop_loc.add(0,-1,0)); + if (pot == null) return true; + return pot.getWater() < amount; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/condition/WaterMoreThan.java b/src/main/java/net/momirealms/customcrops/api/object/condition/WaterMoreThan.java new file mode 100644 index 0000000..a57b5fc --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/condition/WaterMoreThan.java @@ -0,0 +1,21 @@ +package net.momirealms.customcrops.api.object.condition; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.world.SimpleLocation; + +public class WaterMoreThan implements Condition { + + private final int amount; + + public WaterMoreThan(int amount) { + this.amount = amount; + } + + @Override + public boolean isMet(SimpleLocation crop_loc) { + Pot pot = CustomCrops.getInstance().getWorldDataManager().getPotData(crop_loc.add(0,-1,0)); + if (pot == null) return false; + return pot.getWater() > amount; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/condition/WrongSeason.java b/src/main/java/net/momirealms/customcrops/api/object/condition/WrongSeason.java new file mode 100644 index 0000000..f27d9f8 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/condition/WrongSeason.java @@ -0,0 +1,36 @@ +package net.momirealms.customcrops.api.object.condition; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.season.CCSeason; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import net.momirealms.customcrops.api.object.world.WorldDataManager; + +public class WrongSeason implements Condition { + + private final CCSeason[] seasons; + + public WrongSeason(CCSeason[] seasons) { + this.seasons = seasons; + } + + @Override + public boolean isMet(SimpleLocation simpleLocation) { + String world = simpleLocation.getWorldName(); + CCSeason current = CustomCrops.getInstance().getIntegrationManager().getSeasonInterface().getSeason(world); + for (CCSeason bad : seasons) { + if (current == bad) { + WorldDataManager worldDataManager = CustomCrops.getInstance().getWorldDataManager(); + if (ConfigManager.enableGreenhouse) { + for (int i = 0; i < ConfigManager.greenhouseRange; i++) { + if (worldDataManager.isGreenhouse(simpleLocation.add(0, i, 0))) { + return false; + } + } + } + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/crop/CropConfig.java b/src/main/java/net/momirealms/customcrops/api/object/crop/CropConfig.java new file mode 100644 index 0000000..ea00166 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/crop/CropConfig.java @@ -0,0 +1,109 @@ +package net.momirealms.customcrops.api.object.crop; + +import net.momirealms.customcrops.api.object.BoneMeal; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.action.Action; +import net.momirealms.customcrops.api.object.condition.Condition; +import net.momirealms.customcrops.api.object.condition.DeathCondition; +import net.momirealms.customcrops.api.object.requirement.Requirement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; + +public class CropConfig { + + private String key; + private final ItemMode itemMode; + private final String[] bottom_blocks; + private final int max_points; + private final HashMap stageMap; + private final Requirement[] plantRequirements; + private final Requirement[] breakRequirements; + private final DeathCondition[] deathConditions; + private final Condition[] growConditions; + private final BoneMeal[] boneMeals; + private final Action[] plantActions; + + public CropConfig(String key, + ItemMode itemMode, + int max_points, + String[] bottom_blocks, + Requirement[] plantRequirements, + Requirement[] breakRequirements, + DeathCondition[] deathConditions, + Condition[] growConditions, + HashMap stageMap, + BoneMeal[] boneMeals, + Action[] plantActions + ) { + this.key = key; + this.itemMode = itemMode; + this.deathConditions = deathConditions; + this.plantRequirements = plantRequirements; + this.breakRequirements = breakRequirements; + this.max_points = max_points; + this.bottom_blocks = bottom_blocks; + this.stageMap = stageMap; + this.growConditions = growConditions; + this.boneMeals = boneMeals; + this.plantActions = plantActions; + } + + public String getKey() { + return key; + } + + @NotNull + public ItemMode getCropMode() { + return itemMode; + } + + public int getMaxPoints() { + return max_points; + } + + @Nullable + public StageConfig getStageConfig(int stage) { + return stageMap.get(stage); + } + + @NotNull + public String[] getBottom_blocks() { + return bottom_blocks; + } + + public int getMax_points() { + return max_points; + } + + @Nullable + public Requirement[] getPlantRequirements() { + return plantRequirements; + } + + @Nullable + public Requirement[] getBreakRequirements() { + return breakRequirements; + } + + @Nullable + public DeathCondition[] getDeathConditions() { + return deathConditions; + } + + @Nullable + public Condition[] getGrowConditions() { + return growConditions; + } + + @Nullable + public BoneMeal[] getBoneMeals() { + return boneMeals; + } + + @Nullable + public Action[] getPlantActions() { + return plantActions; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/crop/CropManager.java b/src/main/java/net/momirealms/customcrops/api/object/crop/CropManager.java new file mode 100644 index 0000000..d8e0d5a --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/crop/CropManager.java @@ -0,0 +1,182 @@ +package net.momirealms.customcrops.api.object.crop; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.condition.Condition; +import net.momirealms.customcrops.api.object.condition.DeathCondition; +import net.momirealms.customcrops.api.object.requirement.Requirement; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.api.util.ConfigUtils; +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Item; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.ItemSpawnEvent; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.util.HashMap; +import java.util.HashSet; + +public class CropManager extends Function implements Listener { + + private final CustomCrops plugin; + private final HashMap stageToCrop; + private final HashMap seedToCropConfig; + private final HashMap cropConfigMap; + private final HashMap stageConfigMap; + private final HashSet deadCrops; + + public CropManager(CustomCrops plugin) { + this.plugin = plugin; + this.stageToCrop = new HashMap<>(); + this.cropConfigMap = new HashMap<>(); + this.stageConfigMap = new HashMap<>(); + this.seedToCropConfig = new HashMap<>(); + this.deadCrops = new HashSet<>(); + } + + @Override + public void load() { + this.loadConfig(); + Bukkit.getPluginManager().registerEvents(this, plugin); + } + + @Override + public void unload() { + this.stageToCrop.clear(); + this.cropConfigMap.clear(); + this.stageConfigMap.clear(); + this.deadCrops.clear(); + this.seedToCropConfig.clear(); + HandlerList.unregisterAll(this); + } + + private void loadConfig() { + File crop_folder = new File(plugin.getDataFolder(), "contents" + File.separator + "crops"); + if (!crop_folder.exists()) { + if (!crop_folder.mkdirs()) return; + plugin.saveResource("contents" + File.separator + "crops" + File.separator + "tomato.yml", false); + } + File[] files = crop_folder.listFiles(); + if (files == null) return; + for (File file : files) { + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + for (String key : config.getKeys(false)) { + ConfigurationSection cropSec = config.getConfigurationSection(key); + if (cropSec == null) continue; + ItemMode itemMode = ItemMode.valueOf(cropSec.getString("crop-mode", "TripWire").toUpperCase()); + String[] bottomBlocks = cropSec.getStringList("pot-whitelist").toArray(new String[0]); + if (bottomBlocks.length == 0) { + AdventureUtils.consoleMessage("[CustomCrops] pot-whitelist is not set for crop: " + key); + continue; + } + + String seed = cropSec.getString("seed"); + Requirement[] breakReq = ConfigUtils.getRequirementsWithMsg(cropSec.getConfigurationSection("requirements.break")); + Requirement[] plantReq = ConfigUtils.getRequirementsWithMsg(cropSec.getConfigurationSection("requirements.plant")); + + int max = cropSec.getInt("max-points", 0); + ConfigurationSection pointSec = cropSec.getConfigurationSection("points"); + if (pointSec == null || max == 0) { + AdventureUtils.consoleMessage("[CustomCrops] Points are not set for crop: " + key); + continue; + } + HashMap stageMap = new HashMap<>(); + for (String point : pointSec.getKeys(false)) { + try { + int parsed = Integer.parseInt(point); + String stageModel = pointSec.getString(point + ".model"); + StageConfig stageConfig = new StageConfig( + stageModel, + ConfigUtils.getActions(pointSec.getConfigurationSection(point + ".events.break"), stageModel), + ConfigUtils.getActions(pointSec.getConfigurationSection(point + ".events.grow"), stageModel), + ConfigUtils.getInteractActions(pointSec.getConfigurationSection(point + ".events.interact-with-item"), stageModel), + ConfigUtils.getActions(pointSec.getConfigurationSection(point + ".events.interact-by-hand"), stageModel) + ); + stageMap.put(parsed, stageConfig); + if (stageModel != null) { + stageToCrop.put(stageModel, key); + stageConfigMap.put(stageModel, stageConfig); + } + } + catch (NumberFormatException e) { + AdventureUtils.consoleMessage("[CustomCrops] Unexpected point value: " + point); + } + } + DeathCondition[] deathConditions = ConfigUtils.getDeathConditions(cropSec.getConfigurationSection("death-conditions")); + Condition[] growConditions = ConfigUtils.getConditions(cropSec.getConfigurationSection("grow-conditions")); + CropConfig cropConfig = new CropConfig( + key, + itemMode, + max, + bottomBlocks, + plantReq, + breakReq, + deathConditions, + growConditions, + stageMap, + ConfigUtils.getBoneMeals(cropSec.getConfigurationSection("custom-bone-meal")), + ConfigUtils.getActions(cropSec.getConfigurationSection("plant-actions"), null) + ); + cropConfigMap.put(key, cropConfig); + if (seed != null) seedToCropConfig.put(seed, cropConfig); + } + } + AdventureUtils.consoleMessage("[CustomCrops] Loaded " + cropConfigMap.size() + " crop(s)"); + } + + @Nullable + public StageConfig getStageConfig(String stage_id) { + return stageConfigMap.get(stage_id); + } + + @Nullable + public CropConfig getCropConfigByID(String id) { + return this.cropConfigMap.get(id); + } + + @Nullable + public CropConfig getCropConfigByStage(String stage_id) { + String key = getCropConfigID(stage_id); + if (key == null) return null; + return this.cropConfigMap.get(key); + } + + @Nullable + public String getCropConfigID(String stage_id) { + return this.stageToCrop.get(stage_id); + } + + public boolean isDeadCrop(String id) { + return deadCrops.contains(id); + } + + public boolean containsStage(String stage_id) { + return stageToCrop.containsKey(stage_id); + } + + // Prevent players from getting stage model + @EventHandler + public void onItemSpawn(ItemSpawnEvent event) { + if (event.isCancelled()) return; + Item item = event.getEntity(); + String id = plugin.getPlatformInterface().getItemID(item.getItemStack()); + if (containsStage(id)) { + event.setCancelled(true); + } + } + + public void registerDeadCrops(String id) { + this.deadCrops.add(id); + } + + @Nullable + public CropConfig getCropConfigBySeed(String seed) { + return seedToCropConfig.get(seed); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/crop/GrowingCrop.java b/src/main/java/net/momirealms/customcrops/api/object/crop/GrowingCrop.java new file mode 100644 index 0000000..0d8306a --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/crop/GrowingCrop.java @@ -0,0 +1,32 @@ +package net.momirealms.customcrops.api.object.crop; + +import net.momirealms.customcrops.CustomCrops; + +import java.io.Serializable; + +public class GrowingCrop implements Serializable { + + private int points; + private final String crop; + + public GrowingCrop(String crop, int points) { + this.points = points; + this.crop = crop; + } + + public int getPoints() { + return points; + } + + public void setPoints(int points) { + this.points = points; + } + + public String getCropKey() { + return crop; + } + + public CropConfig getConfig() { + return CustomCrops.getInstance().getCropManager().getCropConfigByID(crop); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/crop/StageConfig.java b/src/main/java/net/momirealms/customcrops/api/object/crop/StageConfig.java new file mode 100644 index 0000000..0456860 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/crop/StageConfig.java @@ -0,0 +1,47 @@ +package net.momirealms.customcrops.api.object.crop; + +import net.momirealms.customcrops.api.object.InteractWithItem; +import net.momirealms.customcrops.api.object.action.Action; +import org.jetbrains.annotations.Nullable; + +public class StageConfig { + + private final String model; + private final Action[] breakActions; + private final InteractWithItem[] interactActions; + private final Action[] growActions; + private final Action[] interactByHandActions; + + public StageConfig(@Nullable String model, @Nullable Action[] breakActions, @Nullable Action[] growActions, @Nullable InteractWithItem[] interactActions, @Nullable Action[] interactByHandActions) { + this.breakActions = breakActions; + this.interactActions = interactActions; + this.growActions = growActions; + this.interactByHandActions = interactByHandActions; + this.model = model; + } + + @Nullable + public Action[] getBreakActions() { + return breakActions; + } + + @Nullable + public InteractWithItem[] getInteractActions() { + return interactActions; + } + + @Nullable + public Action[] getGrowActions() { + return growActions; + } + + @Nullable + public Action[] getInteractByHandActions() { + return interactByHandActions; + } + + @Nullable + public String getModel() { + return model; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/crop/VariationCrop.java b/src/main/java/net/momirealms/customcrops/api/object/crop/VariationCrop.java new file mode 100644 index 0000000..b2e676e --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/crop/VariationCrop.java @@ -0,0 +1,28 @@ +package net.momirealms.customcrops.api.object.crop; + +import net.momirealms.customcrops.api.object.ItemMode; + +public class VariationCrop { + + private final String id; + private final ItemMode itemMode; + private final double chance; + + public VariationCrop(String id, ItemMode itemMode, double chance) { + this.id = id; + this.itemMode = itemMode; + this.chance = chance; + } + + public String getId() { + return id; + } + + public ItemMode getCropMode() { + return itemMode; + } + + public double getChance() { + return chance; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fertilizer/Fertilizer.java b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/Fertilizer.java new file mode 100644 index 0000000..e6ec858 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/Fertilizer.java @@ -0,0 +1,39 @@ +package net.momirealms.customcrops.api.object.fertilizer; + +import net.momirealms.customcrops.CustomCrops; +import org.jetbrains.annotations.Nullable; + +import java.io.Serializable; + +public class Fertilizer implements Serializable { + + private final String key; + private int times; + + public Fertilizer(String key, int times) { + this.key = key; + this.times = times; + } + + public Fertilizer(FertilizerConfig fertilizerConfig) { + this.key = fertilizerConfig.getKey(); + this.times = fertilizerConfig.getTimes(); + } + + /* + If fertilizer is used up + */ + public boolean reduceTimes() { + times--; + return times <= 0; + } + + public String getKey() { + return key; + } + + @Nullable + public FertilizerConfig getConfig() { + return CustomCrops.getInstance().getFertilizerManager().getConfigByFertilizer(this); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fertilizer/FertilizerConfig.java b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/FertilizerConfig.java new file mode 100644 index 0000000..51bde95 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/FertilizerConfig.java @@ -0,0 +1,84 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.fertilizer; + +import net.kyori.adventure.sound.Sound; +import org.bukkit.Particle; +import org.jetbrains.annotations.Nullable; + +public abstract class FertilizerConfig { + + protected int times; + protected double chance; + protected String key; + protected FertilizerType fertilizerType; + protected String[] pot_whitelist; + protected boolean beforePlant; + protected Particle particle; + protected Sound sound; + + public FertilizerConfig(String key, FertilizerType fertilizerType, int times, double chance, @Nullable String[] pot_whitelist, boolean beforePlant, @Nullable Particle particle, @Nullable Sound sound) { + this.times = times; + this.chance = chance; + this.key = key; + this.fertilizerType = fertilizerType; + this.pot_whitelist = pot_whitelist; + this.beforePlant = beforePlant; + this.particle = particle; + this.sound = sound; + } + + public int getTimes() { + return times; + } + + public double getChance() { + return chance; + } + + public boolean canTakeEffect() { + return Math.random() < chance; + } + + public String getKey() { + return key; + } + + public FertilizerType getFertilizerType() { + return fertilizerType; + } + + @Nullable + public String[] getPotWhitelist() { + return pot_whitelist; + } + + public boolean isBeforePlant() { + return beforePlant; + } + + @Nullable + public Particle getParticle() { + return particle; + } + + @Nullable + public Sound getSound() { + return sound; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fertilizer/FertilizerManager.java b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/FertilizerManager.java new file mode 100644 index 0000000..896cdb7 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/FertilizerManager.java @@ -0,0 +1,113 @@ +package net.momirealms.customcrops.api.object.fertilizer; + +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.object.Pair; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.api.util.ConfigUtils; +import org.bukkit.Particle; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.intellij.lang.annotations.Subst; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; + +public class FertilizerManager extends Function { + + private final CustomCrops plugin; + private final HashMap fertilizerConfigMap; + private final HashMap itemToKey; + + public FertilizerManager(CustomCrops plugin) { + this.plugin = plugin; + this.fertilizerConfigMap = new HashMap<>(); + this.itemToKey = new HashMap<>(); + } + + @Override + public void load() { + this.loadConfig(); + } + + @Override + public void unload() { + this.fertilizerConfigMap.clear(); + this.itemToKey.clear(); + } + + @Nullable + public FertilizerConfig getConfigByFertilizer(@Nullable Fertilizer fertilizer) { + if (fertilizer == null) return null; + return fertilizerConfigMap.get(fertilizer.getKey()); + } + + @Nullable + public FertilizerConfig getConfigByKey(String key) { + return fertilizerConfigMap.get(key); + } + + @Nullable + public FertilizerConfig getConfigByItemID(String id) { + String key = itemToKey.get(id); + if (key == null) return null; + return fertilizerConfigMap.get(id); + } + + private void loadConfig() { + File can_folder = new File(plugin.getDataFolder(), "contents" + File.separator + "fertilizers"); + if (!can_folder.exists()) { + if (!can_folder.mkdirs()) return; + plugin.saveResource("contents" + File.separator + "fertilizers" + File.separator + "speed-grow.yml", false); + plugin.saveResource("contents" + File.separator + "fertilizers" + File.separator + "quality.yml", false); + plugin.saveResource("contents" + File.separator + "fertilizers" + File.separator + "soil-retain.yml", false); + plugin.saveResource("contents" + File.separator + "fertilizers" + File.separator + "yield-increase.yml", false); + plugin.saveResource("contents" + File.separator + "fertilizers" + File.separator + "variation.yml", false); + } + File[] files = can_folder.listFiles(); + if (files == null) return; + for (File file : files) { + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + for (String key : config.getKeys(false)) { + ConfigurationSection fertilizerSec = config.getConfigurationSection(key); + if (fertilizerSec == null) continue; + FertilizerConfig fertilizerConfig; + FertilizerType fertilizerType = FertilizerType.valueOf(fertilizerSec.getString("type", "SPEED_GROW").toUpperCase()); + String[] pot_whitelist = fertilizerSec.contains("pot-whitelist") ? fertilizerSec.getStringList("pot-whitelist").toArray(new String[0]) : null; + boolean beforePlant = fertilizerSec.getBoolean("before-plant", false); + int times = fertilizerSec.getInt("times", 14); + Particle particle = fertilizerSec.contains("particle") ? Particle.valueOf(fertilizerSec.getString("particle")) : null; + @Subst("namespace:key") String soundKey = fertilizerSec.getString("sound", "minecraft:item.hoe.till"); + Sound sound = fertilizerSec.contains("sound") ? Sound.sound(Key.key(soundKey), Sound.Source.PLAYER, 1, 1) : null; + switch (fertilizerType) { + case SPEED_GROW -> fertilizerConfig = new SpeedGrow(key, fertilizerType, times, getChancePair(fertilizerSec), pot_whitelist, beforePlant, particle, sound); + case YIELD_INCREASE -> fertilizerConfig = new YieldIncrease(key, fertilizerType, times, fertilizerSec.getDouble("chance"), getChancePair(fertilizerSec), pot_whitelist, beforePlant, particle, sound); + case VARIATION -> fertilizerConfig = new Variation(key, fertilizerType, times, fertilizerSec.getDouble("chance"), pot_whitelist, beforePlant, particle, sound); + case QUALITY -> fertilizerConfig = new Quality(key, fertilizerType, times, fertilizerSec.getDouble("chance"), ConfigUtils.getQualityRatio(fertilizerSec.getString("ratio", "2/2/1")), pot_whitelist, beforePlant, particle, sound); + case SOIL_RETAIN -> fertilizerConfig = new SoilRetain(key, fertilizerType, times, fertilizerSec.getDouble("chance"), pot_whitelist, beforePlant, particle, sound); + default -> fertilizerConfig = null; + } + if (fertilizerConfig != null) + fertilizerConfigMap.put(key, fertilizerConfig); + else + AdventureUtils.consoleMessage("[CustomCrops] Invalid fertilizer: " + key); + } + } + AdventureUtils.consoleMessage("[CustomCrops] Loaded " + fertilizerConfigMap.size() + " fertilizer(s)"); + } + + public ArrayList> getChancePair(ConfigurationSection fertilizerSec) { + ArrayList> pairs = new ArrayList<>(); + ConfigurationSection effectSec = fertilizerSec.getConfigurationSection("effects"); + if (effectSec == null) return new ArrayList<>(); + for (String point : effectSec.getKeys(false)) { + Pair pair = new Pair<>(effectSec.getDouble(point), Integer.parseInt(point)); + pairs.add(pair); + } + return pairs; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fertilizer/FertilizerType.java b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/FertilizerType.java new file mode 100644 index 0000000..c897439 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/FertilizerType.java @@ -0,0 +1,9 @@ +package net.momirealms.customcrops.api.object.fertilizer; + +public enum FertilizerType { + SPEED_GROW, + QUALITY, + SOIL_RETAIN, + VARIATION, + YIELD_INCREASE +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fertilizer/Quality.java b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/Quality.java new file mode 100644 index 0000000..51683da --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/Quality.java @@ -0,0 +1,19 @@ +package net.momirealms.customcrops.api.object.fertilizer; + +import net.kyori.adventure.sound.Sound; +import org.bukkit.Particle; +import org.jetbrains.annotations.Nullable; + +public class Quality extends FertilizerConfig { + + private final double[] ratio; + + public Quality(String key, FertilizerType fertilizerType, int times, double chance, double[] ratio, @Nullable String[] pot_whitelist, boolean beforePlant, @Nullable Particle particle, @Nullable Sound sound) { + super(key, fertilizerType, times, chance, pot_whitelist, beforePlant, particle, sound); + this.ratio = ratio; + } + + public double[] getRatio() { + return ratio; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fertilizer/SoilRetain.java b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/SoilRetain.java new file mode 100644 index 0000000..2e89e09 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/SoilRetain.java @@ -0,0 +1,12 @@ +package net.momirealms.customcrops.api.object.fertilizer; + +import net.kyori.adventure.sound.Sound; +import org.bukkit.Particle; +import org.jetbrains.annotations.Nullable; + +public class SoilRetain extends FertilizerConfig { + + public SoilRetain(String key, FertilizerType fertilizerType, int times, double chance, @Nullable String[] pot_whitelist, boolean beforePlant, @Nullable Particle particle, @Nullable Sound sound) { + super(key, fertilizerType, times, chance, pot_whitelist, beforePlant, particle, sound); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fertilizer/SpeedGrow.java b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/SpeedGrow.java new file mode 100644 index 0000000..dd77d1c --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/SpeedGrow.java @@ -0,0 +1,31 @@ +package net.momirealms.customcrops.api.object.fertilizer; + +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.api.object.Pair; +import org.bukkit.Particle; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class SpeedGrow extends FertilizerConfig { + + private final List> pairs; + + public SpeedGrow(String key, FertilizerType fertilizerType, int times, List> pairs, @Nullable String[] pot_whitelist, boolean beforePlant, @Nullable Particle particle, @Nullable Sound sound) { + super(key, fertilizerType, times, 1, pot_whitelist, beforePlant, particle, sound); + this.pairs = pairs; + } + + public List> getPairs() { + return pairs; + } + + public int getPointBonus() { + for (Pair pair : pairs) { + if (Math.random() < pair.left()) { + return pair.right(); + } + } + return 0; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fertilizer/Variation.java b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/Variation.java new file mode 100644 index 0000000..58cb966 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/Variation.java @@ -0,0 +1,12 @@ +package net.momirealms.customcrops.api.object.fertilizer; + +import net.kyori.adventure.sound.Sound; +import org.bukkit.Particle; +import org.jetbrains.annotations.Nullable; + +public class Variation extends FertilizerConfig { + + public Variation(String key, FertilizerType fertilizerType, int times, double chance, @Nullable String[] pot_whitelist, boolean beforePlant, @Nullable Particle particle, @Nullable Sound sound) { + super(key, fertilizerType, times, chance, pot_whitelist, beforePlant, particle, sound); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fertilizer/YieldIncrease.java b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/YieldIncrease.java new file mode 100644 index 0000000..4f3d026 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fertilizer/YieldIncrease.java @@ -0,0 +1,31 @@ +package net.momirealms.customcrops.api.object.fertilizer; + +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.api.object.Pair; +import org.bukkit.Particle; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class YieldIncrease extends FertilizerConfig { + + private final List> pairs; + + public YieldIncrease(String key, FertilizerType fertilizerType, int times, double chance, List> pairs, @Nullable String[] pot_whitelist, boolean beforePlant, @Nullable Particle particle, @Nullable Sound sound) { + super(key, fertilizerType, times, chance, pot_whitelist, beforePlant, particle, sound); + this.pairs = pairs; + } + + public List> getPairs() { + return pairs; + } + + public int getAmountBonus() { + for (Pair pair : pairs) { + if (Math.random() < pair.left()) { + return pair.right(); + } + } + return 0; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fill/AbstractFillMethod.java b/src/main/java/net/momirealms/customcrops/api/object/fill/AbstractFillMethod.java new file mode 100644 index 0000000..3d3b4f4 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fill/AbstractFillMethod.java @@ -0,0 +1,32 @@ +package net.momirealms.customcrops.api.object.fill; + +import net.kyori.adventure.sound.Sound; +import org.bukkit.Particle; +import org.jetbrains.annotations.Nullable; + +public abstract class AbstractFillMethod { + + protected int amount; + protected Particle particle; + protected Sound sound; + + protected AbstractFillMethod(int amount, Particle particle, Sound sound) { + this.amount = amount; + this.particle = particle; + this.sound = sound; + } + + public int getAmount() { + return amount; + } + + @Nullable + public Particle getParticle() { + return particle; + } + + + public Sound getSound() { + return sound; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fill/PassiveFillMethod.java b/src/main/java/net/momirealms/customcrops/api/object/fill/PassiveFillMethod.java new file mode 100644 index 0000000..f1b9e0b --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fill/PassiveFillMethod.java @@ -0,0 +1,29 @@ +package net.momirealms.customcrops.api.object.fill; + +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.CustomCrops; +import org.bukkit.Particle; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class PassiveFillMethod extends AbstractFillMethod { + + private final String used; + private final String returned; + + public PassiveFillMethod(String used, @Nullable String returned, int amount, @Nullable Particle particle, @Nullable Sound sound) { + super(amount, particle, sound); + this.used = used; + this.returned = returned; + } + + public boolean isRightItem(String item_id) { + return used.equals(item_id); + } + + @Nullable + public ItemStack getReturnedItemStack() { + if (returned == null) return null; + return CustomCrops.getInstance().getIntegrationManager().build(returned); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/fill/PositiveFillMethod.java b/src/main/java/net/momirealms/customcrops/api/object/fill/PositiveFillMethod.java new file mode 100644 index 0000000..af6a1a5 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/fill/PositiveFillMethod.java @@ -0,0 +1,30 @@ +package net.momirealms.customcrops.api.object.fill; + +import net.kyori.adventure.sound.Sound; +import org.bukkit.Particle; + +public class PositiveFillMethod extends AbstractFillMethod { + + private final InteractType type; + private final String id; + + public PositiveFillMethod(InteractType type, String id, int amount, Particle particle, Sound sound) { + super(amount, particle, sound); + this.type = type; + this.id = id; + } + + public InteractType getType() { + return type; + } + + public String getId() { + return id; + } + + public enum InteractType { + BLOCK, + ENTITY, + MM + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/loot/Loot.java b/src/main/java/net/momirealms/customcrops/api/object/loot/Loot.java new file mode 100644 index 0000000..79160cc --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/loot/Loot.java @@ -0,0 +1,54 @@ +package net.momirealms.customcrops.api.object.loot; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.fertilizer.YieldIncrease; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import net.momirealms.customcrops.integration.SkillInterface; +import net.objecthunter.exp4j.Expression; +import net.objecthunter.exp4j.ExpressionBuilder; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.util.concurrent.ThreadLocalRandom; + +public abstract class Loot { + + public int min; + public int max; + + public Loot(int min, int max) { + this.min = min; + this.max = max; + } + + public void drop(Player player, Location location) { + //empty + } + + public int getMin() { + return min; + } + + public int getMax() { + return max; + } + + public int getAmount(Player player) { + int random = ThreadLocalRandom.current().nextInt(getMin(), getMax() + 1); + if (ConfigManager.enableSkillBonus && player != null) { + SkillInterface skillInterface = CustomCrops.getInstance().getIntegrationManager().getSkillInterface(); + if (skillInterface != null) { + int level = skillInterface.getLevel(player); + Expression expression = new ExpressionBuilder(ConfigManager.bonusFormula) + .variables("base", "level") + .build() + .setVariable("base", random) + .setVariable("level", level); + random = (int) expression.evaluate(); + } + } + return random; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/loot/OtherLoot.java b/src/main/java/net/momirealms/customcrops/api/object/loot/OtherLoot.java new file mode 100644 index 0000000..f26a9ce --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/loot/OtherLoot.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.loot; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.fertilizer.YieldIncrease; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class OtherLoot extends Loot { + + private final String itemID; + private final double chance; + + public OtherLoot(int min, int max, String itemID, double chance) { + super(min, max); + this.itemID = itemID; + this.chance = chance; + } + + public String getItemID() { + return itemID; + } + + public double getChance() { + return chance; + } + + public void drop(Player player, Location location) { + if (Math.random() < getChance()) { + int random = getAmount(player); + Pot pot = CustomCrops.getInstance().getWorldDataManager().getPotData(SimpleLocation.getByBukkitLocation(location).add(0,-1,0)); + if (pot != null && pot.getFertilizer() != null && pot.getFertilizer().getConfig() instanceof YieldIncrease increase) { + random += increase.getAmountBonus(); + } + ItemStack drop = CustomCrops.getInstance().getIntegrationManager().build(getItemID()); + if (drop.getType() == Material.AIR) return; + drop.setAmount(random); + location.getWorld().dropItemNaturally(location, drop); + } + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/loot/QualityLoot.java b/src/main/java/net/momirealms/customcrops/api/object/loot/QualityLoot.java new file mode 100644 index 0000000..429329d --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/loot/QualityLoot.java @@ -0,0 +1,55 @@ +package net.momirealms.customcrops.api.object.loot; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.fertilizer.FertilizerConfig; +import net.momirealms.customcrops.api.object.fertilizer.YieldIncrease; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.fertilizer.Quality; +import net.momirealms.customcrops.api.object.world.SimpleLocation; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class QualityLoot extends Loot { + + private final String quality_1; + private final String quality_2; + private final String quality_3; + + public QualityLoot(int min, int max, String quality_1, String quality_2, String quality_3) { + super(min, max); + this.quality_1 = quality_1; + this.quality_2 = quality_2; + this.quality_3 = quality_3; + } + + @Override + public void drop(Player player, Location location) { + SimpleLocation simpleLocation = SimpleLocation.getByBukkitLocation(location); + Pot pot = CustomCrops.getInstance().getWorldDataManager().getPotData(simpleLocation); + int amount = getAmount(player); + double[] qualityRatio = ConfigManager.defaultRatio; + if (pot != null) { + FertilizerConfig fertilizerConfig = CustomCrops.getInstance().getFertilizerManager().getConfigByFertilizer(pot.getFertilizer()); + if (fertilizerConfig instanceof Quality quality && quality.canTakeEffect()) { + qualityRatio = quality.getRatio(); + } else if (fertilizerConfig instanceof YieldIncrease increase) { + amount += increase.getAmountBonus(); + } + } + for (int i = 0; i < amount; i++) { + double random = Math.random(); + if (random < qualityRatio[0]) dropItem(location, quality_1); + else if (random > qualityRatio[1]) dropItem(location, quality_2); + else dropItem(location, quality_3); + } + } + + private void dropItem(Location location, String id) { + ItemStack drop = CustomCrops.getInstance().getIntegrationManager().build(id); + if (drop.getType() == Material.AIR) return; + location.getWorld().dropItemNaturally(location, drop); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/pot/Pot.java b/src/main/java/net/momirealms/customcrops/api/object/pot/Pot.java new file mode 100644 index 0000000..4deb801 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/pot/Pot.java @@ -0,0 +1,82 @@ +package net.momirealms.customcrops.api.object.pot; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.fertilizer.Fertilizer; +import org.jetbrains.annotations.NotNull; + +import java.io.Serializable; + +public class Pot implements Serializable { + + private Fertilizer fertilizer; + private int water; + private final String key; + + public Pot(String key, Fertilizer fertilizer, int water) { + this.key = key; + this.fertilizer = fertilizer; + this.water = water; + } + + public Fertilizer getFertilizer() { + return fertilizer; + } + + public void setFertilizer(Fertilizer fertilizer) { + this.fertilizer = fertilizer; + } + + public int getWater() { + return water; + } + + /* + whether to change block model + */ + public boolean addWater(int amount) { + if (water == 0) { + this.water = Math.min(getConfig().getMax_storage(), amount); + return true; + } + else { + this.water = Math.min(getConfig().getMax_storage(), water + amount); + return false; + } + } + + public void setWater(int amount) { + this.water = amount; + } + + /* + whether to change block model + */ + public boolean reduceWater() { + water--; + return water <= 0; + } + + /* + whether to change block model + */ + public boolean reduceFertilizer() { + if (this.fertilizer != null && fertilizer.reduceTimes()) { + this.fertilizer = null; + return true; + } + return false; + } + + public boolean isWet() { + return water != 0; + } + + @NotNull + public String getPotKey() { + return key; + } + + public PotConfig getConfig() { + return CustomCrops.getInstance().getPotManager().getPotConfig(key); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/pot/PotConfig.java b/src/main/java/net/momirealms/customcrops/api/object/pot/PotConfig.java new file mode 100644 index 0000000..7b0f916 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/pot/PotConfig.java @@ -0,0 +1,61 @@ +package net.momirealms.customcrops.api.object.pot; + +import net.momirealms.customcrops.api.object.Pair; +import net.momirealms.customcrops.api.object.fill.PassiveFillMethod; +import net.momirealms.customcrops.api.object.fertilizer.Fertilizer; +import net.momirealms.customcrops.api.object.fertilizer.FertilizerConfig; +import net.momirealms.customcrops.api.object.fertilizer.FertilizerType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; + +public class PotConfig { + + private final HashMap> fertilizerConvertMap; + private final int max_storage; + private final Pair pot; + private final boolean enableFertilized; + private final PassiveFillMethod[] passiveFillMethods; + + public PotConfig(int max_storage, String dry_pot, String wet_pot, boolean enableFertilized, @NotNull PassiveFillMethod[] passiveFillMethods) { + this.max_storage = max_storage; + this.pot = Pair.of(dry_pot, wet_pot); + this.enableFertilized = enableFertilized; + this.fertilizerConvertMap = new HashMap<>(); + this.passiveFillMethods = passiveFillMethods; + } + + public void registerFertilizedPot(FertilizerType fertilizerType, String dry_pot, String wet_pot) { + fertilizerConvertMap.put(fertilizerType, Pair.of(dry_pot, wet_pot)); + } + + public String getWetPot(@Nullable Fertilizer fertilizer) { + if (fertilizer == null || !enableFertilized) return pot.right(); + FertilizerConfig fertilizerConfig = fertilizer.getConfig(); + if (fertilizerConfig == null) return pot.right(); + FertilizerType fertilizerType = fertilizerConfig.getFertilizerType(); + Pair pair = fertilizerConvertMap.get(fertilizerType); + if (pair == null) return pot.right(); + else return pair.right(); + } + + public String getDryPot(@Nullable Fertilizer fertilizer) { + if (fertilizer == null || !enableFertilized) return pot.left(); + FertilizerConfig fertilizerConfig = fertilizer.getConfig(); + if (fertilizerConfig == null) return pot.left(); + FertilizerType fertilizerType = fertilizerConfig.getFertilizerType(); + Pair pair = fertilizerConvertMap.get(fertilizerType); + if (pair == null) return pot.left(); + else return pair.left(); + } + + public int getMax_storage() { + return max_storage; + } + + @NotNull + public PassiveFillMethod[] getPassiveFillMethods() { + return passiveFillMethods; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/pot/PotManager.java b/src/main/java/net/momirealms/customcrops/api/object/pot/PotManager.java new file mode 100644 index 0000000..a3aea8f --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/pot/PotManager.java @@ -0,0 +1,117 @@ +package net.momirealms.customcrops.api.object.pot; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.object.fertilizer.FertilizerType; +import net.momirealms.customcrops.api.object.fill.PassiveFillMethod; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.api.util.ConfigUtils; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.util.HashMap; + +public class PotManager extends Function { + + private final CustomCrops plugin; + private final HashMap potConfigMap; + private final HashMap blockToPotKey; + + public PotManager(CustomCrops plugin) { + this.plugin = plugin; + this.potConfigMap = new HashMap<>(); + this.blockToPotKey = new HashMap<>(); + } + + @Override + public void load() { + loadConfig(); + } + + @Override + public void unload() { + this.potConfigMap.clear(); + this.blockToPotKey.clear(); + } + + private void loadConfig() { + File pot_folder = new File(plugin.getDataFolder(), "contents" + File.separator + "pots"); + if (!pot_folder.exists()) { + if (!pot_folder.mkdirs()) return; + plugin.saveResource("contents" + File.separator + "pots" + File.separator + "default.yml", false); + } + File[] files = pot_folder.listFiles(); + if (files == null) return; + for (File file : files) { + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + for (String key : config.getKeys(false)) { + ConfigurationSection section = config.getConfigurationSection(key); + if (section == null) continue; + boolean enableFertilized = section.getBoolean("fertilized-pots.enable", false); + String base_dry = section.getString("base.dry"); + String base_wet = section.getString("base.wet"); + if (base_wet == null || base_dry == null) { + AdventureUtils.consoleMessage("[CustomCrops] base.dry/base.wet is not correctly set for pot: " + key); + continue; + } + PassiveFillMethod[] methods = ConfigUtils.getPassiveFillMethods(section.getConfigurationSection("fill-method")); + if (methods == null) { + AdventureUtils.consoleMessage("[CustomCrops] fill method is not set for pot: " + key); + continue; + } + blockToPotKey.put(base_wet, key); + blockToPotKey.put(base_dry, key); + PotConfig potConfig = new PotConfig( + section.getInt("max-water-storage"), + base_dry, + base_wet, + enableFertilized, + methods + ); + if (enableFertilized) { + ConfigurationSection fertilizedSec = section.getConfigurationSection("fertilized-pots"); + if (fertilizedSec == null) continue; + for (String type : fertilizedSec.getKeys(false)) { + if (type.equals("enable")) continue; + String dry = fertilizedSec.getString(type + ".dry"); + String wet = fertilizedSec.getString(type + ".wet"); + blockToPotKey.put(dry, key); + blockToPotKey.put(wet, key); + switch (type) { + case "quality" -> potConfig.registerFertilizedPot(FertilizerType.QUALITY, dry, wet); + case "yield-increase" -> potConfig.registerFertilizedPot(FertilizerType.YIELD_INCREASE, dry, wet); + case "variation" -> potConfig.registerFertilizedPot(FertilizerType.VARIATION, dry, wet); + case "soil-retain" -> potConfig.registerFertilizedPot(FertilizerType.SOIL_RETAIN, dry, wet); + case "speed-grow" -> potConfig.registerFertilizedPot(FertilizerType.SPEED_GROW, dry, wet); + } + } + } + potConfigMap.put(key, potConfig); + } + } + AdventureUtils.consoleMessage("[CustomCrops] Loaded " + potConfigMap.size() + " pot(s)"); + } + + public boolean containsPotBlock(String id) { + return blockToPotKey.containsKey(id); + } + + @Nullable + public PotConfig getPotConfig(String key) { + return potConfigMap.get(key); + } + + @Nullable + public String getPotKeyByBlockID(String id) { + return blockToPotKey.get(id); + } + + @Nullable + public PotConfig getPotConfigByBlockID(String id) { + String key = blockToPotKey.get(id); + if (key == null) return null; + return potConfigMap.get(key); + } +} diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/Requirement.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/AbstractRequirement.java similarity index 62% rename from src/main/java/net/momirealms/customcrops/objects/requirements/Requirement.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/AbstractRequirement.java index 2f68925..caacc0a 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/Requirement.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/AbstractRequirement.java @@ -15,27 +15,25 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements; +package net.momirealms.customcrops.api.object.requirement; -import net.momirealms.customcrops.utils.AdventureUtil; +import net.momirealms.customcrops.api.util.AdventureUtils; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public abstract class Requirement { +public abstract class AbstractRequirement { - protected String[] values; - protected boolean mode; - protected String msg; + protected String[] msg; - protected Requirement(@NotNull String[] values, boolean mode, @Nullable String msg) { - this.values = values; - this.mode = mode; + protected AbstractRequirement(@Nullable String[] msg) { this.msg = msg; } public void notMetMessage(Player player) { - if (msg == null) return; - AdventureUtil.playerMessage(player, this.msg); + if (msg != null && player != null) { + for (String str : msg) { + AdventureUtils.playerMessage(player, str); + } + } } } diff --git a/src/main/java/net/momirealms/customcrops/objects/actions/ActionSkillXP.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/BiomeImpl.java similarity index 51% rename from src/main/java/net/momirealms/customcrops/objects/actions/ActionSkillXP.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/BiomeImpl.java index d0a0f65..0a72cbb 100644 --- a/src/main/java/net/momirealms/customcrops/objects/actions/ActionSkillXP.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/BiomeImpl.java @@ -15,30 +15,29 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.actions; +package net.momirealms.customcrops.api.object.requirement; -import net.momirealms.customcrops.config.MainConfig; -import org.bukkit.entity.Player; +import net.momirealms.biomeapi.BiomeAPI; +import org.jetbrains.annotations.Nullable; -public class ActionSkillXP implements ActionInterface { +import java.util.HashSet; - private final double xp; - private final double chance; +public class BiomeImpl extends AbstractRequirement implements Requirement { - public ActionSkillXP(double xp, double chance) { - this.xp = xp; - this.chance = chance; + private final HashSet biomes; + + public BiomeImpl(@Nullable String[] msg, HashSet biomes) { + super(msg); + this.biomes = biomes; } @Override - public void performOn(Player player) { - if (MainConfig.skillInterface != null) { - MainConfig.skillInterface.addXp(player, xp); + public boolean isConditionMet(CurrentState currentState) { + String currentBiome = BiomeAPI.getBiome(currentState.getLocation()); + if (biomes.contains(currentBiome)) { + return true; } - } - - @Override - public double getChance() { - return chance; + notMetMessage(currentState.getPlayer()); + return false; } } diff --git a/src/main/java/net/momirealms/customcrops/objects/actions/ActionXP.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/CurrentState.java similarity index 63% rename from src/main/java/net/momirealms/customcrops/objects/actions/ActionXP.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/CurrentState.java index 67d174d..1034116 100644 --- a/src/main/java/net/momirealms/customcrops/objects/actions/ActionXP.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/CurrentState.java @@ -15,27 +15,26 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.actions; +package net.momirealms.customcrops.api.object.requirement; +import org.bukkit.Location; import org.bukkit.entity.Player; -public class ActionXP implements ActionInterface { +public class CurrentState { - private final int amount; - private final double chance; + private final Location location; + private final Player player; - public ActionXP(int amount, double chance) { - this.amount = amount; - this.chance = chance; + public CurrentState(Location crop_loc, Player player) { + this.location = crop_loc; + this.player = player; } - @Override - public void performOn(Player player) { - player.giveExp(amount); + public Location getLocation() { + return location; } - @Override - public double getChance() { - return chance; + public Player getPlayer() { + return player; } -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/requirement/CustomPapi.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/CustomPapi.java new file mode 100644 index 0000000..7d3878e --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/CustomPapi.java @@ -0,0 +1,80 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.requirement; + +import net.momirealms.customcrops.api.object.requirement.papi.*; +import org.bukkit.configuration.MemorySection; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class CustomPapi extends AbstractRequirement implements Requirement { + + private final List papiRequirement; + + public CustomPapi(String[] msg, Map expressions){ + super(msg); + papiRequirement = getRequirements(expressions); + } + + @Override + public boolean isConditionMet(CurrentState currentState) { + Player player = currentState.getPlayer(); + if (currentState.getPlayer() == null) return true; + for (PapiRequirement requirement : papiRequirement) { + if (!requirement.isMet(player)) { + notMetMessage(player); + return false; + } + } + return true; + } + + private List getRequirements(Map map) { + List papiRequirements = new ArrayList<>(); + map.keySet().forEach(key -> { + if (key.startsWith("&&")) { + if (map.get(key) instanceof MemorySection map2) { + papiRequirements.add(new ExpressionAnd(getRequirements(map2.getValues(false)))); + } + } else if (key.startsWith("||")) { + if (map.get(key) instanceof MemorySection map2) { + papiRequirements.add(new ExpressionOr(getRequirements(map2.getValues(false)))); + } + } else { + if (map.get(key) instanceof MemorySection map2) { + String type = map2.getString("type"); + String papi = map2.getString("papi"); + String value = map2.getString("value"); + if (value == null || papi == null || type == null) return; + switch (type){ + case "==" -> papiRequirements.add(new PapiEquals(papi, value)); + case "!=" -> papiRequirements.add(new PapiNotEquals(papi, value)); + case ">=" -> papiRequirements.add(new PapiNoLess(papi, value)); + case "<=" -> papiRequirements.add(new PapiNoLarger(papi, value)); + case "<" -> papiRequirements.add(new PapiSmaller(papi, value)); + case ">" -> papiRequirements.add(new PapiGreater(papi, value)); + } + } + } + }); + return papiRequirements; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/requirement/DateImpl.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/DateImpl.java new file mode 100644 index 0000000..2dbaf6e --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/DateImpl.java @@ -0,0 +1,25 @@ +package net.momirealms.customcrops.api.object.requirement; + +import java.util.Calendar; +import java.util.HashSet; + +public class DateImpl extends AbstractRequirement implements Requirement { + + private final HashSet dates; + + public DateImpl(String[] msg, HashSet dates) { + super(msg); + this.dates = dates; + } + + @Override + public boolean isConditionMet(CurrentState currentState) { + Calendar calendar = Calendar.getInstance(); + String current = (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DATE); + if (dates.contains(current)) { + return true; + } + notMetMessage(currentState.getPlayer()); + return false; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/requirement/JobLevelImpl.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/JobLevelImpl.java new file mode 100644 index 0000000..379cd02 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/JobLevelImpl.java @@ -0,0 +1,26 @@ +package net.momirealms.customcrops.api.object.requirement; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.integration.JobInterface; +import org.jetbrains.annotations.Nullable; + +public class JobLevelImpl extends AbstractRequirement implements Requirement { + + private final int level; + + public JobLevelImpl(@Nullable String[] msg, int level) { + super(msg); + this.level = level; + } + + @Override + public boolean isConditionMet(CurrentState currentState) { + JobInterface jobInterface = CustomCrops.getInstance().getIntegrationManager().getJobInterface(); + if (jobInterface == null || currentState.getPlayer() == null) return true; + if (jobInterface.getLevel(currentState.getPlayer()) >= level) { + return true; + } + notMetMessage(currentState.getPlayer()); + return false; + } +} diff --git a/src/main/java/net/momirealms/customcrops/objects/actions/ActionCommand.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/PermissionImpl.java similarity index 51% rename from src/main/java/net/momirealms/customcrops/objects/actions/ActionCommand.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/PermissionImpl.java index 72f8675..576b4d3 100644 --- a/src/main/java/net/momirealms/customcrops/objects/actions/ActionCommand.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/PermissionImpl.java @@ -15,30 +15,29 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.actions; +package net.momirealms.customcrops.api.object.requirement; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; -public class ActionCommand implements ActionInterface { +public class PermissionImpl extends AbstractRequirement implements Requirement { - private final String[] commands; - private final double chance; + private final String permission; - public ActionCommand(String[] commands, double chance) { - this.commands = commands; - this.chance = chance; + public PermissionImpl(@Nullable String[] msg, String permission) { + super(msg); + this.permission = permission; + } + + public String getPermission() { + return this.permission; } @Override - public void performOn(Player player) { - for (String command : commands) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName())); + public boolean isConditionMet(CurrentState currentState) { + if (currentState.getPlayer() == null || currentState.getPlayer().hasPermission(permission)) { + return true; } + notMetMessage(currentState.getPlayer()); + return false; } - - @Override - public double getChance() { - return chance; - } -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/objects/Function.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/Requirement.java similarity index 82% rename from src/main/java/net/momirealms/customcrops/objects/Function.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/Requirement.java index dc40a92..a2d177f 100644 --- a/src/main/java/net/momirealms/customcrops/objects/Function.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/Requirement.java @@ -15,13 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects; +package net.momirealms.customcrops.api.object.requirement; -public class Function { +public interface Requirement { - public void load() { - } - - public void unload() { - } + boolean isConditionMet(CurrentState currentState); } diff --git a/src/main/java/net/momirealms/customcrops/api/object/requirement/SeasonImpl.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/SeasonImpl.java new file mode 100644 index 0000000..c1ceae0 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/SeasonImpl.java @@ -0,0 +1,47 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.requirement; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.season.CCSeason; +import net.momirealms.customcrops.integration.SeasonInterface; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class SeasonImpl extends AbstractRequirement implements Requirement { + + private final List seasons; + + public SeasonImpl(@Nullable String[] msg, List seasons) { + super(msg); + this.seasons = seasons; + } + + @Override + public boolean isConditionMet(CurrentState currentState) { + SeasonInterface seasonInterface = CustomCrops.getInstance().getIntegrationManager().getSeasonInterface(); + if (seasonInterface == null) return true; + CCSeason currentSeason = seasonInterface.getSeason(currentState.getLocation().getWorld().getName()); + if (seasons.contains(currentSeason)) { + return true; + } + notMetMessage(currentState.getPlayer()); + return false; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/requirement/SkillLevelImpl.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/SkillLevelImpl.java new file mode 100644 index 0000000..823678f --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/SkillLevelImpl.java @@ -0,0 +1,26 @@ +package net.momirealms.customcrops.api.object.requirement; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.integration.SkillInterface; +import org.jetbrains.annotations.Nullable; + +public class SkillLevelImpl extends AbstractRequirement implements Requirement { + + private final int level; + + public SkillLevelImpl(@Nullable String[] msg, int level) { + super(msg); + this.level = level; + } + + @Override + public boolean isConditionMet(CurrentState currentState) { + SkillInterface skillInterface = CustomCrops.getInstance().getIntegrationManager().getSkillInterface(); + if (skillInterface == null || currentState.getPlayer() == null) return true; + if (skillInterface.getLevel(currentState.getPlayer()) >= level) { + return true; + } + notMetMessage(currentState.getPlayer()); + return false; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/requirement/TimeImpl.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/TimeImpl.java new file mode 100644 index 0000000..e9ddd38 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/TimeImpl.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.requirement; + +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class TimeImpl extends AbstractRequirement implements Requirement { + + private final List times; + + public TimeImpl(@Nullable String[] msg, List times) { + super(msg); + this.times = times; + } + + @Override + public boolean isConditionMet(CurrentState currentState) { + long time = currentState.getLocation().getWorld().getTime(); + for (String range : times) { + String[] timeMinMax = range.split("~"); + if (time > Long.parseLong(timeMinMax[0]) && time < Long.parseLong(timeMinMax[1])) { + return true; + } + } + notMetMessage(currentState.getPlayer()); + return false; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/requirement/WeatherImpl.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/WeatherImpl.java new file mode 100644 index 0000000..4daff49 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/WeatherImpl.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.object.requirement; + +import org.bukkit.World; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class WeatherImpl extends AbstractRequirement implements Requirement { + + private final List weathers; + + public WeatherImpl(@Nullable String[] msg, List weathers) { + super(msg); + this.weathers = weathers; + } + + @Override + public boolean isConditionMet(CurrentState currentState) { + World world = currentState.getLocation().getWorld(); + String currentWeather; + if (world.isThundering()) currentWeather = "thunder"; + else if (world.isClearWeather()) currentWeather = "clear"; + else currentWeather = "rain"; + for (String weather : weathers) { + if (weather.equalsIgnoreCase(currentWeather)) { + return true; + } + } + notMetMessage(currentState.getPlayer()); + return false; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/utils/WorldUtils.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/WorldImpl.java similarity index 53% rename from src/main/java/net/momirealms/customcrops/api/utils/WorldUtils.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/WorldImpl.java index 1e7220c..06899f8 100644 --- a/src/main/java/net/momirealms/customcrops/api/utils/WorldUtils.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/WorldImpl.java @@ -15,28 +15,29 @@ * along with this program. If not, see . */ +package net.momirealms.customcrops.api.object.requirement; -package net.momirealms.customcrops.api.utils; - -import net.momirealms.customcrops.CustomCrops; import org.bukkit.World; +import org.jetbrains.annotations.Nullable; -public class WorldUtils { +import java.util.List; - /** - * load a world's crop data - * @param world world - */ - public static void loadCropWorld(World world) { - CustomCrops.plugin.getCropManager().onWorldLoad(world); +public class WorldImpl extends AbstractRequirement implements Requirement { + + private final List worlds; + + public WorldImpl(@Nullable String[] msg, List worlds) { + super(msg); + this.worlds = worlds; } - /** - * unload a world's crop data - * @param world world - * @param sync whether unload is sync or async - */ - public static void unloadCropWorld(World world, boolean sync) { - CustomCrops.plugin.getCropManager().onWorldUnload(world, sync); + @Override + public boolean isConditionMet(CurrentState currentState) { + World world = currentState.getLocation().getWorld(); + if (worlds.contains(world.getName())) { + return true; + } + notMetMessage(currentState.getPlayer()); + return false; } -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementWorld.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/YPosImpl.java similarity index 56% rename from src/main/java/net/momirealms/customcrops/objects/requirements/RequirementWorld.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/YPosImpl.java index baaea20..e92cefd 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementWorld.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/YPosImpl.java @@ -15,26 +15,31 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements; +package net.momirealms.customcrops.api.object.requirement; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class RequirementWorld extends Requirement implements RequirementInterface { +import java.util.List; - public RequirementWorld(@NotNull String[] values, boolean mode, @Nullable String msg) { - super(values, mode, msg); +public class YPosImpl extends AbstractRequirement implements Requirement { + + private final List yPos; + + public YPosImpl(@Nullable String[] msg, List yPos) { + super(msg); + this.yPos = yPos; } @Override - public boolean isConditionMet(PlayerCondition playerCondition) { - String worldName = playerCondition.getLocation().getWorld().getName(); - for (String value : values) { - if (value.equals(worldName)) { + public boolean isConditionMet(CurrentState currentState) { + int y = (int) currentState.getLocation().getY(); + for (String range : yPos) { + String[] yMinMax = range.split("~"); + if (y > Integer.parseInt(yMinMax[0]) && y < Integer.parseInt(yMinMax[1])) { return true; } } - notMetMessage(playerCondition.getPlayer()); + notMetMessage(currentState.getPlayer()); return false; } } \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/ExpressionAnd.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/ExpressionAnd.java similarity index 80% rename from src/main/java/net/momirealms/customcrops/objects/requirements/papi/ExpressionAnd.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/papi/ExpressionAnd.java index 05bdfff..6381c00 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/ExpressionAnd.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/ExpressionAnd.java @@ -15,19 +15,18 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements.papi; +package net.momirealms.customcrops.api.object.requirement.papi; import org.bukkit.entity.Player; -import java.util.HashMap; import java.util.List; public record ExpressionAnd(List requirements) implements PapiRequirement{ @Override - public boolean isMet(HashMap papiMap, Player player) { + public boolean isMet(Player player) { for (PapiRequirement requirement : requirements) { - if (!requirement.isMet(papiMap, player)) return false; + if (!requirement.isMet(player)) return false; } return true; } diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/ExpressionOr.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/ExpressionOr.java similarity index 80% rename from src/main/java/net/momirealms/customcrops/objects/requirements/papi/ExpressionOr.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/papi/ExpressionOr.java index cc01373..5b491d0 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/ExpressionOr.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/ExpressionOr.java @@ -15,19 +15,18 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements.papi; +package net.momirealms.customcrops.api.object.requirement.papi; import org.bukkit.entity.Player; -import java.util.HashMap; import java.util.List; public record ExpressionOr(List requirements) implements PapiRequirement{ @Override - public boolean isMet(HashMap papiMap, Player player) { + public boolean isMet(Player player) { for (PapiRequirement requirement : requirements) { - if (requirement.isMet(papiMap, player)) return true; + if (requirement.isMet(player)) return true; } return false; } diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiEquals.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiEquals.java similarity index 82% rename from src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiEquals.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiEquals.java index 60cd62f..2fae860 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiEquals.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiEquals.java @@ -15,19 +15,18 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements.papi; +package net.momirealms.customcrops.api.object.requirement.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; -import java.util.HashMap; import java.util.Objects; public record PapiEquals(String papi, String requirement) implements PapiRequirement{ @Override - public boolean isMet(HashMap papiMap, Player player) { - String value = papiMap.get(papi); + public boolean isMet(Player player) { + String value = PlaceholderAPI.setPlaceholders(player, papi); return Objects.equals(value, PlaceholderAPI.setPlaceholders(player, requirement)); } } diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiGreater.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiGreater.java similarity index 81% rename from src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiGreater.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiGreater.java index a58fea6..f8919db 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiGreater.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiGreater.java @@ -15,18 +15,16 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements.papi; +package net.momirealms.customcrops.api.object.requirement.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; -import java.util.HashMap; - public record PapiGreater(String papi, String requirement) implements PapiRequirement{ @Override - public boolean isMet(HashMap papiMap, Player player) { - double value = Double.parseDouble(papiMap.get(papi)); + public boolean isMet(Player player) { + double value = Double.parseDouble(PlaceholderAPI.setPlaceholders(player, papi)); return value > Double.parseDouble(PlaceholderAPI.setPlaceholders(player, requirement)); } } diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiNoLarger.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiNoLarger.java similarity index 81% rename from src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiNoLarger.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiNoLarger.java index 863290b..004016a 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiNoLarger.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiNoLarger.java @@ -15,18 +15,16 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements.papi; +package net.momirealms.customcrops.api.object.requirement.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; -import java.util.HashMap; - public record PapiNoLarger(String papi, String requirement) implements PapiRequirement{ @Override - public boolean isMet(HashMap papiMap, Player player) { - double value = Double.parseDouble(papiMap.get(papi)); + public boolean isMet(Player player) { + double value = Double.parseDouble(PlaceholderAPI.setPlaceholders(player, papi)); return value <= Double.parseDouble(PlaceholderAPI.setPlaceholders(player, requirement)); } } diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiNoLess.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiNoLess.java similarity index 81% rename from src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiNoLess.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiNoLess.java index 72f68ce..cefc664 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiNoLess.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiNoLess.java @@ -15,18 +15,16 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements.papi; +package net.momirealms.customcrops.api.object.requirement.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; -import java.util.HashMap; - public record PapiNoLess(String papi, String requirement) implements PapiRequirement{ @Override - public boolean isMet(HashMap papiMap, Player player) { - double value = Double.parseDouble(papiMap.get(papi)); + public boolean isMet(Player player) { + double value = Double.parseDouble(PlaceholderAPI.setPlaceholders(player, papi)); return value >= Double.parseDouble(PlaceholderAPI.setPlaceholders(player, requirement)); } } diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiNotEquals.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiNotEquals.java similarity index 82% rename from src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiNotEquals.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiNotEquals.java index 95555b3..ecebf26 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiNotEquals.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiNotEquals.java @@ -15,19 +15,18 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements.papi; +package net.momirealms.customcrops.api.object.requirement.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; -import java.util.HashMap; import java.util.Objects; public record PapiNotEquals(String papi, String requirement) implements PapiRequirement{ @Override - public boolean isMet(HashMap papiMap, Player player) { - String value = papiMap.get(papi); + public boolean isMet(Player player) { + String value = PlaceholderAPI.setPlaceholders(player, papi); return !Objects.equals(value, PlaceholderAPI.setPlaceholders(player, requirement)); } } \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiRequirement.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiRequirement.java similarity index 82% rename from src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiRequirement.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiRequirement.java index a2eb97b..1aa9df0 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiRequirement.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiRequirement.java @@ -15,12 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements.papi; +package net.momirealms.customcrops.api.object.requirement.papi; import org.bukkit.entity.Player; -import java.util.HashMap; - public interface PapiRequirement { - boolean isMet(HashMap papiMap, Player player); + boolean isMet(Player player); } diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiSmaller.java b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiSmaller.java similarity index 81% rename from src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiSmaller.java rename to src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiSmaller.java index 85a577d..6040540 100644 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/papi/PapiSmaller.java +++ b/src/main/java/net/momirealms/customcrops/api/object/requirement/papi/PapiSmaller.java @@ -15,18 +15,16 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.requirements.papi; +package net.momirealms.customcrops.api.object.requirement.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; -import java.util.HashMap; - public record PapiSmaller(String papi, String requirement) implements PapiRequirement{ @Override - public boolean isMet(HashMap papiMap, Player player) { - double value = Double.parseDouble(papiMap.get(papi)); + public boolean isMet(Player player) { + double value = Double.parseDouble(PlaceholderAPI.setPlaceholders(player, papi)); return value < Double.parseDouble(PlaceholderAPI.setPlaceholders(player, requirement)); } } diff --git a/src/main/java/net/momirealms/customcrops/objects/fertilizer/Gigantic.java b/src/main/java/net/momirealms/customcrops/api/object/season/CCSeason.java similarity index 60% rename from src/main/java/net/momirealms/customcrops/objects/fertilizer/Gigantic.java rename to src/main/java/net/momirealms/customcrops/api/object/season/CCSeason.java index 6db0c8b..7025339 100644 --- a/src/main/java/net/momirealms/customcrops/objects/fertilizer/Gigantic.java +++ b/src/main/java/net/momirealms/customcrops/api/object/season/CCSeason.java @@ -15,16 +15,26 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.fertilizer; +package net.momirealms.customcrops.api.object.season; -public class Gigantic extends Fertilizer{ +import net.momirealms.customcrops.api.object.basic.MessageManager; - public Gigantic(String key, int times, double chance, boolean before, String name) { - super(key, times, chance, before, name); +public enum CCSeason { + + SPRING(MessageManager.spring), + SUMMER(MessageManager.summer), + AUTUMN(MessageManager.autumn), + WINTER(MessageManager.winter), + UNKNOWN(MessageManager.noSeason); + + private final String display; + + CCSeason(String display) { + this.display = display; } @Override - public Fertilizer getWithTimes(int times) { - return new Gigantic(this.key, times, this.chance, this.before, this.name); + public String toString() { + return display; } } diff --git a/src/main/java/net/momirealms/customcrops/api/object/season/SeasonData.java b/src/main/java/net/momirealms/customcrops/api/object/season/SeasonData.java new file mode 100644 index 0000000..53876b0 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/season/SeasonData.java @@ -0,0 +1,60 @@ +package net.momirealms.customcrops.api.object.season; + +import net.momirealms.customcrops.api.object.basic.ConfigManager; + +public class SeasonData { + + private CCSeason ccSeason; + private int date; + private final String world; + + public SeasonData(String world, CCSeason ccSeason, int date) { + this.world = world; + this.ccSeason = ccSeason; + this.date = date; + } + + public SeasonData(String world) { + this.world = world; + this.ccSeason = CCSeason.SPRING; + this.date = 1; + } + + public CCSeason getSeason() { + return ccSeason; + } + + public int getDate() { + return date; + } + + public void addDate() { + this.date++; + if (date > ConfigManager.seasonInterval) { + this.date = 1; + this.ccSeason = getNextSeason(ccSeason); + } + } + + public CCSeason getNextSeason(CCSeason ccSeason) { + return switch (ccSeason) { + case AUTUMN -> CCSeason.WINTER; + case WINTER -> CCSeason.SPRING; + case SPRING -> CCSeason.SUMMER; + case SUMMER -> CCSeason.AUTUMN; + default -> CCSeason.UNKNOWN; + }; + } + + public void changeSeason(CCSeason ccSeason) { + this.ccSeason = ccSeason; + } + + public String getWorld() { + return world; + } + + public void setDate(int date) { + this.date = date; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/season/SeasonManager.java b/src/main/java/net/momirealms/customcrops/api/object/season/SeasonManager.java new file mode 100644 index 0000000..e2197dd --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/season/SeasonManager.java @@ -0,0 +1,56 @@ +package net.momirealms.customcrops.api.object.season; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.integration.SeasonInterface; +import org.jetbrains.annotations.Nullable; + +import java.util.concurrent.ConcurrentHashMap; + +public class SeasonManager extends Function { + + private final CustomCrops plugin; + private final ConcurrentHashMap seasonMap; + + public SeasonManager(CustomCrops plugin) { + this.plugin = plugin; + this.seasonMap = new ConcurrentHashMap<>(4); + } + + @Override + public void disable() { + this.seasonMap.clear(); + } + + @Nullable + public SeasonData getSeasonData(String world) { + return seasonMap.get(world); + } + + public void loadSeasonData(SeasonData seasonData) { + seasonMap.put(seasonData.getWorld(), seasonData); + } + + @Nullable + public SeasonData unloadSeasonData(String world) { + return seasonMap.remove(world); + } + + public CCSeason getSeason(String world) { + SeasonData seasonData = seasonMap.get(world); + if (seasonData == null) return CCSeason.UNKNOWN; + return seasonData.getSeason(); + } + + public void addDate(String world) { + SeasonData seasonData = seasonMap.get(world); + if (seasonData != null) seasonData.addDate(); + } + + public int getDate(String world) { + SeasonData seasonData = seasonMap.get(world); + if (seasonData == null) return -1; + return seasonData.getDate(); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/sprinkler/Sprinkler.java b/src/main/java/net/momirealms/customcrops/api/object/sprinkler/Sprinkler.java new file mode 100644 index 0000000..e73303a --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/sprinkler/Sprinkler.java @@ -0,0 +1,30 @@ +package net.momirealms.customcrops.api.object.sprinkler; + +import java.io.Serializable; + +public class Sprinkler implements Serializable { + + private int water; + private int range; + + public Sprinkler(int water, int range) { + this.water = water; + this.range = range; + } + + public int getWater() { + return water; + } + + public void setWater(int water) { + this.water = water; + } + + public void setRange(int range) { + this.range = range; + } + + public int getRange() { + return range; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/sprinkler/SprinklerConfig.java b/src/main/java/net/momirealms/customcrops/api/object/sprinkler/SprinklerConfig.java new file mode 100644 index 0000000..05b0132 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/sprinkler/SprinklerConfig.java @@ -0,0 +1,67 @@ +package net.momirealms.customcrops.api.object.sprinkler; + +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.fill.PassiveFillMethod; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class SprinklerConfig { + + private final String key; + private final int storage; + private final int range; + private final Sound sound; + private final ItemMode itemMode; + private final String threeD; + private final String twoD; + private final PassiveFillMethod[] passiveFillMethods; + + public SprinklerConfig(String key, int storage, int range, @Nullable Sound sound, @NotNull ItemMode itemMode, @NotNull String threeD, @NotNull String twoD, @NotNull PassiveFillMethod[] passiveFillMethods) { + this.key = key; + this.storage = storage; + this.range = range; + this.sound = sound; + this.itemMode = itemMode; + this.threeD = threeD; + this.twoD = twoD; + this.passiveFillMethods = passiveFillMethods; + } + + public String getKey() { + return key; + } + + public int getStorage() { + return storage; + } + + public int getRange() { + return range; + } + + @Nullable + public Sound getSound() { + return sound; + } + + @NotNull + public ItemMode getItemMode() { + return itemMode; + } + + @NotNull + public String getThreeD() { + return threeD; + } + + @NotNull + public String getTwoD() { + return twoD; + } + + @NotNull + public PassiveFillMethod[] getPassiveFillMethods() { + return passiveFillMethods; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/sprinkler/SprinklerManager.java b/src/main/java/net/momirealms/customcrops/api/object/sprinkler/SprinklerManager.java new file mode 100644 index 0000000..094ec2e --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/sprinkler/SprinklerManager.java @@ -0,0 +1,127 @@ +package net.momirealms.customcrops.api.object.sprinkler; + +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.fill.PassiveFillMethod; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.api.util.ConfigUtils; +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Item; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.ItemSpawnEvent; +import org.bukkit.inventory.ItemStack; +import org.intellij.lang.annotations.Subst; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.util.HashMap; + +public class SprinklerManager extends Function implements Listener { + + private final CustomCrops plugin; + private final HashMap sprinklerConfigMap; + private final HashMap itemToKey; + + public SprinklerManager(CustomCrops plugin) { + this.plugin = plugin; + this.sprinklerConfigMap = new HashMap<>(); + this.itemToKey = new HashMap<>(); + } + + @Override + public void load() { + this.loadConfig(); + Bukkit.getPluginManager().registerEvents(this, plugin); + } + + @Override + public void unload() { + this.sprinklerConfigMap.clear(); + this.itemToKey.clear(); + HandlerList.unregisterAll(this); + } + + private void loadConfig() { + File sprinkler_folder = new File(plugin.getDataFolder(), "contents" + File.separator + "sprinklers"); + if (!sprinkler_folder.exists()) { + if (!sprinkler_folder.mkdirs()) return; + plugin.saveResource("contents" + File.separator + "sprinklers" + File.separator + "default.yml", false); + } + File[] files = sprinkler_folder.listFiles(); + if (files == null) return; + for (File file : files) { + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + for (String key : config.getKeys(false)) { + ConfigurationSection sprinklerSec = config.getConfigurationSection(key); + if (sprinklerSec == null) continue; + String twoD = sprinklerSec.getString("2D-item"); + String threeD = sprinklerSec.getString("3D-item"); + if (twoD == null || threeD == null) { + AdventureUtils.consoleMessage("[CustomCrops] 2/3D-item is not set for sprinkler: " + key); + continue; + } + PassiveFillMethod[] methods = ConfigUtils.getPassiveFillMethods(sprinklerSec.getConfigurationSection("fill-method")); + if (methods == null) { + AdventureUtils.consoleMessage("[CustomCrops] fill method is not set for sprinkler: " + key); + continue; + } + @Subst("namespace:key") String soundKey = sprinklerSec.getString("place-sound", "minecraft:block.bone_block.place"); + Sound sound = sprinklerSec.contains("place-sound") ? Sound.sound(Key.key(soundKey), Sound.Source.PLAYER, 1, 1) : null; + ItemMode itemMode = ItemMode.valueOf(sprinklerSec.getString("type","ITEM_FRAME").toUpperCase()); + SprinklerConfig sprinklerConfig = new SprinklerConfig( + key, + sprinklerSec.getInt("storage", 3), + sprinklerSec.getInt("range", 1), + sound, + itemMode, + threeD, + twoD, + methods + ); + this.itemToKey.put(threeD, key); + this.itemToKey.put(twoD, key); + this.sprinklerConfigMap.put(key, sprinklerConfig); + } + } + AdventureUtils.consoleMessage("[CustomCrops] Loaded " + sprinklerConfigMap.size() + " sprinkler(s)"); + } + + @Nullable + public SprinklerConfig getConfigByItemID(String id) { + String key = itemToKey.get(id); + if (key == null) return null; + return sprinklerConfigMap.get(key); + } + + @Nullable + public String getConfigKeyByItemID(String id) { + return itemToKey.get(id); + } + + public boolean containsSprinkler(String key) { + return sprinklerConfigMap.containsKey(key); + } + + @EventHandler + public void onItemSpawn(ItemSpawnEvent event) { + if (event.isCancelled()) return; + Item item = event.getEntity(); + String id = plugin.getPlatformInterface().getItemID(item.getItemStack()); + String key = itemToKey.get(id); + if (key == null) return; + String twoD = sprinklerConfigMap.get(key).getTwoD(); + ItemStack itemStack = plugin.getPlatformInterface().getItemStack(twoD); + if (itemStack == null) { + AdventureUtils.consoleMessage("[CustomCrops] 2D sprinkler " + twoD + " doesn't exist"); + return; + } + item.setItemStack(itemStack); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/wateringcan/WateringCanConfig.java b/src/main/java/net/momirealms/customcrops/api/object/wateringcan/WateringCanConfig.java new file mode 100644 index 0000000..717e956 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/wateringcan/WateringCanConfig.java @@ -0,0 +1,121 @@ +package net.momirealms.customcrops.api.object.wateringcan; + +import net.kyori.adventure.sound.Sound; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.momirealms.customcrops.api.object.fill.PositiveFillMethod; +import org.bukkit.Particle; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class WateringCanConfig { + + private final int width; + private final int length; + private final int storage; + private final String[] pot_whitelist; + private final String[] sprinkler_whitelist; + private final boolean hasDynamicLore; + private final boolean hasActionBar; + private final Sound sound; + private final Particle particle; + private final List loreTemplate; + private final String actionBarMsg; + private final String bar_left; + private final String bar_full; + private final String bar_empty; + private final String bar_right; + private final PositiveFillMethod[] positiveFillMethods; + + public WateringCanConfig(int width, int length, int storage, + boolean hasDynamicLore, boolean hasActionBar, @Nullable List loreTemplate, @Nullable String actionBarMsg, + @Nullable String bar_left, @Nullable String bar_full, @Nullable String bar_empty, @Nullable String bar_right, + String[] pot_whitelist, String[] sprinkler_whitelist, @Nullable Sound sound, @Nullable Particle particle, @NotNull PositiveFillMethod[] positiveFillMethods) { + this.width = width; + this.length = length; + this.storage = storage; + this.hasDynamicLore = hasDynamicLore; + this.hasActionBar = hasActionBar; + this.loreTemplate = loreTemplate; + this.actionBarMsg = actionBarMsg; + this.bar_left = bar_left; + this.bar_full = bar_full; + this.bar_empty = bar_empty; + this.bar_right = bar_right; + this.pot_whitelist = pot_whitelist; + this.sprinkler_whitelist = sprinkler_whitelist; + this.sound = sound; + this.particle = particle; + this.positiveFillMethods = positiveFillMethods; + } + + public int getWidth() { + return width; + } + + public int getLength() { + return length; + } + + public int getStorage() { + return storage; + } + + public String getWaterBar(int current) { + return bar_left + + String.valueOf(bar_full).repeat(current) + + String.valueOf(bar_empty).repeat(storage - current) + + bar_right; + } + + public boolean hasDynamicLore() { + return hasDynamicLore; + } + + public boolean hasActionBar() { + return hasActionBar; + } + + public String getActionBarMsg(int current) { + assert actionBarMsg != null; + return actionBarMsg + .replace("{current}", String.valueOf(current)) + .replace("{storage}", String.valueOf(storage)) + .replace("{water_bar}", getWaterBar(current)); + } + + public List getLore(int current) { + assert loreTemplate != null; + return loreTemplate.stream().map(line -> + GsonComponentSerializer.gson().serialize( + MiniMessage.miniMessage().deserialize(line + .replace("{current}", String.valueOf(current)) + .replace("{storage}", String.valueOf(storage)) + .replace("{water_bar}", getWaterBar(current))))).toList(); + } + + public String[] getPotWhitelist() { + return pot_whitelist; + } + + public String[] getSprinklerWhitelist() { + return sprinkler_whitelist; + } + + @Nullable + public Sound getSound() { + return sound; + } + + @Nullable + public Particle getParticle() { + return particle; + } + + @NotNull + public PositiveFillMethod[] getPositiveFillMethods() { + return positiveFillMethods; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/wateringcan/WateringCanManager.java b/src/main/java/net/momirealms/customcrops/api/object/wateringcan/WateringCanManager.java new file mode 100644 index 0000000..b3f8fe7 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/wateringcan/WateringCanManager.java @@ -0,0 +1,111 @@ +package net.momirealms.customcrops.api.object.wateringcan; + +import de.tr7zw.changeme.nbtapi.NBTCompound; +import de.tr7zw.changeme.nbtapi.NBTItem; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.object.fill.PositiveFillMethod; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.api.util.ConfigUtils; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.ItemStack; +import org.intellij.lang.annotations.Subst; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.util.HashMap; +import java.util.List; + +public class WateringCanManager extends Function { + + private final CustomCrops plugin; + private final HashMap wateringCanConfigMap; + + public WateringCanManager(CustomCrops plugin) { + this.plugin = plugin; + this.wateringCanConfigMap = new HashMap<>(); + } + + @Override + public void load() { + loadConfig(); + } + + @Override + public void unload() { + this.wateringCanConfigMap.clear(); + } + + @Nullable + public WateringCanConfig getConfigByItemID(String id) { + return wateringCanConfigMap.get(id); + } + + private void loadConfig() { + File can_folder = new File(plugin.getDataFolder(), "contents" + File.separator + "watering-cans"); + if (!can_folder.exists()) { + if (!can_folder.mkdirs()) return; + plugin.saveResource("contents" + File.separator + "watering-cans" + File.separator + "default.yml", false); + } + File[] files = can_folder.listFiles(); + if (files == null) return; + for (File file : files) { + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + for (String key : config.getKeys(false)) { + ConfigurationSection canSec = config.getConfigurationSection(key); + if (canSec == null) continue; + PositiveFillMethod[] methods = ConfigUtils.getPositiveFillMethods(canSec.getConfigurationSection("fill-method")); + if (methods == null) { + AdventureUtils.consoleMessage("[CustomCrops] You need to at least one fill-method for: " + key); + continue; + } + @Subst("namespace:key") String soundKey = canSec.getString("sound", "minecraft:block.water.ambient"); + Sound sound = canSec.contains("sound") ? Sound.sound(Key.key(soundKey), Sound.Source.PLAYER, 1, 1) : null; + WateringCanConfig wateringCanConfig = new WateringCanConfig( + canSec.getInt("effective-range.width"), + canSec.getInt("effective-range.length"), + canSec.getInt("capacity"), + canSec.getBoolean("dynamic-lore.enable", false), + canSec.getBoolean("actionbar.enable", false), + canSec.getStringList("dynamic-lore.lore"), + canSec.getString("actionbar.content"), + canSec.getString("water-bar.left"), + canSec.getString("water-bar.full"), + canSec.getString("water-bar.empty"), + canSec.getString("water-bar.right"), + canSec.contains("pot-whitelist") ? canSec.getStringList("pot-whitelist").toArray(new String[0]) : null, + canSec.contains("sprinkler-whitelist") ? canSec.getStringList("sprinkler-whitelist").toArray(new String[0]) : null, + sound, + canSec.contains("particle") ? Particle.valueOf(canSec.getString("particle", "WATER_SPLASH").toUpperCase()) : null, + methods + ); + wateringCanConfigMap.put(canSec.getString("item"), wateringCanConfig); + } + } + AdventureUtils.consoleMessage("[CustomCrops] Loaded " + wateringCanConfigMap.size() + " watering-can(s)"); + } + + public int getCurrentWater(ItemStack itemStack) { + if (itemStack.getType() == Material.AIR) return 0; + NBTItem nbtItem = new NBTItem(itemStack); + return nbtItem.getInteger("WaterAmount"); + } + + public void setWater(ItemStack itemStack, int water, WateringCanConfig config) { + if (itemStack.getType() == Material.AIR) return; + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setInteger("WaterAmount", water); + if (config.hasDynamicLore()) { + NBTCompound display = nbtItem.getCompound("display"); + List lore = display.getStringList("Lore"); + lore.clear(); + lore.addAll(config.getLore(water)); + } + itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/world/CCChunk.java b/src/main/java/net/momirealms/customcrops/api/object/world/CCChunk.java new file mode 100644 index 0000000..83982d4 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/world/CCChunk.java @@ -0,0 +1,166 @@ +package net.momirealms.customcrops.api.object.world; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.CustomCropsAPI; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.crop.GrowingCrop; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.fertilizer.Fertilizer; +import net.momirealms.customcrops.api.object.sprinkler.Sprinkler; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.Serializable; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadLocalRandom; + +public class CCChunk implements Serializable { + + private final ConcurrentHashMap growingCropMap; + private final ConcurrentHashMap potMap; + private final ConcurrentHashMap sprinklerMap; + private final Set greenhouseSet; + private final Set scarecrowSet; + + public CCChunk() { + this.growingCropMap = new ConcurrentHashMap<>(64); + this.potMap = new ConcurrentHashMap<>(64); + this.sprinklerMap = new ConcurrentHashMap<>(16); + this.greenhouseSet = Collections.synchronizedSet(new HashSet<>(64)); + this.scarecrowSet = Collections.synchronizedSet(new HashSet<>(4)); + } + + public void removeCropData(SimpleLocation simpleLocation) { + growingCropMap.remove(simpleLocation); + } + + public void addCropData(SimpleLocation simpleLocation, GrowingCrop growingCrop) { + growingCropMap.put(simpleLocation, growingCrop); + } + + @Nullable + public GrowingCrop getCropData(SimpleLocation simpleLocation) { + return growingCropMap.get(simpleLocation); + } + + public int getCropAmount() { + return growingCropMap.size(); + } + + @Nullable + public Pot getPotData(SimpleLocation simpleLocation) { + return potMap.get(simpleLocation); + } + + public void addPotData(SimpleLocation simpleLocation, Pot pot) { + potMap.put(simpleLocation, pot); + } + + public void removePotData(SimpleLocation simpleLocation) { + potMap.remove(simpleLocation); + } + + public void addGreenhouse(SimpleLocation simpleLocation) { + greenhouseSet.add(simpleLocation); + } + + public void removeGreenhouse(SimpleLocation simpleLocation) { + greenhouseSet.remove(simpleLocation); + } + + public boolean isGreenhouse(SimpleLocation simpleLocation) { + return greenhouseSet.contains(simpleLocation); + } + + public void addScarecrow(SimpleLocation simpleLocation) { + scarecrowSet.add(simpleLocation); + } + + public void removeScarecrow(SimpleLocation simpleLocation) { + scarecrowSet.remove(simpleLocation); + } + + public boolean hasScarecrow() { + return scarecrowSet.size() != 0; + } + + public boolean isUseless() { + return growingCropMap.size() == 0 && potMap.size() == 0 && greenhouseSet.size() == 0 && sprinklerMap.size() == 0 && scarecrowSet.size() == 0; + } + + @Nullable + public Sprinkler getSprinklerData(SimpleLocation simpleLocation) { + return sprinklerMap.get(simpleLocation); + } + + public void removeSprinklerData(SimpleLocation simpleLocation) { + sprinklerMap.remove(simpleLocation); + } + + public void addSprinklerData(SimpleLocation simpleLocation, Sprinkler sprinkler) { + sprinklerMap.put(simpleLocation, sprinkler); + } + + public void addWaterToPot(SimpleLocation simpleLocation, int amount, @Nullable String pot_id) { + Pot pot = potMap.get(simpleLocation); + if (pot != null) { + if (pot.addWater(amount)) { + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + CustomCropsAPI.getInstance().changePotModel(simpleLocation, pot); + return null; + }); + } + } + else if (pot_id != null) { + Pot newPot = new Pot(pot_id, null, amount); + potMap.put(simpleLocation, newPot); + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + CustomCropsAPI.getInstance().changePotModel(simpleLocation, newPot); + return null; + }); + } + } + + public void addFertilizerToPot(SimpleLocation simpleLocation, Fertilizer fertilizer, @NotNull String pot_id) { + Pot pot = potMap.get(simpleLocation); + if (pot != null) { + pot.setFertilizer(fertilizer); + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + CustomCropsAPI.getInstance().changePotModel(simpleLocation, pot); + return null; + }); + } + else { + Pot newPot = new Pot(pot_id, fertilizer, 0); + potMap.put(simpleLocation, newPot); + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + CustomCropsAPI.getInstance().changePotModel(simpleLocation, newPot); + return null; + }); + } + } + + public void scheduleGrowTask(CCWorld ccWorld) { + Random randomGenerator = ThreadLocalRandom.current(); + for (SimpleLocation simpleLocation : growingCropMap.keySet()) { + ccWorld.pushCropTask(simpleLocation, randomGenerator.nextInt(ConfigManager.pointGainInterval)); + } + } + + public void scheduleSprinklerTask(CCWorld ccWorld) { + Random randomGenerator = ThreadLocalRandom.current(); + for (SimpleLocation simpleLocation : sprinklerMap.keySet()) { + ccWorld.pushSprinklerTask(simpleLocation, randomGenerator.nextInt(30)); + } + } + + public void scheduleConsumeTask(CCWorld ccWorld) { + Random randomGenerator = ThreadLocalRandom.current(); + for (SimpleLocation simpleLocation : potMap.keySet()) { + ccWorld.pushConsumeTask(simpleLocation, randomGenerator.nextInt(60)); + } + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/world/CCWorld.java b/src/main/java/net/momirealms/customcrops/api/object/world/CCWorld.java new file mode 100644 index 0000000..37857a9 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/world/CCWorld.java @@ -0,0 +1,685 @@ +package net.momirealms.customcrops.api.object.world; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.CustomCropsAPI; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.object.action.Action; +import net.momirealms.customcrops.api.object.action.VariationImpl; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.condition.Condition; +import net.momirealms.customcrops.api.object.condition.DeathCondition; +import net.momirealms.customcrops.api.object.crop.CropConfig; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.crop.GrowingCrop; +import net.momirealms.customcrops.api.object.crop.StageConfig; +import net.momirealms.customcrops.api.object.crop.VariationCrop; +import net.momirealms.customcrops.api.object.fertilizer.*; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.season.CCSeason; +import net.momirealms.customcrops.api.object.season.SeasonData; +import net.momirealms.customcrops.api.object.sprinkler.Sprinkler; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.api.util.ConfigUtils; +import net.momirealms.customcrops.helper.Log; +import org.apache.commons.pool2.BasePooledObjectFactory; +import org.apache.commons.pool2.PooledObject; +import org.apache.commons.pool2.impl.DefaultPooledObject; +import org.apache.commons.pool2.impl.GenericObjectPool; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.*; +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +import java.util.Map; +import java.util.concurrent.*; + +public class CCWorld extends Function { + + private final String worldName; + private final Reference world; + private final ConcurrentHashMap chunkMap; + private final ScheduledThreadPoolExecutor schedule; + private final GenericObjectPool cropTaskPool; + private final GenericObjectPool sprinklerTaskPool; + private final GenericObjectPool consumeTaskPool; + private boolean hasWorkedToday; + private boolean hasConsumedToday; + + public CCWorld(World world) { + this.world = new WeakReference<>(world); + this.worldName = world.getName(); + this.chunkMap = new ConcurrentHashMap<>(64); + this.schedule = new ScheduledThreadPoolExecutor(ConfigManager.corePoolSize); + this.schedule.setMaximumPoolSize(ConfigManager.maxPoolSize); + this.schedule.setKeepAliveTime(ConfigManager.keepAliveTime, TimeUnit.SECONDS); + this.schedule.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); + this.cropTaskPool = new GenericObjectPool<>(new CropTaskFactory(), new GenericObjectPoolConfig<>()); + this.cropTaskPool.setMaxTotal(10); + this.cropTaskPool.setMinIdle(1); + this.sprinklerTaskPool = new GenericObjectPool<>(new SprinklerTaskFactory(), new GenericObjectPoolConfig<>()); + this.sprinklerTaskPool.setMaxTotal(10); + this.sprinklerTaskPool.setMinIdle(1); + this.consumeTaskPool = new GenericObjectPool<>(new ConsumeTaskFactory(), new GenericObjectPoolConfig<>()); + this.consumeTaskPool.setMaxTotal(10); + this.consumeTaskPool.setMinIdle(1); + this.hasConsumedToday = false; + this.hasWorkedToday = false; + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + public void load() { + File chunks_folder = new File(CustomCrops.getInstance().getDataFolder().getParentFile().getParentFile(), ConfigManager.worldFolderPath + worldName + File.separator + "customcrops" + File.separator + "chunks"); + if (!chunks_folder.exists()) chunks_folder.mkdirs(); + File[] data_files = chunks_folder.listFiles(); + if (data_files == null) return; + for (File file : data_files) { + ChunkCoordinate chunkCoordinate = ChunkCoordinate.getByString(file.getName().substring(0, file.getName().length() - 7)); + try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis)) { + CCChunk chunk = (CCChunk) ois.readObject(); + if (chunk.isUseless()) { + file.delete(); + continue; + } + if (chunkCoordinate != null) chunkMap.put(chunkCoordinate, chunk); + } catch (IOException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + if (ConfigManager.enableSeason && !ConfigManager.rsHook) { + YamlConfiguration seasonDataFile = ConfigUtils.readData(new File(CustomCrops.getInstance().getDataFolder().getParentFile().getParentFile(), ConfigManager.worldFolderPath + worldName + File.separator + "customcrops" + File.separator + "data.yml")); + SeasonData seasonData; + if (seasonDataFile.contains("season") && seasonDataFile.contains("date")) { + seasonData = new SeasonData(worldName, CCSeason.valueOf(seasonDataFile.getString("season")), seasonDataFile.getInt("date")); + } else { + seasonData = new SeasonData(worldName); + } + CustomCrops.getInstance().getSeasonManager().loadSeasonData(seasonData); + } + this.arrangeTask(); + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + public void unload() { + closePool(); + File chunks_folder = new File(CustomCrops.getInstance().getDataFolder().getParentFile().getParentFile(), ConfigManager.worldFolderPath + worldName + File.separator + "customcrops" + File.separator + "chunks"); + if (!chunks_folder.exists()) chunks_folder.mkdirs(); + for (Map.Entry entry : chunkMap.entrySet()) { + ChunkCoordinate chunkCoordinate = entry.getKey(); + CCChunk chunk = entry.getValue(); + String fileName = chunkCoordinate.getFileName() + ".ccdata"; + File file = new File(chunks_folder, fileName); + if (chunk.isUseless() && file.exists()) { + file.delete(); + continue; + } + try (FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos)) { + oos.writeObject(chunk); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (ConfigManager.enableSeason && !ConfigManager.rsHook) { + YamlConfiguration seasonDataFile = new YamlConfiguration(); + SeasonData seasonData = CustomCrops.getInstance().getSeasonManager().unloadSeasonData(worldName); + if (seasonData == null) { + seasonDataFile.set("season", "SPRING"); + seasonDataFile.set("date", 1); + } else { + seasonDataFile.set("season", seasonData.getSeason().name()); + seasonDataFile.set("date", seasonData.getDate()); + } + try { + seasonDataFile.save(new File(CustomCrops.getInstance().getDataFolder().getParentFile().getParentFile(), ConfigManager.worldFolderPath + worldName + File.separator + "customcrops" + File.separator + "data.yml")); + } catch (IOException e) { + AdventureUtils.consoleMessage("[CustomCrops] Failed to save season data for world: " + worldName); + } + } + } + + /** + * Some season plugin would change the length of a day + * So a flag is needed to ensure that all the function would only work once + */ + private void arrangeTask() { + this.schedule.scheduleAtFixedRate(() -> { + World current = world.get(); + if (current != null) { + long time = current.getTime(); + if (time < 100 && !hasConsumedToday) { + hasConsumedToday = true; + if (ConfigManager.enableSeason && !ConfigManager.rsHook && ConfigManager.autoSeasonChange) { + CustomCrops.getInstance().getSeasonManager().addDate(worldName); + } + if (ConfigManager.enableScheduleSystem) { + schedule.schedule(() -> { + for (CCChunk chunk : chunkMap.values()) { + chunk.scheduleConsumeTask(this); + } + }, 0, TimeUnit.SECONDS); + } + } + else if (time > 1950 && time < 2050 && !hasWorkedToday) { + hasWorkedToday = true; + if (ConfigManager.enableScheduleSystem) { + schedule.schedule(() -> { + for (CCChunk chunk : chunkMap.values()) { + chunk.scheduleSprinklerTask(this); + } + }, 0, TimeUnit.SECONDS); + } + } + else if (time > 23900) { + hasConsumedToday = false; + hasWorkedToday = false; + } + } + else { + this.schedule.shutdown(); + } + }, 2, 2, TimeUnit.SECONDS); + + this.schedule.scheduleAtFixedRate(() -> { + for (CCChunk chunk : chunkMap.values()) { + chunk.scheduleGrowTask(this); + } + }, 1, ConfigManager.pointGainInterval, TimeUnit.SECONDS); + } + + private void closePool() { + this.schedule.shutdown(); + } + + public void pushCropTask(SimpleLocation simpleLocation, int delay) { + schedule.schedule(new ScheduledCropTask(simpleLocation), delay, TimeUnit.SECONDS); + } + + public void pushSprinklerTask(SimpleLocation simpleLocation, int delay) { + schedule.schedule(new ScheduledSprinklerTask(simpleLocation), delay, TimeUnit.SECONDS); + } + + public void pushConsumeTask(SimpleLocation simpleLocation, int delay) { + schedule.schedule(new ScheduledConsumeTask(simpleLocation), delay, TimeUnit.SECONDS); + } + + public abstract static class ScheduledTask implements Runnable { + + SimpleLocation simpleLocation; + + public ScheduledTask(SimpleLocation simpleLocation) { + this.simpleLocation = simpleLocation; + } + } + + public class ScheduledCropTask extends ScheduledTask { + + public ScheduledCropTask(SimpleLocation simpleLocation) { + super(simpleLocation); + } + + @Override + public void run() { + try { + CropCheckTask cropCheckTask = cropTaskPool.borrowObject(); + GrowingCrop growingCrop = getCropData(simpleLocation); + if (growingCrop == null) return; + cropCheckTask.setArgs(simpleLocation, growingCrop); + cropCheckTask.execute(); + cropTaskPool.returnObject(cropCheckTask); + } + catch (Exception e) { + e.printStackTrace(); + } + } + } + + public class ScheduledConsumeTask extends ScheduledTask { + + public ScheduledConsumeTask(SimpleLocation simpleLocation) { + super(simpleLocation); + } + + @Override + public void run() { + try { + ConsumeCheckTask consumeCheckTask = consumeTaskPool.borrowObject(); + Pot pot = getPotData(simpleLocation); + if (pot == null) return; + consumeCheckTask.setArgs(simpleLocation, pot); + consumeCheckTask.execute(); + consumeTaskPool.returnObject(consumeCheckTask); + } + catch (Exception e) { + e.printStackTrace(); + } + } + } + + public class ScheduledSprinklerTask extends ScheduledTask { + + public ScheduledSprinklerTask(SimpleLocation simpleLocation) { + super(simpleLocation); + } + + @Override + public void run() { + try { + SprinklerCheckTask sprinklerCheckTask = sprinklerTaskPool.borrowObject(); + Sprinkler sprinkler = getSprinklerData(simpleLocation); + if (sprinkler == null) return; + sprinklerCheckTask.setArgs(simpleLocation, sprinkler); + sprinklerCheckTask.execute(); + sprinklerTaskPool.returnObject(sprinklerCheckTask); + } + catch (Exception e) { + e.printStackTrace(); + } + } + } + + public class ConsumeCheckTask { + + private SimpleLocation simpleLocation; + private Pot pot; + + public void setArgs(SimpleLocation simpleLocation, Pot pot) { + this.simpleLocation = simpleLocation; + this.pot = pot; + } + + public void execute() { + if (pot != null) { + if (pot.isWet() && CustomCrops.getInstance().getFertilizerManager().getConfigByFertilizer(pot.getFertilizer()) instanceof SoilRetain soilRetain && soilRetain.canTakeEffect()) { + pot.setWater(pot.getWater() + 1); + } + if (pot.reduceWater() | pot.reduceFertilizer()) { + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + CustomCropsAPI.getInstance().changePotModel(simpleLocation, pot); + return null; + }); + } + } + } + + public void clear() { + this.simpleLocation = null; + this.pot = null; + } + } + + public class SprinklerCheckTask { + + private SimpleLocation simpleLocation; + private Sprinkler sprinkler; + + public void setArgs(SimpleLocation simpleLocation, Sprinkler sprinkler) { + this.simpleLocation = simpleLocation; + this.sprinkler = sprinkler; + } + + public void execute() { + int water = sprinkler.getWater(); + if (water > 0) { + sprinkler.setWater(--water); + if (water == 0) { + removeSprinklerData(simpleLocation); + } + int range = sprinkler.getRange(); + for (int i = -range; i <= range; i++) { + for (int j = -range; j <= range; j++) { + addWaterToPot(simpleLocation.add(i, -1, j), 1, null); + } + } + } + else { + removeSprinklerData(simpleLocation); + } + } + + public void clear() { + this.simpleLocation = null; + this.sprinkler = null; + } + } + + public class CropCheckTask { + + private SimpleLocation simpleLocation; + private GrowingCrop growingCrop; + + public void setArgs(SimpleLocation simpleLocation, GrowingCrop growingCrop) { + this.simpleLocation = simpleLocation; + this.growingCrop = growingCrop; + } + + public void execute() { + + CropConfig cropConfig = growingCrop.getConfig(); + if (cropConfig == null) { + removeCropData(simpleLocation); + return; + } + + ItemMode itemMode = cropConfig.getCropMode(); + DeathCondition[] deathConditions = cropConfig.getDeathConditions(); + if (deathConditions != null) { + for (DeathCondition deathCondition : deathConditions) { + if (deathCondition.checkIfDead(simpleLocation)) { + removeCropData(simpleLocation); + deathCondition.applyDeadModel(simpleLocation, itemMode); + return; + } + } + } + + Condition[] conditions = cropConfig.getGrowConditions(); + if (conditions != null) { + for (Condition condition : conditions) { + if (!condition.isMet(simpleLocation)) { + return; + } + } + } + + int points = 1; + Pot pot = CustomCrops.getInstance().getWorldDataManager().getPotData(simpleLocation.add(0,-1,0)); + if (pot != null) { + FertilizerConfig fertilizerConfig = CustomCrops.getInstance().getFertilizerManager().getConfigByFertilizer(pot.getFertilizer()); + if (fertilizerConfig instanceof SpeedGrow speedGrow) { + points += speedGrow.getPointBonus(); + } + } + addCropPoint(points, cropConfig, growingCrop, simpleLocation, itemMode); + } + + public void clear() { + simpleLocation = null; + growingCrop = null; + } + } + + public boolean addCropPointAt(SimpleLocation simpleLocation, int points) { + GrowingCrop growingCrop = getCropData(simpleLocation); + if (growingCrop == null) return false; + CropConfig cropConfig = growingCrop.getConfig(); + if (cropConfig == null) { + removeCropData(simpleLocation); + return false; + } + if (points == 0) return true; + addCropPoint(points, cropConfig, growingCrop, simpleLocation, cropConfig.getCropMode()); + return true; + } + + public void addCropPoint(int points, CropConfig cropConfig, GrowingCrop growingCrop, SimpleLocation simpleLocation, ItemMode itemMode) { + int current = growingCrop.getPoints(); + String nextModel = null; + for (int i = current + 1; i <= points + current; i++) { + StageConfig stageConfig = cropConfig.getStageConfig(i); + if (stageConfig == null) continue; + if (stageConfig.getModel() != null) nextModel = stageConfig.getModel(); + Action[] growActions = stageConfig.getGrowActions(); + if (growActions != null) { + for (Action action : growActions) { + if (action instanceof VariationImpl variation) { + if (variation.doOn(simpleLocation, itemMode)) { + return; + } + } else { + action.doOn(null, simpleLocation, itemMode); + } + } + } + } + + growingCrop.setPoints(current + points); + if (ConfigManager.debug) Log.info(simpleLocation.toString() + ":" + growingCrop.getPoints()); + if (growingCrop.getPoints() >= cropConfig.getMax_points()) { + removeCropData(simpleLocation); + } + + Location location = simpleLocation.getBukkitLocation(); + String finalNextModel = nextModel; + if (finalNextModel == null || location == null) return; + CompletableFuture asyncGetChunk = location.getWorld().getChunkAtAsync(location.getBlockX() >> 4, location.getBlockZ() >> 4); + if (itemMode == ItemMode.ITEM_FRAME || itemMode == ItemMode.ITEM_DISPLAY) { + CompletableFuture loadEntities = asyncGetChunk.thenApply((chunk) -> { + chunk.getEntities(); + return chunk.isEntitiesLoaded(); + }); + loadEntities.whenComplete((result, throwable) -> + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + if (CustomCropsAPI.getInstance().removeCustomItem(location, itemMode)) { + CustomCropsAPI.getInstance().placeCustomItem(location, finalNextModel, itemMode); + } else { + removeCropData(simpleLocation); + } + return null; + })); + } + else { + asyncGetChunk.whenComplete((result, throwable) -> + Bukkit.getScheduler().callSyncMethod(CustomCrops.getInstance(), () -> { + if (CustomCropsAPI.getInstance().removeCustomItem(location, itemMode)) { + CustomCropsAPI.getInstance().placeCustomItem(location, finalNextModel, itemMode); + } else { + removeCropData(simpleLocation); + } + return null; + })); + } + } + + private class CropTaskFactory extends BasePooledObjectFactory { + + @Override + public CropCheckTask create() { + return new CropCheckTask(); + } + + @Override + public PooledObject wrap(CropCheckTask obj) { + return new DefaultPooledObject<>(obj); + } + + @Override + public void passivateObject(PooledObject obj) { + obj.getObject().clear(); + } + } + + private class SprinklerTaskFactory extends BasePooledObjectFactory { + + @Override + public SprinklerCheckTask create() { + return new SprinklerCheckTask(); + } + + @Override + public PooledObject wrap(SprinklerCheckTask obj) { + return new DefaultPooledObject<>(obj); + } + + @Override + public void passivateObject(PooledObject obj) { + obj.getObject().clear(); + } + } + + private class ConsumeTaskFactory extends BasePooledObjectFactory { + + @Override + public ConsumeCheckTask create() { + return new ConsumeCheckTask(); + } + + @Override + public PooledObject wrap(ConsumeCheckTask obj) { + return new DefaultPooledObject<>(obj); + } + + @Override + public void passivateObject(PooledObject obj) { + obj.getObject().clear(); + } + } + + public String getWorldName() { + return worldName; + } + + public World getWorld() { + return world.get(); + } + + public void removePotData(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk == null) return; + chunk.removePotData(simpleLocation); + } + + public void removeCropData(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk == null) return; + chunk.removeCropData(simpleLocation); + } + + public void addCropData(SimpleLocation simpleLocation, GrowingCrop growingCrop) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk != null) { + chunk.addCropData(simpleLocation, growingCrop); + return; + } + chunk = createNewChunk(simpleLocation); + chunk.addCropData(simpleLocation, growingCrop); + } + + public GrowingCrop getCropData(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk != null) { + return chunk.getCropData(simpleLocation); + } + return null; + } + + public int getChunkCropAmount(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk == null) return 0; + return chunk.getCropAmount(); + } + + public void removeGreenhouse(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk == null) return; + chunk.removeGreenhouse(simpleLocation); + } + + public void addGreenhouse(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk != null) { + chunk.addGreenhouse(simpleLocation); + return; + } + chunk = createNewChunk(simpleLocation); + chunk.addGreenhouse(simpleLocation); + } + + public boolean isGreenhouse(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk == null) return false; + return chunk.isGreenhouse(simpleLocation); + } + + public void removeScarecrow(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk == null) return; + chunk.removeScarecrow(simpleLocation); + } + + public void addScarecrow(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk != null) { + chunk.addScarecrow(simpleLocation); + return; + } + chunk = createNewChunk(simpleLocation); + chunk.addScarecrow(simpleLocation); + } + + public boolean hasScarecrow(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk == null) return false; + return chunk.hasScarecrow(); + } + + public void removeSprinklerData(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk == null) return; + chunk.removeSprinklerData(simpleLocation); + } + + public void addSprinklerData(SimpleLocation simpleLocation, Sprinkler sprinkler) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk != null) { + chunk.addSprinklerData(simpleLocation, sprinkler); + return; + } + chunk = createNewChunk(simpleLocation); + chunk.addSprinklerData(simpleLocation, sprinkler); + } + + @Nullable + public Sprinkler getSprinklerData(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk == null) return null; + return chunk.getSprinklerData(simpleLocation); + } + + public void addWaterToPot(SimpleLocation simpleLocation, int amount, @Nullable String pot_id) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk != null) { + chunk.addWaterToPot(simpleLocation, amount, pot_id); + return; + } + chunk = createNewChunk(simpleLocation); + chunk.addWaterToPot(simpleLocation, amount, pot_id); + } + + public void addFertilizerToPot(SimpleLocation simpleLocation, Fertilizer fertilizer, @NotNull String pot_id) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk != null) { + chunk.addFertilizerToPot(simpleLocation, fertilizer, pot_id); + return; + } + chunk = createNewChunk(simpleLocation); + chunk.addFertilizerToPot(simpleLocation, fertilizer, pot_id); + } + + public Pot getPotData(SimpleLocation simpleLocation) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk == null) return null; + return chunk.getPotData(simpleLocation); + } + + public void addPotData(SimpleLocation simpleLocation, Pot pot) { + CCChunk chunk = chunkMap.get(simpleLocation.getChunkCoordinate()); + if (chunk != null) { + chunk.addPotData(simpleLocation, pot); + return; + } + chunk = createNewChunk(simpleLocation); + chunk.addPotData(simpleLocation, pot); + } + + public CCChunk createNewChunk(SimpleLocation simpleLocation) { + CCChunk newChunk = new CCChunk(); + chunkMap.put(simpleLocation.getChunkCoordinate(), newChunk); + return newChunk; + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/world/ChunkCoordinate.java b/src/main/java/net/momirealms/customcrops/api/object/world/ChunkCoordinate.java new file mode 100644 index 0000000..ad45240 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/world/ChunkCoordinate.java @@ -0,0 +1,72 @@ +package net.momirealms.customcrops.api.object.world; + +import org.bukkit.Chunk; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.Serializable; + +public class ChunkCoordinate implements Serializable { + + private final int x; + private final int z; + + public ChunkCoordinate(int x, int z) { + this.x = x; + this.z = z; + } + + public int getX() { + return x; + } + + public int getZ() { + return z; + } + + public String getFileName() { + return x + "," + z; + } + + @Override + public int hashCode() { + long combined = (long) x << 32 | z; + return Long.hashCode(combined); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ChunkCoordinate other = (ChunkCoordinate) obj; + if (this.x != other.x) { + return false; + } + if (this.z != other.z) { + return false; + } + return true; + } + + @Nullable + public static ChunkCoordinate getByString(@NotNull String str) { + String[] split = str.split(",", 2); + try { + int x = Integer.parseInt(split[0]); + int z = Integer.parseInt(split[1]); + return new ChunkCoordinate(x, z); + } + catch (NumberFormatException e) { + return null; + } + } + + @NotNull + public static ChunkCoordinate getByBukkitChunk(@NotNull Chunk chunk) { + return new ChunkCoordinate(chunk.getX(), chunk.getZ()); + } +} diff --git a/src/main/java/net/momirealms/customcrops/objects/SimpleLocation.java b/src/main/java/net/momirealms/customcrops/api/object/world/SimpleLocation.java similarity index 55% rename from src/main/java/net/momirealms/customcrops/objects/SimpleLocation.java rename to src/main/java/net/momirealms/customcrops/api/object/world/SimpleLocation.java index e984185..ac9021d 100644 --- a/src/main/java/net/momirealms/customcrops/objects/SimpleLocation.java +++ b/src/main/java/net/momirealms/customcrops/api/object/world/SimpleLocation.java @@ -15,11 +15,18 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects; +package net.momirealms.customcrops.api.object.world; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.jetbrains.annotations.Nullable; + +import java.io.Serializable; import java.util.Objects; -public class SimpleLocation { +public class SimpleLocation implements Serializable { private final int x; private final int y; @@ -33,10 +40,29 @@ public class SimpleLocation { this.z = z; } - public int getX() {return x;} - public int getZ() {return z;} - public int getY() {return y;} - public String getWorldName() {return worldName;} + public int getX() { + return x; + } + + public int getZ() { + return z; + } + + public int getY() { + return y; + } + + public String getWorldName() { + return worldName; + } + + public ChunkCoordinate getChunkCoordinate() { + return new ChunkCoordinate(x >> 4, z >> 4); + } + + public SimpleLocation add(int x, int y, int z) { + return new SimpleLocation(worldName, this.x + x, this.y + y, this.z + z); + } @Override public boolean equals(Object obj) { @@ -65,10 +91,36 @@ public class SimpleLocation { @Override public int hashCode() { int hash = 3; - hash = 19 * hash + (worldName != null ? worldName.hashCode() : 0); + //hash = 19 * hash + (worldName != null ? worldName.hashCode() : 0); hash = 19 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32)); hash = 19 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32)); hash = 19 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32)); return hash; } + + @Nullable + public Location getBukkitLocation() { + World world = Bukkit.getWorld(worldName); + if (world == null) return null; + return new Location(world, x, y, z); + } + + @Nullable + public World getBukkitWorld() { + return Bukkit.getWorld(worldName); + } + + public static SimpleLocation getByString(String location, String world) { + String[] loc = StringUtils.split(location, ","); + return new SimpleLocation(world, Integer.parseInt(loc[0]), Integer.parseInt(loc[1]), Integer.parseInt(loc[2])); + } + + public static SimpleLocation getByBukkitLocation(Location location) { + return new SimpleLocation(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); + } + + @Override + public String toString() { + return "[" + worldName + "," + x + "," + y + "," + z + "]"; + } } \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/object/world/WorldDataManager.java b/src/main/java/net/momirealms/customcrops/api/object/world/WorldDataManager.java new file mode 100644 index 0000000..2331473 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/world/WorldDataManager.java @@ -0,0 +1,211 @@ +package net.momirealms.customcrops.api.object.world; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.crop.CropConfig; +import net.momirealms.customcrops.api.object.crop.GrowingCrop; +import net.momirealms.customcrops.api.object.pot.Pot; +import net.momirealms.customcrops.api.object.fertilizer.Fertilizer; +import net.momirealms.customcrops.api.object.sprinkler.Sprinkler; +import net.momirealms.customcrops.api.object.sprinkler.SprinklerConfig; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.Nullable; + +import java.util.concurrent.ConcurrentHashMap; + +public class WorldDataManager extends Function { + + private final ConcurrentHashMap worldMap; + private final CustomCrops plugin; + private final WorldListener worldListener; + + public WorldDataManager(CustomCrops plugin) { + this.plugin = plugin; + this.worldMap = new ConcurrentHashMap<>(); + this.worldListener = new WorldListener(this); + } + + @Override + public void load() { + Bukkit.getPluginManager().registerEvents(worldListener, plugin); + } + + @Override + public void unload() { + HandlerList.unregisterAll(worldListener); + } + + @Override + public void disable() { + for (CCWorld ccWorld : worldMap.values()) { + ccWorld.unload(); + } + this.worldMap.clear(); + } + + public void loadWorld(World world) { + if (!isWorldAllowed(world)) return; + CCWorld ccWorld = new CCWorld(world); + ccWorld.load(); + worldMap.put(world.getName(), ccWorld); + } + + public void unloadWorld(World world) { + CCWorld ccWorld = worldMap.remove(world.getName()); + if (ccWorld != null) { + ccWorld.unload(); + } + } + + public void removeCropData(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.removeCropData(simpleLocation); + } + } + + public void addCropData(SimpleLocation simpleLocation, GrowingCrop growingCrop) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.addCropData(simpleLocation, growingCrop); + } + } + + public int getChunkCropAmount(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + return ccWorld.getChunkCropAmount(simpleLocation); + } + return -1; + } + + public void removeGreenhouse(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.removeGreenhouse(simpleLocation); + } + } + + public void addGreenhouse(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.addGreenhouse(simpleLocation); + } + } + + public boolean isGreenhouse(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + return ccWorld.isGreenhouse(simpleLocation); + } + return false; + } + + public boolean isWorldAllowed(World world) { + return ConfigManager.whiteListWorlds == ConfigManager.worldList.contains(world.getName()); + } + + public void removePotData(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.removePotData(simpleLocation); + } + } + + public void removeSprinklerData(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.removeSprinklerData(simpleLocation); + } + } + + @Nullable + public Sprinkler getSprinklerData(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + return ccWorld.getSprinklerData(simpleLocation); + } + return null; + } + + public void addSprinklerData(SimpleLocation simpleLocation, Sprinkler sprinkler) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.addSprinklerData(simpleLocation, sprinkler); + } + } + + public void addScarecrow(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.addScarecrow(simpleLocation); + } + } + + public void removeScarecrow(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.removeScarecrow(simpleLocation); + } + } + + public boolean hasScarecrow(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + return ccWorld.hasScarecrow(simpleLocation); + } + return false; + } + + public void addWaterToPot(SimpleLocation simpleLocation, int amount, String pot_id) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.addWaterToPot(simpleLocation, amount, pot_id); + } + } + + public void addFertilizerToPot(SimpleLocation simpleLocation, Fertilizer fertilizer, String pot_id) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.addFertilizerToPot(simpleLocation, fertilizer, pot_id); + } + } + + public Pot getPotData(SimpleLocation simpleLocation) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + return ccWorld.getPotData(simpleLocation); + } + return null; + } + + public void addPotData(SimpleLocation simpleLocation, Pot pot) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + ccWorld.addPotData(simpleLocation, pot); + } + } + + public void addWaterToSprinkler(SimpleLocation simpleLocation, int add, int range, int max) { + Sprinkler sprinkler = getSprinklerData(simpleLocation); + if (sprinkler != null) { + sprinkler.setWater(Math.min(add + sprinkler.getWater(), max)); + sprinkler.setRange(range); + } + else { + Sprinkler newSprinkler = new Sprinkler(Math.min(add, max), range); + addSprinklerData(simpleLocation, newSprinkler); + } + } + + public boolean addCropPointAt(SimpleLocation simpleLocation, int points) { + CCWorld ccWorld = worldMap.get(simpleLocation.getWorldName()); + if (ccWorld != null) { + return ccWorld.addCropPointAt(simpleLocation, points); + } + return false; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/object/world/WorldListener.java b/src/main/java/net/momirealms/customcrops/api/object/world/WorldListener.java new file mode 100644 index 0000000..09c72ff --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/object/world/WorldListener.java @@ -0,0 +1,25 @@ +package net.momirealms.customcrops.api.object.world; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.world.WorldLoadEvent; +import org.bukkit.event.world.WorldUnloadEvent; + +public class WorldListener implements Listener { + + private final WorldDataManager worldManager; + + public WorldListener(WorldDataManager worldManager) { + this.worldManager = worldManager; + } + + @EventHandler + public void onChunkLoad(WorldLoadEvent event) { + worldManager.loadWorld(event.getWorld()); + } + + @EventHandler + public void onChunkUnload(WorldUnloadEvent event) { + worldManager.unloadWorld(event.getWorld()); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/util/AdventureUtils.java b/src/main/java/net/momirealms/customcrops/api/util/AdventureUtils.java new file mode 100644 index 0000000..2e41119 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/util/AdventureUtils.java @@ -0,0 +1,182 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.util; + +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.title.Title; +import net.momirealms.customcrops.CustomCrops; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.time.Duration; + +public class AdventureUtils { + + /** + * Get component from text + * @param text text + * @return component + */ + public static Component getComponentFromMiniMessage(String text) { + return MiniMessage.miniMessage().deserialize(replaceLegacy(text)); + } + + /** + * Send a message to a command sender + * @param sender sender + * @param s message + */ + public static void sendMessage(CommandSender sender, String s) { + if (s == null) return; + if (sender instanceof Player player) playerMessage(player, s); + else consoleMessage(s); + } + + /** + * Send a message to console + * @param s message + */ + public static void consoleMessage(String s) { + if (s == null) return; + Audience au = CustomCrops.getAdventure().sender(Bukkit.getConsoleSender()); + au.sendMessage(getComponentFromMiniMessage(s)); + } + + /** + * Send a message to a player + * @param player player + * @param s message + */ + public static void playerMessage(Player player, String s) { + if (s == null) return; + Audience au = CustomCrops.getAdventure().player(player); + au.sendMessage(getComponentFromMiniMessage(s)); + } + + /** + * Send a title to a player + * @param player player + * @param s1 title + * @param s2 subtitle + * @param in in (ms) + * @param duration duration (ms) + * @param out out (ms) + */ + public static void playerTitle(Player player, String s1, String s2, int in, int duration, int out) { + Audience au = CustomCrops.getAdventure().player(player); + Title.Times times = Title.Times.times(Duration.ofMillis(in), Duration.ofMillis(duration), Duration.ofMillis(out)); + Title title = Title.title(getComponentFromMiniMessage(s1), getComponentFromMiniMessage(s2), times); + au.showTitle(title); + } + + /** + * Send a title to a player + * @param player player + * @param s1 title + * @param s2 subtitle + * @param in in (ms) + * @param duration duration (ms) + * @param out out (ms) + */ + public static void playerTitle(Player player, Component s1, Component s2, int in, int duration, int out) { + Audience au = CustomCrops.getAdventure().player(player); + Title.Times times = Title.Times.times(Duration.ofMillis(in), Duration.ofMillis(duration), Duration.ofMillis(out)); + Title title = Title.title(s1, s2, times); + au.showTitle(title); + } + + /** + * Send an actionbar to a player + * @param player player + * @param s actionbar + */ + public static void playerActionbar(Player player, String s) { + Audience au = CustomCrops.getAdventure().player(player); + au.sendActionBar(getComponentFromMiniMessage(s)); + } + + /** + * Play a sound to a player + * @param player player + * @param source sound source + * @param key sound key + * @param volume volume + * @param pitch pitch + */ + public static void playerSound(Player player, Sound.Source source, Key key, float volume, float pitch) { + Sound sound = Sound.sound(key, source, volume, pitch); + Audience au = CustomCrops.getAdventure().player(player); + au.playSound(sound); + } + + public static void playerSound(Player player, Sound sound) { + Audience au = CustomCrops.getAdventure().player(player); + au.playSound(sound); + } + + + /** + * Replace the legacy codes with MiniMessage Format + * @param str text + * @return MiniMessage format text + */ + public static String replaceLegacy(String str) { + StringBuilder stringBuilder = new StringBuilder(); + char[] chars = str.replace("&","§").toCharArray(); + for (int i = 0; i < chars.length; i++) { + if (chars[i] == '§') { + if (i + 1 < chars.length) { + switch (chars[i+1]) { + case '0' -> {i++;stringBuilder.append("");} + case '1' -> {i++;stringBuilder.append("");} + case '2' -> {i++;stringBuilder.append("");} + case '3' -> {i++;stringBuilder.append("");} + case '4' -> {i++;stringBuilder.append("");} + case '5' -> {i++;stringBuilder.append("");} + case '6' -> {i++;stringBuilder.append("");} + case '7' -> {i++;stringBuilder.append("");} + case '8' -> {i++;stringBuilder.append("");} + case '9' -> {i++;stringBuilder.append("");} + case 'a' -> {i++;stringBuilder.append("");} + case 'b' -> {i++;stringBuilder.append("");} + case 'c' -> {i++;stringBuilder.append("");} + case 'd' -> {i++;stringBuilder.append("");} + case 'e' -> {i++;stringBuilder.append("");} + case 'f' -> {i++;stringBuilder.append("");} + case 'r' -> {i++;stringBuilder.append("");} + case 'l' -> {i++;stringBuilder.append("");} + case 'm' -> {i++;stringBuilder.append("");} + case 'o' -> {i++;stringBuilder.append("");} + case 'n' -> {i++;stringBuilder.append("");} + case 'k' -> {i++;stringBuilder.append("");} + case 'x' -> {stringBuilder.append("<#").append(chars[i+3]).append(chars[i+5]).append(chars[i+7]).append(chars[i+9]).append(chars[i+11]).append(chars[i+13]).append(">");i += 13;} + } + } + } + else { + stringBuilder.append(chars[i]); + } + } + return stringBuilder.toString(); + } +} diff --git a/src/main/java/net/momirealms/customcrops/utils/ArmorStandUtil.java b/src/main/java/net/momirealms/customcrops/api/util/ArmorStandUtils.java similarity index 60% rename from src/main/java/net/momirealms/customcrops/utils/ArmorStandUtil.java rename to src/main/java/net/momirealms/customcrops/api/util/ArmorStandUtils.java index f8f8df6..10f840e 100644 --- a/src/main/java/net/momirealms/customcrops/utils/ArmorStandUtil.java +++ b/src/main/java/net/momirealms/customcrops/api/util/ArmorStandUtils.java @@ -1,21 +1,4 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.utils; +package net.momirealms.customcrops.api.util; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; @@ -25,9 +8,6 @@ import com.comphenix.protocol.wrappers.WrappedDataValue; import com.comphenix.protocol.wrappers.WrappedDataWatcher; import com.google.common.collect.Lists; import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.config.BasicItemConfig; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.managers.CropManager; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.EntityType; @@ -36,30 +16,20 @@ import org.bukkit.inventory.ItemStack; import java.util.*; -public class ArmorStandUtil { +public class ArmorStandUtils { - private final CropManager cropManager; + public static void playWaterAnimation(Player player, Location location, String animation_id) { + int id = new Random().nextInt(Integer.MAX_VALUE); + CustomCrops.getProtocolManager().sendServerPacket(player, getSpawnPacket(id, location)); + CustomCrops.getProtocolManager().sendServerPacket(player, getMetaPacket(id)); + CustomCrops.getProtocolManager().sendServerPacket(player, getEquipPacket(id, CustomCrops.getInstance().getIntegrationManager().build(animation_id))); - public ArmorStandUtil(CropManager cropManager) { - this.cropManager = cropManager; + Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.getInstance(), () -> { + CustomCrops.getProtocolManager().sendServerPacket(player, getDestroyPacket(id)); + }, 200); } - public CropManager getCropManager() { - return cropManager; - } - - public void playWaterAnimation(Player player, Location location) { - int id = new Random().nextInt(1000000000); - CustomCrops.protocolManager.sendServerPacket(player, getSpawnPacket(id, location)); - CustomCrops.protocolManager.sendServerPacket(player, getMetaPacket(id)); - CustomCrops.protocolManager.sendServerPacket(player, getEquipPacket(id, cropManager.getCustomInterface().getItemStack(BasicItemConfig.waterEffect))); - - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.plugin, () -> { - CustomCrops.protocolManager.sendServerPacket(player, getDestroyPacket(id)); - }, MainConfig.timeToWork/2); - } - - public WrappedDataWatcher createDataWatcher() { + public static WrappedDataWatcher createInvisibleDataWatcher() { WrappedDataWatcher wrappedDataWatcher = new WrappedDataWatcher(); WrappedDataWatcher.Serializer serializer1 = WrappedDataWatcher.Registry.get(Boolean.class); WrappedDataWatcher.Serializer serializer2 = WrappedDataWatcher.Registry.get(Byte.class); @@ -69,13 +39,13 @@ public class ArmorStandUtil { return wrappedDataWatcher; } - public PacketContainer getDestroyPacket(int id) { + public static PacketContainer getDestroyPacket(int id) { PacketContainer destroyPacket = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY); destroyPacket.getIntLists().write(0, List.of(id)); return destroyPacket; } - public PacketContainer getSpawnPacket(int id, Location location) { + public static PacketContainer getSpawnPacket(int id, Location location) { PacketContainer entityPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY); entityPacket.getModifier().write(0, id); entityPacket.getModifier().write(1, UUID.randomUUID()); @@ -86,11 +56,11 @@ public class ArmorStandUtil { return entityPacket; } - public PacketContainer getMetaPacket(int id) { + public static PacketContainer getMetaPacket(int id) { PacketContainer metaPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); metaPacket.getIntegers().write(0, id); - if (CustomCrops.plugin.getVersionHelper().isVersionNewerThan1_19_R2()) { - WrappedDataWatcher wrappedDataWatcher = createDataWatcher(); + if (CustomCrops.getInstance().getVersionHelper().isVersionNewerThan1_19_R2()) { + WrappedDataWatcher wrappedDataWatcher = createInvisibleDataWatcher(); List wrappedDataValueList = Lists.newArrayList(); wrappedDataWatcher.getWatchableObjects().stream().filter(Objects::nonNull).forEach(entry -> { final WrappedDataWatcher.WrappedDataWatcherObject dataWatcherObject = entry.getWatcherObject(); @@ -98,12 +68,12 @@ public class ArmorStandUtil { }); metaPacket.getDataValueCollectionModifier().write(0, wrappedDataValueList); } else { - metaPacket.getWatchableCollectionModifier().write(0, createDataWatcher().getWatchableObjects()); + metaPacket.getWatchableCollectionModifier().write(0, createInvisibleDataWatcher().getWatchableObjects()); } return metaPacket; } - public PacketContainer getEquipPacket(int id, ItemStack itemStack) { + public static PacketContainer getEquipPacket(int id, ItemStack itemStack) { PacketContainer equipPacket = new PacketContainer(PacketType.Play.Server.ENTITY_EQUIPMENT); equipPacket.getIntegers().write(0, id); List> pairs = new ArrayList<>(); @@ -112,7 +82,7 @@ public class ArmorStandUtil { return equipPacket; } - public PacketContainer getTeleportPacket(int id, Location location, float yaw) { + public static PacketContainer getTeleportPacket(int id, Location location, float yaw) { PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_TELEPORT); packet.getIntegers().write(0, id); packet.getDoubles().write(0, location.getX()); @@ -122,7 +92,7 @@ public class ArmorStandUtil { return packet; } - public PacketContainer getRotationPacket(int id, float yaw) { + public static PacketContainer getRotationPacket(int id, float yaw) { PacketContainer rotationPacket = new PacketContainer(PacketType.Play.Server.ENTITY_HEAD_ROTATION); rotationPacket.getIntegers().write(0, id); return rotationPacket; diff --git a/src/main/java/net/momirealms/customcrops/api/util/ConfigUtils.java b/src/main/java/net/momirealms/customcrops/api/util/ConfigUtils.java new file mode 100644 index 0000000..f2d14da --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/util/ConfigUtils.java @@ -0,0 +1,423 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.api.util; + +import dev.dejvokep.boostedyaml.YamlDocument; +import dev.dejvokep.boostedyaml.dvs.versioning.BasicVersioning; +import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings; +import dev.dejvokep.boostedyaml.settings.general.GeneralSettings; +import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings; +import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.BoneMeal; +import net.momirealms.customcrops.api.object.InteractWithItem; +import net.momirealms.customcrops.api.object.Pair; +import net.momirealms.customcrops.api.object.fill.PassiveFillMethod; +import net.momirealms.customcrops.api.object.action.*; +import net.momirealms.customcrops.api.object.condition.Random; +import net.momirealms.customcrops.api.object.condition.*; +import net.momirealms.customcrops.api.object.ItemMode; +import net.momirealms.customcrops.api.object.crop.VariationCrop; +import net.momirealms.customcrops.api.object.fill.PositiveFillMethod; +import net.momirealms.customcrops.api.object.loot.Loot; +import net.momirealms.customcrops.api.object.loot.OtherLoot; +import net.momirealms.customcrops.api.object.loot.QualityLoot; +import net.momirealms.customcrops.api.object.requirement.*; +import net.momirealms.customcrops.api.object.season.CCSeason; +import net.momirealms.customcrops.helper.Log; +import org.bukkit.Particle; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.MemorySection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.intellij.lang.annotations.Subst; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +public class ConfigUtils { + + /** + * Get a config by name + * @param configName config's name + * @return yaml + */ + public static YamlConfiguration getConfig(String configName) { + File file = new File(CustomCrops.getInstance().getDataFolder(), configName); + if (!file.exists()) CustomCrops.getInstance().saveResource(configName, false); + return YamlConfiguration.loadConfiguration(file); + } + + /** + * Update config + * @param fileName config + */ + public static void update(String fileName){ + try { + YamlDocument.create(new File(CustomCrops.getInstance().getDataFolder(), fileName), Objects.requireNonNull(CustomCrops.getInstance().getResource(fileName)), GeneralSettings.DEFAULT, LoaderSettings.builder().setAutoUpdate(true).build(), DumperSettings.DEFAULT, UpdaterSettings.builder().setVersioning(new BasicVersioning("config-version")).build()); + } catch (IOException e){ + Log.warn(e.getMessage()); + } + } + + /** + * Create a data file if not exists + * @param file file path + * @return yaml data + */ + @SuppressWarnings("ResultOfMethodCallIgnored") + public static YamlConfiguration readData(File file) { + if (!file.exists()) { + try { + file.getParentFile().mkdirs(); + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + AdventureUtils.consoleMessage("[CustomFishing] Failed to generate data files!"); + } + } + return YamlConfiguration.loadConfiguration(file); + } + + @Nullable + public static DeathCondition[] getDeathConditions(ConfigurationSection section) { + if (section != null) { + List deathConditions = new ArrayList<>(); + for (String key : section.getKeys(false)) { + String model = section.getString(key + ".model"); + ConfigurationSection conditionSec = section.getConfigurationSection(key + ".conditions"); + if (conditionSec == null) { + AdventureUtils.consoleMessage("[CustomCrops] No condition is set for: " + section.getCurrentPath()); + continue; + } + List conditions = getConditions(conditionSec.getValues(false)); + deathConditions.add(new DeathCondition(model, conditions.toArray(new Condition[0]))); + if (model != null) CustomCrops.getInstance().getCropManager().registerDeadCrops(model); + } + return deathConditions.toArray(new DeathCondition[0]); + } + return null; + } + + @Nullable + public static Condition[] getConditions(ConfigurationSection section) { + if (section != null) { + return getConditions(section.getValues(false)).toArray(new Condition[0]); + } + return null; + } + + @NotNull + public static List getConditions(Map map) { + List conditions = new ArrayList<>(); + map.forEach((key, value) -> { + if (key.startsWith("&&")) { + if (map.get(key) instanceof MemorySection map2) { + conditions.add(new AndCondition(getConditions(map2.getValues(false)))); + } + } else if (key.startsWith("||")) { + if (map.get(key) instanceof MemorySection map2) { + conditions.add(new OrCondition(getConditions(map2.getValues(false)))); + } + } else { + if (map.get(key) instanceof MemorySection map2) { + String type = map2.getString("type"); + if (type == null) return; + switch (type) { + case "water_less_than" -> conditions.add(new WaterLessThan(map2.getInt("value"))); + case "water_more_than" -> conditions.add(new WaterMoreThan(map2.getInt("value"))); + case "unsuitable_season" -> conditions.add(new WrongSeason(map2.getStringList("value").stream().map(s -> CCSeason.valueOf(s.toUpperCase())).toList().toArray(new CCSeason[0]))); + case "suitable_season" -> conditions.add(new RightSeason(map2.getStringList("value").stream().map(s -> CCSeason.valueOf(s.toUpperCase())).toList().toArray(new CCSeason[0]))); + case "crow_attack" -> conditions.add(new CrowAttack(map2.getDouble("value.chance"), map2.getString("value.fly-model"), map2.getString("value.stand-model"))); + case "random" -> conditions.add(new Random(map2.getDouble("value"))); + } + } + } + }); + return conditions; + } + + @Nullable + public static Requirement[] getRequirementsWithMsg(ConfigurationSection section) { + if (section != null) { + List requirements = new ArrayList<>(); + for (String id : section.getKeys(false)) { + ConfigurationSection innerSec = section.getConfigurationSection(id); + if (innerSec == null) continue; + String type = innerSec.getString("type"); + if (type == null) continue; + String[] msg = innerSec.getStringList("message").size() == 0 ? (innerSec.getString("message") == null ? null : new String[]{innerSec.getString("message")}) : innerSec.getStringList("message").toArray(new String[0]); + switch (type) { + case "biome" -> requirements.add(new BiomeImpl(msg, new HashSet<>(innerSec.getStringList("value")))); + case "weather" -> requirements.add(new WeatherImpl(msg, innerSec.getStringList("value"))); + case "ypos" -> requirements.add(new YPosImpl(msg, innerSec.getStringList("value"))); + case "season" -> requirements.add(new SeasonImpl(msg, innerSec.getStringList("value").stream().map(str -> CCSeason.valueOf(str.toUpperCase())).collect(Collectors.toList()))); + case "world" -> requirements.add(new WorldImpl(msg, innerSec.getStringList("value"))); + case "permission" -> requirements.add(new PermissionImpl(msg, innerSec.getString("value"))); + case "time" -> requirements.add(new TimeImpl(msg, innerSec.getStringList("value"))); + case "skill-level" -> requirements.add(new SkillLevelImpl(msg, innerSec.getInt("value"))); + case "job-level" -> requirements.add(new JobLevelImpl(msg, innerSec.getInt("value"))); + case "date" -> requirements.add(new DateImpl(msg, new HashSet<>(innerSec.getStringList("value")))); + case "papi-condition" -> requirements.add(new CustomPapi(msg, Objects.requireNonNull(innerSec.getConfigurationSection("value")).getValues(false))); + } + } + return requirements.toArray(new Requirement[0]); + } + return null; + } + + @Nullable + public static Action[] getActions(ConfigurationSection section, String model_id) { + if (section != null) { + List actions = new ArrayList<>(); + for (String action_key : section.getKeys(false)) { + ConfigurationSection actionSec = section.getConfigurationSection(action_key); + if (actionSec == null) continue; + String type = actionSec.getString("type"); + if (type == null) continue; + switch (type) { + case "message" -> actions.add(new MessageActionImpl( + actionSec.getStringList("value").toArray(new String[0]), + actionSec.getDouble("chance", 1)) + ); + case "command" -> actions.add(new CommandActionImpl( + actionSec.getStringList("value").toArray(new String[0]), + actionSec.getDouble("chance", 1)) + ); + case "exp" -> actions.add(new VanillaXPImpl( + actionSec.getInt("value"), + false, + actionSec.getDouble("chance", 1)) + ); + case "mending" -> actions.add(new VanillaXPImpl( + actionSec.getInt("value"), + true, + actionSec.getDouble("chance", 1)) + ); + case "skill-xp" -> actions.add(new SkillXPImpl( + actionSec.getDouble("value"), + actionSec.getDouble("chance", 1)) + ); + case "job-xp" -> actions.add(new JobXPImpl( + actionSec.getDouble("value"), + actionSec.getDouble("chance", 1)) + ); + case "sound" -> actions.add(new SoundActionImpl( + actionSec.getString("value.source"), + actionSec.getString("value.key"), + (float) actionSec.getDouble("value.volume"), + (float) actionSec.getDouble("value.pitch")) + ); + case "particle" -> actions.add(new ParticleImpl( + Particle.valueOf(actionSec.getString("value.particle", "FLAME").toUpperCase()), + actionSec.getInt("value.amount"), + actionSec.getDouble("value.offset")) + ); + case "potion-effect" -> { + PotionEffectType potionEffectType = PotionEffectType.getByName(actionSec.getString("value.type", "BLINDNESS").toUpperCase()); + PotionEffect potionEffect = new PotionEffect( + potionEffectType == null ? PotionEffectType.LUCK : potionEffectType, + actionSec.getInt("value.duration"), + actionSec.getInt("value.amplifier") + ); + actions.add(new PotionEffectImpl(potionEffect, actionSec.getDouble("chance", 1))); + } + case "drop-items" -> { + ConfigurationSection lootSec = actionSec.getConfigurationSection("value"); + if (lootSec == null) continue; + ArrayList loots = new ArrayList<>(); + if (lootSec.contains("quality-crops")) { + loots.add(new QualityLoot( + lootSec.getInt("quality-crops.min"), + lootSec.getInt("quality-crops.max"), + lootSec.getString("quality-crops.items.1"), + lootSec.getString("quality-crops.items.2"), + lootSec.getString("quality-crops.items.3") + )); + } + if (lootSec.contains("other-items")) { + ConfigurationSection otherLootSec = lootSec.getConfigurationSection("other-items"); + if (otherLootSec == null) continue; + for (String inner_key : otherLootSec.getKeys(false)) { + OtherLoot otherLoot = new OtherLoot( + otherLootSec.getInt(inner_key + ".min"), + otherLootSec.getInt(inner_key + ".max"), + otherLootSec.getString(inner_key + ".item"), + otherLootSec.getDouble(inner_key + ".chance") + ); + loots.add(otherLoot); + } + } + actions.add(new DropItemImpl(loots.toArray(new Loot[0]))); + } + case "break" -> actions.add(new BreakImpl( + actionSec.getBoolean("value", true), + model_id) + ); + case "replant" -> actions.add(new ReplantImpl( + actionSec.getInt("value.point"), + actionSec.getString("value.model"), + actionSec.getString("value.crop") + )); + case "variation" -> { + ConfigurationSection variationSec = actionSec.getConfigurationSection("value"); + if (variationSec == null) continue; + ArrayList variationCrops = new ArrayList<>(); + for (String inner_key : variationSec.getKeys(false)) { + VariationCrop variationCrop = new VariationCrop( + variationSec.getString(inner_key + ".item"), + ItemMode.valueOf(variationSec.getString(inner_key + ".type", "TripWire").toUpperCase()), + variationSec.getDouble(inner_key + ".chance") + ); + variationCrops.add(variationCrop); + } + actions.add(new VariationImpl(variationCrops.toArray(new VariationCrop[0]))); + } + case "chain" -> actions.add(new ChainImpl( + getActions(actionSec.getConfigurationSection("value"), model_id), + actionSec.getDouble("chance") + )); + } + } + return actions.toArray(new Action[0]); + } + return null; + } + + @Nullable + public static PassiveFillMethod[] getPassiveFillMethods(ConfigurationSection section) { + if (section == null) return null; + ArrayList passiveFillMethods = new ArrayList<>(); + for (String key : section.getKeys(false)) { + ConfigurationSection methodSec = section.getConfigurationSection(key); + if (methodSec == null) continue; + @Subst("namespace:key") String soundKey = methodSec.getString("sound", "minecraft:block.water.ambient"); + Sound sound = methodSec.contains("sound") ? Sound.sound(Key.key(soundKey), Sound.Source.PLAYER, 1, 1) : null; + PassiveFillMethod passiveFillMethod = new PassiveFillMethod( + methodSec.getString("item"), + methodSec.getString("return"), + methodSec.getInt("amount", 1), + methodSec.contains("particle") ? Particle.valueOf(methodSec.getString("particle", "WATER_SPLASH").toUpperCase()) : null, + sound + ); + passiveFillMethods.add(passiveFillMethod); + } + return passiveFillMethods.toArray(new PassiveFillMethod[0]); + } + + public static double[] getQualityRatio(String str) { + double[] ratio = new double[2]; + String[] split = str.split("/", 3); + double[] weight = new double[3]; + weight[0] = Double.parseDouble(split[0]); + weight[1] = Double.parseDouble(split[1]); + weight[2] = Double.parseDouble(split[2]); + double weightTotal = weight[0] + weight[1] + weight[2]; + ratio[0] = weight[0]/(weightTotal); + ratio[1] = 1 - weight[1]/(weightTotal); + return ratio; + } + + public static boolean isVanillaItem(String item) { + char[] chars = item.toCharArray(); + for (char character : chars) { + if ((character < 65 || character > 90) && character != 95) { + return false; + } + } + return true; + } + + @Nullable + public static BoneMeal[] getBoneMeals(ConfigurationSection section) { + if (section == null) return null; + ArrayList boneMeals = new ArrayList<>(); + for (String key : section.getKeys(false)) { + ConfigurationSection boneMealSec = section.getConfigurationSection(key); + if (boneMealSec == null) continue; + ConfigurationSection chanceSec = boneMealSec.getConfigurationSection("chance"); + if (chanceSec == null) { + AdventureUtils.consoleMessage("chance is not properly set for custom bone meal at: " + boneMealSec.getCurrentPath()); + continue; + } + ArrayList> pairs = new ArrayList<>(); + for (String point : chanceSec.getKeys(false)) { + Pair pair = Pair.of(chanceSec.getDouble(point), Integer.parseInt(point)); + pairs.add(pair); + } + @Subst("namespace:key") String soundKey = boneMealSec.getString("sound", "minecraft:item.bone_meal.use"); + Sound sound = boneMealSec.contains("sound") ? Sound.sound(Key.key(soundKey), Sound.Source.PLAYER, 1, 1) : null; + BoneMeal boneMeal = new BoneMeal( + boneMealSec.getString("item"), + boneMealSec.getString("return"), + pairs, + sound, + boneMealSec.contains("particle") ? Particle.valueOf(boneMealSec.getString("particle", "WATER_SPLASH").toUpperCase()) : null + ); + boneMeals.add(boneMeal); + } + return boneMeals.toArray(new BoneMeal[0]); + } + + @Nullable + public static PositiveFillMethod[] getPositiveFillMethods(ConfigurationSection section) { + if (section == null) return null; + ArrayList methods = new ArrayList<>(); + for (String key : section.getKeys(false)) { + ConfigurationSection methodSec = section.getConfigurationSection(key); + if (methodSec == null) continue; + String id = methodSec.getString("target", "WATER"); + PositiveFillMethod.InteractType type = PositiveFillMethod.InteractType.valueOf(methodSec.getString("type", "block").toUpperCase()); + @Subst("namespace:key") String soundKey = methodSec.getString("sound", "minecraft:item.bucket.fill"); + Sound sound = Sound.sound(Key.key(soundKey), Sound.Source.PLAYER, 1, 1); + PositiveFillMethod method = new PositiveFillMethod( + type, + id, + methodSec.getInt("amount"), + methodSec.contains("particle") ? Particle.valueOf(methodSec.getString("particle", "WATER_SPLASH").toUpperCase()) : null, + sound + ); + methods.add(method); + } + return methods.toArray(new PositiveFillMethod[0]); + } + + public static InteractWithItem[] getInteractActions(ConfigurationSection section, String stageModel) { + if (section == null) return null; + ArrayList interactWithItems = new ArrayList<>(); + for (String key : section.getKeys(false)) { + ConfigurationSection innerSec = section.getConfigurationSection(key); + if (innerSec == null) continue; + InteractWithItem interactWithItem = new InteractWithItem( + innerSec.getString("item", "AIR"), + innerSec.getBoolean("reduce-amount", false), + innerSec.getString("return"), + getActions(innerSec.getConfigurationSection("actions"), stageModel) + ); + interactWithItems.add(interactWithItem); + } + return interactWithItems.toArray(new InteractWithItem[0]); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/api/util/PaperUtils.java b/src/main/java/net/momirealms/customcrops/api/util/PaperUtils.java new file mode 100644 index 0000000..2abcfd5 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/util/PaperUtils.java @@ -0,0 +1,14 @@ +package net.momirealms.customcrops.api.util; + +import org.bukkit.Chunk; +import org.bukkit.World; + +import java.util.concurrent.CompletableFuture; + +public class PaperUtils { + + public static CompletableFuture getChunkAtAsync(final World world, final int x, final int z) { + if (world == null) return CompletableFuture.completedFuture(null); + return world.getChunkAtAsync(x, z, false); + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/util/RotationUtils.java b/src/main/java/net/momirealms/customcrops/api/util/RotationUtils.java new file mode 100644 index 0000000..f138eb2 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/api/util/RotationUtils.java @@ -0,0 +1,14 @@ +package net.momirealms.customcrops.api.util; + +import org.bukkit.Rotation; + +import java.util.Random; + +public class RotationUtils { + + private static final Rotation[] rotations4 = {Rotation.NONE, Rotation.FLIPPED, Rotation.CLOCKWISE, Rotation.COUNTER_CLOCKWISE}; + + public static Rotation getRandomRotation() { + return rotations4[new Random().nextInt(rotations4.length-1)]; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/utils/AntiGriefUtils.java b/src/main/java/net/momirealms/customcrops/api/utils/AntiGriefUtils.java deleted file mode 100644 index d7164c5..0000000 --- a/src/main/java/net/momirealms/customcrops/api/utils/AntiGriefUtils.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.momirealms.customcrops.api.utils; - -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.integrations.CCAntiGrief; - -public class AntiGriefUtils { - - public static void register(CCAntiGrief CCAntiGrief) { - MainConfig.registerAntiGrief(CCAntiGrief); - } - - public static void unregister(CCAntiGrief CCAntiGrief) { - MainConfig.unregisterAntiGrief(CCAntiGrief); - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/utils/CropUtils.java b/src/main/java/net/momirealms/customcrops/api/utils/CropUtils.java deleted file mode 100644 index 519dd28..0000000 --- a/src/main/java/net/momirealms/customcrops/api/utils/CropUtils.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.api.utils; - -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.config.BasicItemConfig; -import net.momirealms.customcrops.config.CropConfig; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.managers.CropManager; -import net.momirealms.customcrops.managers.CustomWorld; -import net.momirealms.customcrops.objects.GrowingCrop; -import net.momirealms.customcrops.objects.Sprinkler; -import net.momirealms.customcrops.objects.fertilizer.Fertilizer; -import net.momirealms.customcrops.utils.FurnitureUtil; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.jetbrains.annotations.Nullable; - -public class CropUtils { - - /** - * get a crop config - * @param crop crop - * @return crop config - */ - @Nullable - public static Crop getCropConfig(String crop) { - return CropConfig.CROPS.get(crop); - } - - /** - * whether planting succeeds - * @param location location - * @param crop crop - * @return success or not - */ - public static boolean plantCrop(Location location, String crop) { - return CustomCrops.plugin.getCropManager().getHandler().plantSeed(location, crop, null, null); - } - - /** - * Oraxen & ItemsAdder handle item frame hitbox in different ways - * If you want to remove a crop at a certain location, use location.getBlock() method as the param - * @param block block - * @return success or not - */ - public static boolean removeCrop(Block block) { - Location location = block.getLocation(); - CustomCrops.plugin.getCropManager().getHandler().onBreakUnripeCrop(location); - if (MainConfig.cropMode) { - CustomCrops.plugin.getCropManager().getCustomInterface().removeBlock(location); - } - else { - if (MainConfig.OraxenHook) {CustomCrops.plugin.getCropManager().getCustomInterface().removeFurniture(FurnitureUtil.getItemFrame(location.clone().add(0.5,0.03125,0.5)));} - else {CustomCrops.plugin.getCropManager().getCustomInterface().removeFurniture(FurnitureUtil.getItemFrame(location.clone().add(0.5,0.5,0.5)));} - } - return true; - } - - /** - * get the growing crop - * @param location crop location - * @return growing crop - */ - @Nullable - public static GrowingCrop getGrowingCrop(Location location) { - CustomWorld customWorld = CustomCrops.plugin.getCropManager().getCustomWorld(location.getWorld()); - if (customWorld != null) { - return customWorld.getCropCache(location); - } - return null; - } - - /** - * [Only works in tripwire mode] - * @param block block - * @return the block is crop or not - */ - public static boolean isCropBlock(Block block) { - String block_id = CustomCrops.plugin.getCropManager().getCustomInterface().getBlockID(block.getLocation()); - if (block_id == null) return false; - return block_id.contains("_stage_") || block_id.equals(BasicItemConfig.deadCrop); - } - - /** - * [Only works in item_frame mode] - * @param entity entity - * @return the entity is crop or not - */ - public static boolean isCropEntity(Entity entity) { - String entity_id = CustomCrops.plugin.getCropManager().getCustomInterface().getEntityID(entity); - if (entity_id == null) return false; - return entity_id.contains("_stage_") || entity_id.equals(BasicItemConfig.deadCrop); - } - - /** - * get the cropManager - * @return cropManager - */ - public static CropManager getCropManager() { - return CustomCrops.plugin.getCropManager(); - } - - /** - * get the fertilizer - * @param location pot location - * @return fertilizer - */ - @Nullable - public static Fertilizer getFertilizer(Location location) { - CustomWorld customWorld = CustomCrops.plugin.getCropManager().getCustomWorld(location.getWorld()); - if (customWorld != null) { - return customWorld.getFertilizerCache(location); - } - return null; - } - - /** - * get the wet state - * @param location pot location - * @return wet or not - */ - public static boolean isPotWet(Location location) { - String block_id = CustomCrops.plugin.getCropManager().getCustomInterface().getBlockID(location); - if (block_id == null) return false; - return block_id.equals(BasicItemConfig.wetPot); - } - - /** - * Make a pot dry - * @param location pot location - */ - public static void makePotDry(Location location) { - CustomCrops.plugin.getCropManager().makePotDry(location); - } - - /** - * If the block is a pot - * @param location pot location - * @return the block is a pot or not - */ - public static boolean isPotBlock(Location location) { - String block_id = CustomCrops.plugin.getCropManager().getCustomInterface().getBlockID(location); - if (block_id == null) return false; - return block_id.equals(BasicItemConfig.wetPot) || block_id.equals(BasicItemConfig.dryPot); - } - - /** - * get the sprinkler data - * @param location sprinkler location - * @return sprinkler data - */ - @Nullable - public static Sprinkler getSprinkler(Location location) { - CustomWorld customWorld = CustomCrops.plugin.getCropManager().getCustomWorld(location.getWorld()); - if (customWorld != null) { - return customWorld.getSprinklerCache(location); - } - return null; - } -} diff --git a/src/main/java/net/momirealms/customcrops/api/utils/SeasonUtils.java b/src/main/java/net/momirealms/customcrops/api/utils/SeasonUtils.java deleted file mode 100644 index 66218ea..0000000 --- a/src/main/java/net/momirealms/customcrops/api/utils/SeasonUtils.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.api.utils; - -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.config.MessageConfig; -import org.bukkit.World; -import org.jetbrains.annotations.NotNull; - -public class SeasonUtils { - - /** - * Set season for a specified world - * @param world world - * @param season season - */ - public static void setSeason(World world, CCSeason season) { - CustomCrops.plugin.getCropManager().getSeasonAPI().setSeason(season, world); - } - - /** - * return a world's season, if it has no season, it would return a new season - * @param world world - * @return season - */ - @NotNull - public static CCSeason getSeason(World world) { - return CustomCrops.plugin.getCropManager().getSeasonAPI().getSeason(world); - } - - /** - * remove a world's season data from cache - * @param world world - */ - public static void unloadSeason(World world) { - CustomCrops.plugin.getCropManager().getSeasonAPI().unloadWorld(world); - } - - /** - * Get a season's localization - * @param season season - * @return localization - */ - public static String getSeasonText(CCSeason season) { - return switch (season) { - case SPRING -> MessageConfig.spring; - case SUMMER -> MessageConfig.summer; - case AUTUMN -> MessageConfig.autumn; - case WINTER -> MessageConfig.winter; - case UNKNOWN -> "Error"; - }; - } -} diff --git a/src/main/java/net/momirealms/customcrops/commands/PluginCommand.java b/src/main/java/net/momirealms/customcrops/command/AbstractMainCommand.java similarity index 57% rename from src/main/java/net/momirealms/customcrops/commands/PluginCommand.java rename to src/main/java/net/momirealms/customcrops/command/AbstractMainCommand.java index 4acf91c..4f8c7fb 100644 --- a/src/main/java/net/momirealms/customcrops/commands/PluginCommand.java +++ b/src/main/java/net/momirealms/customcrops/command/AbstractMainCommand.java @@ -15,11 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.commands; +package net.momirealms.customcrops.command; -import net.momirealms.customcrops.commands.subcmd.*; -import net.momirealms.customcrops.config.MessageConfig; -import net.momirealms.customcrops.utils.AdventureUtil; +import net.momirealms.customcrops.api.object.basic.MessageManager; +import net.momirealms.customcrops.api.util.AdventureUtils; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; @@ -28,60 +27,54 @@ import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.ConcurrentHashMap; -public class PluginCommand implements TabExecutor { +public abstract class AbstractMainCommand implements TabExecutor { - private final Map subCommandMap; + protected final Map subCommandMap; - public PluginCommand() { - subCommandMap = new ConcurrentHashMap<>(); - regDefaultSubCommands(); + public AbstractMainCommand() { + this.subCommandMap = new ConcurrentHashMap<>(); } @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { List argList = Arrays.asList(args); if (argList.size() < 1) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.nonArgs); + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.nonArgs); return true; } - SubCommand subCommand = subCommandMap.get(argList.get(0)); + if (!sender.hasPermission("customcrops." + argList.get(0))) { + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.noPerm); + return true; + } + AbstractSubCommand subCommand = subCommandMap.get(argList.get(0)); if (subCommand != null) return subCommand.onCommand(sender, argList.subList(1, argList.size())); else { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.unavailableArgs); + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.unavailableArgs); return true; } } - private void regDefaultSubCommands() { - regSubCommand(ReloadCommand.INSTANCE); - regSubCommand(SetSeasonCommand.INSTANCE); - regSubCommand(SimulateCommand.INSTANCE); - regSubCommand(GrowCommand.INSTANCE); - regSubCommand(SaveCacheCommand.INSTANCE); - regSubCommand(BackUpCommand.INSTANCE); - } - - public void regSubCommand(SubCommand executor) { - subCommandMap.put(executor.getSubCommand(), executor); - } - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { List argList = Arrays.asList(args); if (argList.size() <= 1) { List returnList = new ArrayList<>(subCommandMap.keySet()); - returnList.removeIf(str -> !str.startsWith(args[0])); + returnList.removeIf(str -> !str.startsWith(args[0]) || !sender.hasPermission("customcrops." + str)); return returnList; } - SubCommand subCommand = subCommandMap.get(argList.get(0)); + AbstractSubCommand subCommand = subCommandMap.get(argList.get(0)); if (subCommand != null) return subCommand.onTabComplete(sender, argList.subList(1, argList.size())); else return Collections.singletonList(""); } - public Map getSubCommandMap() { + public void regSubCommand(AbstractSubCommand executor) { + subCommandMap.put(executor.getSubCommand(), executor); + } + + public Map getSubCommandMap() { return subCommandMap; } } diff --git a/src/main/java/net/momirealms/customcrops/commands/AbstractSubCommand.java b/src/main/java/net/momirealms/customcrops/command/AbstractSubCommand.java similarity index 53% rename from src/main/java/net/momirealms/customcrops/commands/AbstractSubCommand.java rename to src/main/java/net/momirealms/customcrops/command/AbstractSubCommand.java index 3a28c8f..eeb029f 100644 --- a/src/main/java/net/momirealms/customcrops/commands/AbstractSubCommand.java +++ b/src/main/java/net/momirealms/customcrops/command/AbstractSubCommand.java @@ -15,44 +15,43 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.commands; +package net.momirealms.customcrops.command; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.config.MessageConfig; -import net.momirealms.customcrops.utils.AdventureUtil; +import net.momirealms.customcrops.api.object.basic.MessageManager; +import net.momirealms.customcrops.api.util.AdventureUtils; +import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; -public abstract class AbstractSubCommand implements SubCommand { +public abstract class AbstractSubCommand { private final String command; - private Map subCommandMap; + private Map subCommandMap; - public AbstractSubCommand(String command, Map subCommandMap) { + public AbstractSubCommand(String command) { this.command = command; - this.subCommandMap = subCommandMap; } - @Override public boolean onCommand(CommandSender sender, List args) { if (subCommandMap == null || args.size() < 1) { return true; } - SubCommand subCommand = subCommandMap.get(args.get(0)); + AbstractSubCommand subCommand = subCommandMap.get(args.get(0)); if (subCommand == null) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.unavailableArgs); + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.unavailableArgs); } else { subCommand.onCommand(sender, args.subList(1, args.size())); } return true; } - @Override public List onTabComplete(CommandSender sender, List args) { if (subCommandMap == null) return Collections.singletonList(""); @@ -61,42 +60,58 @@ public abstract class AbstractSubCommand implements SubCommand { returnList.removeIf(str -> !str.startsWith(args.get(0))); return returnList; } - SubCommand subCmd = subCommandMap.get(args.get(0)); + AbstractSubCommand subCmd = subCommandMap.get(args.get(0)); if (subCmd != null) return subCommandMap.get(args.get(0)).onTabComplete(sender, args.subList(1, args.size())); return Collections.singletonList(""); } - @Override public String getSubCommand() { return command; } - @Override - public Map getSubCommands() { + public Map getSubCommands() { return Collections.unmodifiableMap(subCommandMap); } - @Override - public void regSubCommand(SubCommand command) { + public void regSubCommand(AbstractSubCommand command) { if (subCommandMap == null) { subCommandMap = new ConcurrentHashMap<>(); } subCommandMap.put(command.getSubCommand(), command); } - public List getWorlds(List args) { - List worlds = MainConfig.getWorldNameList(); - List worldNames = new ArrayList<>(); - for (String world : worlds) { - if (world.startsWith(args.get(0))) { - worldNames.add(world); - } + protected boolean noConsoleExecute(CommandSender commandSender) { + if (!(commandSender instanceof Player)) { + AdventureUtils.consoleMessage(MessageManager.prefix + MessageManager.noConsole); + return true; } - return worldNames; + return false; } - public void setSubCommandMap(Map subCommandMap) { - this.subCommandMap = subCommandMap; + protected boolean playerNotOnline(CommandSender commandSender, String player) { + if (Bukkit.getPlayer(player) == null) { + AdventureUtils.sendMessage(commandSender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", player)); + return true; + } + return false; + } + + protected boolean lackArgs(CommandSender commandSender, int required, int current) { + if (required > current) { + AdventureUtils.sendMessage(commandSender, MessageManager.prefix + MessageManager.lackArgs); + return true; + } + return false; + } + + protected List online_players() { + List online = new ArrayList<>(); + Bukkit.getOnlinePlayers().forEach((player -> online.add(player.getName()))); + return online; + } + + protected List filterStartingWith(List list, String prefix) { + return list.stream().filter(s -> s.startsWith(prefix)).collect(Collectors.toList()); } } diff --git a/src/main/java/net/momirealms/customcrops/objects/QualityRatio.java b/src/main/java/net/momirealms/customcrops/command/CustomCropsCommand.java similarity index 61% rename from src/main/java/net/momirealms/customcrops/objects/QualityRatio.java rename to src/main/java/net/momirealms/customcrops/command/CustomCropsCommand.java index 9dc7155..aed77e8 100644 --- a/src/main/java/net/momirealms/customcrops/objects/QualityRatio.java +++ b/src/main/java/net/momirealms/customcrops/command/CustomCropsCommand.java @@ -15,23 +15,17 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects; +package net.momirealms.customcrops.command; -public class QualityRatio { +import net.momirealms.customcrops.command.subcmd.*; - private final double quality_1; - private final double quality_2; +public class CustomCropsCommand extends AbstractMainCommand { - public QualityRatio(double quality_1, double quality_2) { - this.quality_1 = quality_1; - this.quality_2 = quality_2; - } - - public double getQuality_1() { - return quality_1; - } - - public double getQuality_2() { - return quality_2; + public CustomCropsCommand() { + regSubCommand(ReloadCommand.INSTANCE); + regSubCommand(SetSeasonCommand.INSTANCE); + regSubCommand(HelpCommand.INSTANCE); + regSubCommand(AboutCommand.INSTANCE); + regSubCommand(SetDateCommand.INSTANCE); } } diff --git a/src/main/java/net/momirealms/customcrops/command/subcmd/AboutCommand.java b/src/main/java/net/momirealms/customcrops/command/subcmd/AboutCommand.java new file mode 100644 index 0000000..2565dec --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/command/subcmd/AboutCommand.java @@ -0,0 +1,44 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.command.subcmd; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.command.AbstractSubCommand; +import org.bukkit.command.CommandSender; + +import java.util.List; + +public class AboutCommand extends AbstractSubCommand { + + public static final AboutCommand INSTANCE = new AboutCommand(); + + public AboutCommand() { + super("about"); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + AdventureUtils.sendMessage(sender, "<#FFA500>⛈ CustomCrops - <#F4A460>" + CustomCrops.getInstance().getVersionHelper().getPluginVersion()); + AdventureUtils.sendMessage(sender, "<#FFFFE0>Custom crop system based on thread pool"); + AdventureUtils.sendMessage(sender, "<#DA70D6>\uD83E\uDDEA Author: <#FFC0CB>XiaoMoMi"); + AdventureUtils.sendMessage(sender, "<#FF7F50>\uD83D\uDD25 Contributors: <#FFA07A>Cha_Shao, <#FFA07A>TopOrigin, <#FFA07A>AmazingCat"); + AdventureUtils.sendMessage(sender, "<#FFD700>⭐ Document <#A9A9A9>| <#FAFAD2>⛏ Github <#A9A9A9>| <#48D1CC>\uD83D\uDD14 Polymart"); + return true; + } +} diff --git a/src/main/java/net/momirealms/customcrops/command/subcmd/HelpCommand.java b/src/main/java/net/momirealms/customcrops/command/subcmd/HelpCommand.java new file mode 100644 index 0000000..8a4460a --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/command/subcmd/HelpCommand.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.command.subcmd; + +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.command.AbstractSubCommand; +import org.bukkit.command.CommandSender; + +import java.util.List; + +public class HelpCommand extends AbstractSubCommand { + + public static final HelpCommand INSTANCE = new HelpCommand(); + + public HelpCommand() { + super("help"); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + AdventureUtils.sendMessage(sender, "<#FFA500>Command usage:"); + AdventureUtils.sendMessage(sender, " ├─<#FFFACD> "); + AdventureUtils.sendMessage(sender, " └─<#FFFACD><#E1FFFF>[Optional Augument]"); + AdventureUtils.sendMessage(sender, "<#FFA500>/customcrops"); + AdventureUtils.sendMessage(sender, " ├─help"); + AdventureUtils.sendMessage(sender, " ├─about"); + AdventureUtils.sendMessage(sender, " ├─reload <#87CEFA>Reload the plugin"); + AdventureUtils.sendMessage(sender, " └─setseason <#FFFACD> <#87CEFA>Set a world's season"); + return true; + } +} diff --git a/src/main/java/net/momirealms/customcrops/commands/subcmd/ReloadCommand.java b/src/main/java/net/momirealms/customcrops/command/subcmd/ReloadCommand.java similarity index 54% rename from src/main/java/net/momirealms/customcrops/commands/subcmd/ReloadCommand.java rename to src/main/java/net/momirealms/customcrops/command/subcmd/ReloadCommand.java index 1a09ac4..b421c91 100644 --- a/src/main/java/net/momirealms/customcrops/commands/subcmd/ReloadCommand.java +++ b/src/main/java/net/momirealms/customcrops/command/subcmd/ReloadCommand.java @@ -15,33 +15,29 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.commands.subcmd; +package net.momirealms.customcrops.command.subcmd; -import net.momirealms.customcrops.commands.AbstractSubCommand; -import net.momirealms.customcrops.commands.SubCommand; -import net.momirealms.customcrops.config.ConfigUtil; -import net.momirealms.customcrops.config.MessageConfig; -import net.momirealms.customcrops.utils.AdventureUtil; +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.basic.MessageManager; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.command.AbstractSubCommand; import org.bukkit.command.CommandSender; import java.util.List; public final class ReloadCommand extends AbstractSubCommand { - public static final SubCommand INSTANCE = new ReloadCommand(); + public static final ReloadCommand INSTANCE = new ReloadCommand(); private ReloadCommand() { - super("reload", null); + super("reload"); } @Override public boolean onCommand(CommandSender sender, List args) { - if (args.size() < 1) { - long time1 = System.currentTimeMillis(); - ConfigUtil.reloadConfigs(); - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.reload.replace("{time}", String.valueOf(System.currentTimeMillis() - time1))); - return true; - } - return super.onCommand(sender, args); + long time1 = System.currentTimeMillis(); + CustomCrops.getInstance().reload(); + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.reload.replace("{time}", String.valueOf(System.currentTimeMillis() - time1))); + return true; } -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/command/subcmd/SetDateCommand.java b/src/main/java/net/momirealms/customcrops/command/subcmd/SetDateCommand.java new file mode 100644 index 0000000..e2d692c --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/command/subcmd/SetDateCommand.java @@ -0,0 +1,65 @@ +package net.momirealms.customcrops.command.subcmd; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.object.basic.MessageManager; +import net.momirealms.customcrops.api.object.season.CCSeason; +import net.momirealms.customcrops.api.object.season.SeasonData; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.command.AbstractSubCommand; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.generator.WorldInfo; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class SetDateCommand extends AbstractSubCommand { + + public static final SetDateCommand INSTANCE = new SetDateCommand(); + + public SetDateCommand() { + super("setdate"); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + if (lackArgs(sender, 2, args.size())) return true; + World world = Bukkit.getWorld(args.get(0)); + if (world == null) { + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.worldNotExist.replace("{world}", args.get(0))); + return true; + } + try { + int date = Integer.parseInt(args.get(1)); + SeasonData seasonData = CustomCrops.getInstance().getSeasonManager().unloadSeasonData(args.get(0)); + if (seasonData == null) { + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.noSeason); + return true; + } + seasonData.setDate(date); + CustomCrops.getInstance().getSeasonManager().loadSeasonData(seasonData); + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.setDate.replace("{world}", args.get(0)).replace("{date}", String.valueOf(date))); + return true; + } catch (NumberFormatException e) { + AdventureUtils.sendMessage(sender, MessageManager.prefix + "Wrong number format"); + return true; + } + } + + @Override + public List onTabComplete(CommandSender sender, List args) { + if (args.size() == 1) { + return super.filterStartingWith(Bukkit.getWorlds().stream().filter(world -> CustomCrops.getInstance().getWorldDataManager().isWorldAllowed(world)).map(WorldInfo::getName).collect(Collectors.toList()), args.get(0)); + } else if (args.size() == 2) { + ArrayList dates = new ArrayList<>(); + for (int i = 1; i <= ConfigManager.seasonInterval; i++) { + dates.add(String.valueOf(i)); + } + return super.filterStartingWith(dates, args.get(1)); + } + return null; + } +} diff --git a/src/main/java/net/momirealms/customcrops/command/subcmd/SetSeasonCommand.java b/src/main/java/net/momirealms/customcrops/command/subcmd/SetSeasonCommand.java new file mode 100644 index 0000000..c8606cf --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/command/subcmd/SetSeasonCommand.java @@ -0,0 +1,59 @@ +package net.momirealms.customcrops.command.subcmd; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.basic.MessageManager; +import net.momirealms.customcrops.api.object.season.CCSeason; +import net.momirealms.customcrops.api.object.season.SeasonData; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.command.AbstractSubCommand; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.generator.WorldInfo; + +import java.util.List; +import java.util.stream.Collectors; + +public class SetSeasonCommand extends AbstractSubCommand { + + public static final SetSeasonCommand INSTANCE = new SetSeasonCommand(); + + public SetSeasonCommand() { + super("setseason"); + } + + @Override + public boolean onCommand(CommandSender sender, List args) { + if (lackArgs(sender, 2, args.size())) return true; + World world = Bukkit.getWorld(args.get(0)); + if (world == null) { + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.worldNotExist.replace("{world}", args.get(0))); + return true; + } + try { + CCSeason ccSeason = CCSeason.valueOf(args.get(1).toUpperCase()); + SeasonData seasonData = CustomCrops.getInstance().getSeasonManager().unloadSeasonData(args.get(0)); + if (seasonData == null) { + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.noSeason); + return true; + } + seasonData.changeSeason(ccSeason); + CustomCrops.getInstance().getSeasonManager().loadSeasonData(seasonData); + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.setSeason.replace("{world}", args.get(0)).replace("{season}", ccSeason.toString())); + return true; + } catch (IllegalArgumentException e) { + AdventureUtils.sendMessage(sender, MessageManager.prefix + MessageManager.seasonNotExist.replace("{season}", args.get(1))); + return true; + } + } + + @Override + public List onTabComplete(CommandSender sender, List args) { + if (args.size() == 1) { + return super.filterStartingWith(Bukkit.getWorlds().stream().filter(world -> CustomCrops.getInstance().getWorldDataManager().isWorldAllowed(world)).map(WorldInfo::getName).collect(Collectors.toList()), args.get(0)); + } else if (args.size() == 2) { + return super.filterStartingWith(List.of("spring", "summer", "autumn", "winter"), args.get(1)); + } + return null; + } +} diff --git a/src/main/java/net/momirealms/customcrops/commands/SubCommand.java b/src/main/java/net/momirealms/customcrops/commands/SubCommand.java deleted file mode 100644 index 174fb73..0000000 --- a/src/main/java/net/momirealms/customcrops/commands/SubCommand.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.commands; - -import org.bukkit.command.CommandSender; - -import java.util.List; -import java.util.Map; - -public interface SubCommand { - - boolean onCommand(CommandSender sender, List args); - - List onTabComplete(CommandSender sender, List args); - - String getSubCommand(); - - Map getSubCommands(); - - void regSubCommand(SubCommand subCommand); - -} diff --git a/src/main/java/net/momirealms/customcrops/commands/subcmd/BackUpCommand.java b/src/main/java/net/momirealms/customcrops/commands/subcmd/BackUpCommand.java deleted file mode 100644 index 2e713b5..0000000 --- a/src/main/java/net/momirealms/customcrops/commands/subcmd/BackUpCommand.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.momirealms.customcrops.commands.subcmd; - -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.commands.AbstractSubCommand; -import net.momirealms.customcrops.commands.SubCommand; -import net.momirealms.customcrops.config.MessageConfig; -import net.momirealms.customcrops.managers.CustomWorld; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.command.CommandSender; - -import java.util.List; - -public class BackUpCommand extends AbstractSubCommand { - - public static final SubCommand INSTANCE = new BackUpCommand(); - - public BackUpCommand() { - super("backup", null); - } - - @Override - public boolean onCommand(CommandSender sender, List args) { - if (args.size() < 1) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.lackArgs); - return true; - } - String worldName = args.get(0); - World world = Bukkit.getWorld(worldName); - if (world == null) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.worldNotExists.replace("{world}", worldName)); - return true; - } - CustomWorld customWorld = CustomCrops.plugin.getCropManager().getCustomWorld(world); - if (customWorld == null) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + "CustomCrops is not enabled in that world"); - return true; - } - Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> { - customWorld.backUp(); - AdventureUtil.sendMessage(sender, MessageConfig.prefix + "Done"); - }); - return true; - } - - @Override - public List onTabComplete(CommandSender sender, List args) { - if (args.size() == 1) { - return getWorlds(args); - } - return super.onTabComplete(sender, args); - } -} diff --git a/src/main/java/net/momirealms/customcrops/commands/subcmd/GrowCommand.java b/src/main/java/net/momirealms/customcrops/commands/subcmd/GrowCommand.java deleted file mode 100644 index b679dc9..0000000 --- a/src/main/java/net/momirealms/customcrops/commands/subcmd/GrowCommand.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.commands.subcmd; - -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.commands.AbstractSubCommand; -import net.momirealms.customcrops.commands.SubCommand; -import net.momirealms.customcrops.config.MessageConfig; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.command.CommandSender; - -import java.util.List; - -public class GrowCommand extends AbstractSubCommand { - - public static final SubCommand INSTANCE = new GrowCommand(); - - public GrowCommand() { - super("grow", null); - } - - @Override - public boolean onCommand(CommandSender sender, List args) { - if (args.size() < 2) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.lackArgs); - } - else { - World world = Bukkit.getWorld(args.get(0)); - if (world == null) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.worldNotExists.replace("{world}", args.get(0))); - return true; - } - int growTime; - try { - growTime = Integer.parseInt(args.get(1)); - if (growTime <= 0 || growTime > 23999) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + "Time should be a positive number between 1-23999"); - return true; - } - } - catch (IllegalArgumentException e) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + "Time should be a positive number between 1-23999"); - e.printStackTrace(); - return true; - } - Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> { - CustomCrops.plugin.getCropManager().grow(world, growTime, 0, 0, false, true); - }); - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.growSimulation); - } - return true; - } - - @Override - public List onTabComplete(CommandSender sender, List args) { - if (args.size() == 1) { - return getWorlds(args); - } - if (args.size() == 2) { - return List.of(""); - } - return super.onTabComplete(sender, args); - } -} diff --git a/src/main/java/net/momirealms/customcrops/commands/subcmd/SaveCacheCommand.java b/src/main/java/net/momirealms/customcrops/commands/subcmd/SaveCacheCommand.java deleted file mode 100644 index 709fa6e..0000000 --- a/src/main/java/net/momirealms/customcrops/commands/subcmd/SaveCacheCommand.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.momirealms.customcrops.commands.subcmd; - -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.commands.AbstractSubCommand; -import net.momirealms.customcrops.commands.SubCommand; -import net.momirealms.customcrops.config.MessageConfig; -import net.momirealms.customcrops.managers.CustomWorld; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.command.CommandSender; - -import java.util.List; - -public class SaveCacheCommand extends AbstractSubCommand { - - public static final SubCommand INSTANCE = new SaveCacheCommand(); - - public SaveCacheCommand() { - super("savecache", null); - } - - @Override - public boolean onCommand(CommandSender sender, List args) { - if (args.size() < 1) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.lackArgs); - return true; - } - String worldName = args.get(0); - World world = Bukkit.getWorld(worldName); - if (world == null) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.worldNotExists.replace("{world}", worldName)); - return true; - } - CustomWorld customWorld = CustomCrops.plugin.getCropManager().getCustomWorld(world); - if (customWorld == null) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + "CustomCrops is not enabled in that world"); - return true; - } - Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> { - customWorld.unloadData(); - AdventureUtil.sendMessage(sender, MessageConfig.prefix + "Done"); - }); - return true; - } - - @Override - public List onTabComplete(CommandSender sender, List args) { - if (args.size() == 1) { - return getWorlds(args); - } - return super.onTabComplete(sender, args); - } -} diff --git a/src/main/java/net/momirealms/customcrops/commands/subcmd/SetSeasonCommand.java b/src/main/java/net/momirealms/customcrops/commands/subcmd/SetSeasonCommand.java deleted file mode 100644 index 1c669cd..0000000 --- a/src/main/java/net/momirealms/customcrops/commands/subcmd/SetSeasonCommand.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.commands.subcmd; - -import net.momirealms.customcrops.api.utils.CCSeason; -import net.momirealms.customcrops.api.utils.SeasonUtils; -import net.momirealms.customcrops.commands.AbstractSubCommand; -import net.momirealms.customcrops.commands.SubCommand; -import net.momirealms.customcrops.config.MessageConfig; -import net.momirealms.customcrops.config.SeasonConfig; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.command.CommandSender; - -import java.util.ArrayList; -import java.util.List; - -public class SetSeasonCommand extends AbstractSubCommand { - - public static final SubCommand INSTANCE = new SetSeasonCommand(); - - public SetSeasonCommand() { - super("setseason", null); - } - - @Override - public boolean onCommand(CommandSender sender, List args) { - if (!SeasonConfig.enable) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.seasonDisabled); - return true; - } - if (args.size() < 2) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.lackArgs); - return true; - } - else { - World world = Bukkit.getWorld(args.get(0)); - if (world == null) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.worldNotExists.replace("{world}", args.get(0))); - return true; - } - CCSeason ccSeason; - try { - ccSeason = CCSeason.valueOf(args.get(1).toUpperCase()); - } - catch (IllegalArgumentException e) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.seasonNotExists.replace("{season}", args.get(1))); - return true; - } - SeasonUtils.setSeason(world, ccSeason); - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.setSeason.replace("{world}", args.get(0)).replace("{season}", args.get(1))); - } - return super.onCommand(sender, args); - } - - @Override - public List onTabComplete(CommandSender sender, List args) { - if (!SeasonConfig.enable) return null; - if (args.size() == 1) { - return getWorlds(args); - } - if (args.size() == 2) { - List seasons = List.of("Spring","Summer","Autumn","Winter"); - List seasonList = new ArrayList<>(); - for (String season : seasons) { - if (season.startsWith(args.get(1))) { - seasonList.add(season); - } - } - return seasonList; - } - return super.onTabComplete(sender, args); - } -} diff --git a/src/main/java/net/momirealms/customcrops/commands/subcmd/SimulateCommand.java b/src/main/java/net/momirealms/customcrops/commands/subcmd/SimulateCommand.java deleted file mode 100644 index e9652ce..0000000 --- a/src/main/java/net/momirealms/customcrops/commands/subcmd/SimulateCommand.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.commands.subcmd; - -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.commands.AbstractSubCommand; -import net.momirealms.customcrops.commands.SubCommand; -import net.momirealms.customcrops.config.MessageConfig; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.command.CommandSender; - -import java.util.List; - -public class SimulateCommand extends AbstractSubCommand { - - public static final SubCommand INSTANCE = new SimulateCommand(); - - private SimulateCommand() { - super("simulate", null); - } - - @Override - public boolean onCommand(CommandSender sender, List args) { - if (args.size() < 4) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.lackArgs); - } - else { - World world = Bukkit.getWorld(args.get(0)); - if (world == null) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.worldNotExists.replace("{world}", args.get(0))); - return true; - } - int sprinklerTime; - int growTime; - int dryTime; - try { - sprinklerTime = Integer.parseInt(args.get(1)); - growTime = Integer.parseInt(args.get(3)); - dryTime = Integer.parseInt(args.get(2)); - if (sprinklerTime <= 0 || growTime <= 0 || dryTime <= 0 || (sprinklerTime + growTime + dryTime) > 23999) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + "Time should be a positive number between 1-23999"); - return true; - } - } - catch (IllegalArgumentException e) { - AdventureUtil.sendMessage(sender, MessageConfig.prefix + "Time should be a positive number between 1-23999"); - e.printStackTrace(); - return true; - } - Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> { - CustomCrops.plugin.getCropManager().grow(world, growTime, sprinklerTime, dryTime, false, false); - }); - AdventureUtil.sendMessage(sender, MessageConfig.prefix + MessageConfig.growSimulation); - } - return true; - } - - @Override - public List onTabComplete(CommandSender sender, List args) { - if (args.size() == 1) { - return getWorlds(args); - } - if (args.size() == 2) { - return List.of(""); - } - if (args.size() == 3) { - return List.of(""); - } - if (args.size() == 4) { - return List.of(""); - } - return super.onTabComplete(sender, args); - } -} diff --git a/src/main/java/net/momirealms/customcrops/config/BasicItemConfig.java b/src/main/java/net/momirealms/customcrops/config/BasicItemConfig.java deleted file mode 100644 index b6c0feb..0000000 --- a/src/main/java/net/momirealms/customcrops/config/BasicItemConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.config; - -import org.bukkit.configuration.file.YamlConfiguration; - -public class BasicItemConfig { - - public static String dryPot; - public static String wetPot; - public static String deadCrop; - public static String soilSurveyor; - public static String greenHouseGlass; - public static String crowLand; - public static String crowFly; - public static String scarecrow; - public static String waterEffect; - - public static void load() { - YamlConfiguration config = ConfigUtil.getConfig("basic_" + MainConfig.customPlugin + ".yml"); - dryPot = config.getString("dry-pot"); - wetPot = config.getString("wet-pot"); - greenHouseGlass = config.getString("greenhouse-glass"); - soilSurveyor = config.getString("soil-surveyor"); - deadCrop = config.getString("dead-crop"); - crowLand = config.getString("crow-land"); - crowFly = config.getString("crow-fly"); - scarecrow = config.getString("scarecrow"); - waterEffect = config.getString("water-effect"); - } -} diff --git a/src/main/java/net/momirealms/customcrops/config/ConfigUtil.java b/src/main/java/net/momirealms/customcrops/config/ConfigUtil.java deleted file mode 100644 index d0b02db..0000000 --- a/src/main/java/net/momirealms/customcrops/config/ConfigUtil.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.config; - -import dev.dejvokep.boostedyaml.YamlDocument; -import dev.dejvokep.boostedyaml.dvs.versioning.BasicVersioning; -import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings; -import dev.dejvokep.boostedyaml.settings.general.GeneralSettings; -import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings; -import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.helper.Log; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.io.IOException; - -public class ConfigUtil { - - public static void update(String fileName){ - try { - YamlDocument.create(new File(CustomCrops.plugin.getDataFolder(), fileName), CustomCrops.plugin.getResource(fileName), GeneralSettings.DEFAULT, LoaderSettings.builder().setAutoUpdate(true).build(), DumperSettings.DEFAULT, UpdaterSettings.builder().setVersioning(new BasicVersioning("config-version")).build()); - } catch (IOException e){ - Log.warn(e.getMessage()); - } - } - - public static YamlConfiguration readData(File file) { - if (!file.exists()) { - try { - file.getParentFile().mkdirs(); - file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - AdventureUtil.consoleMessage("[CustomCrops] Failed to generate data files!"); - } - } - return YamlConfiguration.loadConfiguration(file); - } - - public static YamlConfiguration getConfig(String configName) { - File file = new File(CustomCrops.plugin.getDataFolder(), configName); - if (!file.exists()) CustomCrops.plugin.saveResource(configName, false); - return YamlConfiguration.loadConfiguration(file); - } - - public static void reloadConfigs() { - MainConfig.load(); - BasicItemConfig.load(); - CropConfig.load(); - FertilizerConfig.load(); - MessageConfig.load(); - SeasonConfig.load(); - SprinklerConfig.load(); - WaterCanConfig.load(); - SoundConfig.load(); - if (CustomCrops.plugin.getPlaceholderManager() != null) { - CustomCrops.plugin.getPlaceholderManager().unload(); - CustomCrops.plugin.getPlaceholderManager().load(); - } - if (CustomCrops.plugin.getCropManager() != null) { - CustomCrops.plugin.getCropManager().reload(); - } - } -} diff --git a/src/main/java/net/momirealms/customcrops/config/CropConfig.java b/src/main/java/net/momirealms/customcrops/config/CropConfig.java deleted file mode 100644 index bc24508..0000000 --- a/src/main/java/net/momirealms/customcrops/config/CropConfig.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.config; - -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.api.utils.CCSeason; -import net.momirealms.customcrops.objects.CCCrop; -import net.momirealms.customcrops.objects.GiganticCrop; -import net.momirealms.customcrops.objects.OtherLoot; -import net.momirealms.customcrops.objects.QualityLoot; -import net.momirealms.customcrops.objects.actions.*; -import net.momirealms.customcrops.objects.requirements.*; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Objects; - -public class CropConfig { - - public static HashMap CROPS; - public static String namespace = ""; - - public static void load() { - - CROPS = new HashMap<>(16); - YamlConfiguration config = ConfigUtil.getConfig("crops_" + MainConfig.customPlugin + ".yml"); - - if (config.contains("tomato") && !config.contains("tomato.max-stage")) config.set("tomato.max-stage", 4); - if (config.contains("grape") && !config.contains("grape.max-stage")) config.set("grape.max-stage", 6); - if (config.contains("garlic") && !config.contains("garlic.max-stage")) config.set("garlic.max-stage", 4); - if (config.contains("redpacket") && !config.contains("redpacket.max-stage")) config.set("redpacket.max-stage", 6); - if (config.contains("cabbage") && !config.contains("cabbage.max-stage")) config.set("cabbage.max-stage", 4); - if (config.contains("pepper") && !config.contains("pepper.max-stage")) config.set("pepper.max-stage", 5); - if (config.contains("corn") && !config.contains("corn.max-stage")) config.set("corn.max-stage", 4); - if (config.contains("apple") && !config.contains("apple.max-stage")) config.set("apple.max-stage", 6); - if (config.contains("pineapple") && !config.contains("pineapple.max-stage")) config.set("pineapple.max-stage", 4); - if (config.contains("pitaya") && !config.contains("pitaya.max-stage")) config.set("pitaya.max-stage", 6); - if (config.contains("eggplant") && !config.contains("eggplant.max-stage")) config.set("eggplant.max-stage", 4); - if (config.contains("chinesecabbage") && !config.contains("chinesecabbage.max-stage")) config.set("chinesecabbage.max-stage", 4); - if (config.contains("hop") && !config.contains("hop.max-stage")) config.set("hop.max-stage", 4); - - if (MainConfig.customPlugin.equals("itemsadder")) { - namespace = config.getString("namespace"); - if (namespace == null) { - namespace = "customcrops:"; - config.set("namespace", "customcrops"); - } - else { - namespace = namespace + ":"; - } - } - - try { - config.save(new File(CustomCrops.plugin.getDataFolder(), "crops_" + MainConfig.customPlugin + ".yml")); - } - catch (IOException e) { - e.printStackTrace(); - } - - for (String key : config.getKeys(false)) { - if (key.equals("namespace")) continue; - - int max_stage; - if (config.contains(key + ".max-stage")) { - max_stage = config.getInt(key + ".max-stage"); - } - else { - AdventureUtil.consoleMessage("[CustomCrops] No \"max-stage\" set for crop: " + key); - AdventureUtil.consoleMessage("[CustomCrops] Please read the update log (v2.1.0), this is for better performance :)"); - continue; - } - - CCCrop crop = new CCCrop(key, max_stage); - for (String option : Objects.requireNonNull(config.getConfigurationSection(key)).getKeys(false)) { - switch (option) { - case "quality-loots" -> { - String amount = config.getString(key + ".quality-loots.amount", "1~2"); - QualityLoot qualityLoot = new QualityLoot( - Integer.parseInt(amount.split("~")[0]), - Integer.parseInt(amount.split("~")[1]), - config.getString(key + ".quality-loots.quality.1"), - config.getString(key + ".quality-loots.quality.2"), - config.getString(key + ".quality-loots.quality.3") - ); - crop.setQualityLoot(qualityLoot); - } - case "harvest-actions" -> { - List actions = new ArrayList<>(); - for (String action : Objects.requireNonNull(config.getConfigurationSection(key + ".harvest-actions")).getKeys(false)) { - switch (action) { - case "xp" -> actions.add(new ActionXP(config.getInt(key + ".harvest-actions." + action), config.getDouble(key + ".harvest-actions." + action + "-chance", 1))); - case "skill-xp" -> actions.add(new ActionSkillXP(config.getDouble(key + ".harvest-actions." + action), config.getDouble(key + ".harvest-actions." + action + "-chance", 1))); - case "job-xp" -> actions.add(new ActionJobXP(config.getDouble(key + ".harvest-actions." + action), config.getDouble(key + ".harvest-actions." + action + "-chance", 1))); - case "commands" -> actions.add(new ActionCommand(config.getStringList(key + ".harvest-actions." + action).toArray(new String[0]), config.getDouble(key + ".harvest-actions." + action + "-chance", 1))); - case "messages" -> actions.add(new ActionMessage(config.getStringList(key + ".harvest-actions." + action).toArray(new String[0]), config.getDouble(key + ".harvest-actions." + action + "-chance", 1))); - } - } - crop.setActions(actions.toArray(new ActionInterface[0])); - } - case "other-loots" -> { - List otherLoots = new ArrayList<>(); - for (String loot : Objects.requireNonNull(config.getConfigurationSection(key + ".other-loots")).getKeys(false)) { - OtherLoot otherLoot = new OtherLoot( - config.getInt(key + ".other-loots." + loot + ".min_amount", 1), - config.getInt(key + ".other-loots." + loot + ".max_amount", 1), - config.getString(key + ".other-loots." + loot + ".item"), - config.getDouble(key + ".other-loots." + loot + ".chance", 1d) - ); - otherLoots.add(otherLoot); - } - crop.setOtherLoots(otherLoots.toArray(new OtherLoot[0])); - } - case "season" -> { - List seasonList = config.getStringList(key + ".season"); - CCSeason[] seasons = new CCSeason[seasonList.size()]; - for (int i = 0; i < seasonList.size(); i++) { - seasons[i] = CCSeason.valueOf(seasonList.get(i).toUpperCase()); - } - crop.setSeasons(seasons); - } - case "gigantic-crop" -> { - boolean isBlock = true; - String blockID = config.getString(key + ".gigantic-crop.block"); - if (blockID == null) { - blockID = config.getString(key + ".gigantic-crop.furniture"); - isBlock = false; - } - GiganticCrop giganticCrop = new GiganticCrop( - config.getDouble(key + ".gigantic-crop.chance"), - isBlock, - blockID - ); - crop.setGiganticCrop(giganticCrop); - } - case "return" -> { - crop.setReturnStage(config.getString(key + ".return")); - } - case "requirements", "plant-requirements", "harvest-requirements" -> { - List requirementList = new ArrayList<>(); - for (String requirement : Objects.requireNonNull(config.getConfigurationSection(key + "." + option)).getKeys(false)) { - String type = config.getString(key + "." + option + "." + requirement + ".type"); - if (type == null) continue; - switch (type) { - case "time" -> requirementList.add(new RequirementTime( - config.getStringList(key + "." + option + "." + requirement + ".value").toArray(new String[0]), - Objects.equals(config.getString(key + "." + option + "." + requirement + ".mode"), "&&"), - config.getString(key + "." + option + "." + requirement + ".message") - )); - case "weather" -> requirementList.add(new RequirementWeather( - config.getStringList(key + "." + option + "." + requirement + ".value").toArray(new String[0]), - Objects.equals(config.getString(key + "." + option + "." + requirement + ".mode"), "&&"), - config.getString(key + "." + option + "." + requirement + ".message") - )); - case "yPos" -> requirementList.add(new RequirementYPos( - config.getStringList(key + "." + option + "." + requirement + ".value").toArray(new String[0]), - Objects.equals(config.getString(key + "." + option + "." + requirement + ".mode"), "&&"), - config.getString(key + "." + option + "." + requirement + ".message") - )); - case "biome" -> requirementList.add(new RequirementBiome( - config.getStringList(key + "." + option + "." + requirement + ".value").toArray(new String[0]), - Objects.equals(config.getString(key + "." + option + "." + requirement + ".mode"), "&&"), - config.getString(key + "." + option + "." + requirement + ".message") - )); - case "world" -> requirementList.add(new RequirementWorld( - config.getStringList(key + "." + option + "." + requirement + ".value").toArray(new String[0]), - Objects.equals(config.getString(key + "." + option + "." + requirement + ".mode"), "&&"), - config.getString(key + "." + option + "." + requirement + ".message") - )); - case "permission" -> requirementList.add(new RequirementPermission( - config.getStringList(key + "." + option + "." + requirement + ".value").toArray(new String[0]), - Objects.equals(config.getString(key + "." + option + "." + requirement + ".mode"), "&&"), - config.getString(key + "." + option + "." + requirement + ".message") - )); - case "papi-condition" -> requirementList.add(new CustomPapi( - Objects.requireNonNull(config.getConfigurationSection(key + "." + option + "." + requirement + ".value")).getValues(false), - config.getString(key + "." + option + "." + requirement + ".message") - )); - } - } - if (option.equals("harvest-requirements")) crop.setHarvestRequirements(requirementList.toArray(new RequirementInterface[0])); - else crop.setPlantRequirements(requirementList.toArray(new RequirementInterface[0])); - } - } - } - crop.setCanRotate(config.getBoolean(key + ".rotation", true)); - CROPS.put(key, crop); - } - AdventureUtil.consoleMessage("[CustomCrops] Loaded " + CROPS.size() + " crops"); - } -} diff --git a/src/main/java/net/momirealms/customcrops/config/FertilizerConfig.java b/src/main/java/net/momirealms/customcrops/config/FertilizerConfig.java deleted file mode 100644 index 93191c9..0000000 --- a/src/main/java/net/momirealms/customcrops/config/FertilizerConfig.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.config; - -import net.momirealms.customcrops.objects.QualityRatio; -import net.momirealms.customcrops.objects.fertilizer.*; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Particle; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.util.HashMap; -import java.util.Objects; - -public class FertilizerConfig { - - public static HashMap FERTILIZERS; - - public static void load() { - FERTILIZERS = new HashMap<>(16); - YamlConfiguration config = ConfigUtil.getConfig("fertilizers_" + MainConfig.customPlugin + ".yml"); - int amount = 0; - for (String key : config.getKeys(false)) { - switch (key) { - case "speed" -> { - for (String fertilizer : Objects.requireNonNull(config.getConfigurationSection(key)).getKeys(false)) { - SpeedGrow speedGrow = new SpeedGrow( - fertilizer, - config.getInt(key + "." + fertilizer + ".times", 14), - config.getDouble(key + "." +fertilizer + ".chance", 0.01), - config.getBoolean(key + "." + fertilizer + ".before-plant", true), - config.getString(key + "." + fertilizer + ".name") - ); - if (config.contains(key + "." + fertilizer + ".particle")) { - speedGrow.setParticle(Particle.valueOf(config.getString(key + "." + fertilizer + ".particle", "VILLAGER_HAPPY").toUpperCase())); - } - FERTILIZERS.put(config.getString(key + "." + fertilizer + ".item"), speedGrow); - FERTILIZERS.put(fertilizer, speedGrow); - amount++; - } - } - case "gigantic" -> { - for (String fertilizer : Objects.requireNonNull(config.getConfigurationSection(key)).getKeys(false)) { - Gigantic gigantic = new Gigantic( - fertilizer, - config.getInt(key + "." + fertilizer + ".times", 14), - config.getDouble(key + "." +fertilizer + ".chance", 0.01), - config.getBoolean(key + "." + fertilizer + ".before-plant", true), - config.getString(key + "." + fertilizer + ".name") - ); - if (config.contains(key + "." + fertilizer + ".particle")) { - gigantic.setParticle(Particle.valueOf(config.getString(key + "." + fertilizer + ".particle", "VILLAGER_HAPPY").toUpperCase())); - } - FERTILIZERS.put(config.getString(key + "." + fertilizer + ".item"), gigantic); - FERTILIZERS.put(fertilizer, gigantic); - amount++; - } - } - case "retaining" -> { - for (String fertilizer : Objects.requireNonNull(config.getConfigurationSection(key)).getKeys(false)) { - RetainingSoil retainingSoil = new RetainingSoil( - fertilizer, - config.getInt(key + "." + fertilizer + ".times", 14), - config.getDouble(key + "." +fertilizer + ".chance", 0.01), - config.getBoolean(key + "." + fertilizer + ".before-plant", true), - config.getString(key + "." + fertilizer + ".name") - ); - if (config.contains(key + "." + fertilizer + ".particle")) { - retainingSoil.setParticle(Particle.valueOf(config.getString(key + "." + fertilizer + ".particle", "VILLAGER_HAPPY").toUpperCase())); - } - FERTILIZERS.put(config.getString(key + "." + fertilizer + ".item"), retainingSoil); - FERTILIZERS.put(fertilizer, retainingSoil); - amount++; - } - } - case "quantity" -> { - for (String fertilizer : Objects.requireNonNull(config.getConfigurationSection(key)).getKeys(false)) { - YieldIncreasing yieldIncreasing = new YieldIncreasing( - fertilizer, - config.getInt(key + "." + fertilizer + ".times", 14), - config.getDouble(key + "." +fertilizer + ".chance", 0.01), - config.getInt(key + "." +fertilizer + ".bonus",1), - config.getBoolean(key + "." + fertilizer + ".before-plant", true), - config.getString(key + "." + fertilizer + ".name") - ); - if (config.contains(key + "." + fertilizer + ".particle")) { - yieldIncreasing.setParticle(Particle.valueOf(config.getString(key + "." + fertilizer + ".particle", "VILLAGER_HAPPY").toUpperCase())); - } - FERTILIZERS.put(config.getString(key + "." + fertilizer + ".item"), yieldIncreasing); - FERTILIZERS.put(fertilizer, yieldIncreasing); - amount++; - } - } - case "quality" -> { - for (String fertilizer : Objects.requireNonNull(config.getConfigurationSection(key)).getKeys(false)) { - String[] split = StringUtils.split(config.getString(key + "." + fertilizer + ".ratio"), "/"); - double[] weight = new double[3]; - weight[0] = Double.parseDouble(split[0]); - weight[1] = Double.parseDouble(split[1]); - weight[2] = Double.parseDouble(split[2]); - double weightTotal = weight[0] + weight[1] + weight[2]; - QualityRatio qualityRatio = new QualityRatio(weight[0]/(weightTotal), 1 - weight[1]/(weightTotal)); - QualityCrop qualityCrop = new QualityCrop( - fertilizer, - config.getInt(key + "." + fertilizer + ".times", 14), - config.getDouble(key + "." +fertilizer + ".chance", 0.01), - qualityRatio, - config.getBoolean(key + "." + fertilizer + ".before-plant", true), - config.getString(key + "." + fertilizer + ".name") - ); - if (config.contains(key + "." + fertilizer + ".particle")) { - qualityCrop.setParticle(Particle.valueOf(config.getString(key + "." + fertilizer + ".particle", "VILLAGER_HAPPY").toUpperCase())); - } - FERTILIZERS.put(config.getString(key + "." + fertilizer + ".item"), qualityCrop); - FERTILIZERS.put(fertilizer, qualityCrop); - amount++; - } - } - } - } - AdventureUtil.consoleMessage("[CustomCrops] Loaded " + amount + " fertilizers"); - } -} diff --git a/src/main/java/net/momirealms/customcrops/config/MainConfig.java b/src/main/java/net/momirealms/customcrops/config/MainConfig.java deleted file mode 100644 index 2e64795..0000000 --- a/src/main/java/net/momirealms/customcrops/config/MainConfig.java +++ /dev/null @@ -1,445 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.config; - -import net.momirealms.customcrops.helper.Log; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import net.momirealms.customcrops.integrations.JobInterface; -import net.momirealms.customcrops.integrations.SkillInterface; -import net.momirealms.customcrops.integrations.job.EcoJobsHook; -import net.momirealms.customcrops.integrations.job.JobsRebornHook; -import net.momirealms.customcrops.integrations.protection.*; -import net.momirealms.customcrops.integrations.skill.AureliumsHook; -import net.momirealms.customcrops.integrations.skill.EcoSkillsHook; -import net.momirealms.customcrops.integrations.skill.MMOCoreHook; -import net.momirealms.customcrops.integrations.skill.mcMMOHook; -import net.momirealms.customcrops.objects.QualityRatio; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.World; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class MainConfig { - - public static List worldNameList; - public static boolean whiteOrBlack; - public static boolean dropLootsInAllWorlds; - public static String customPlugin; - public static boolean OraxenHook; - public static boolean realisticSeasonHook; - public static boolean cropMode; - public static List internalAntiGriefs = new ArrayList<>(); - public static List externalAntiGriefs = new ArrayList<>(); - public static SkillInterface skillInterface; - public static JobInterface jobInterface; - public static double dryGrowChance; - public static boolean limitation; - public static int wireAmount; - public static int frameAmount; - public static QualityRatio qualityRatio; - public static boolean canRightClickHarvest; - public static boolean emptyHand; - public static int waterBucketToSprinkler; - public static int waterToWaterCan; - public static int wateringCanToSprinkler; - public static int timeToGrow; - public static int timeToWork; - public static int timeToDry; - public static String lang; - public static boolean preventInWrongSeason; - public static boolean notifyInWrongSeason; - public static boolean enableBoneMeal; - public static double boneMealChance; - public static Particle boneMealSuccess; - public static boolean enableCrow; - public static double crowChance; - public static boolean enableActionBar; - public static String actionBarLeft; - public static String actionBarFull; - public static String actionBarEmpty; - public static String actionBarRight; - public static boolean enableSprinklerInfo; - public static double sprinklerInfoY; - public static int sprinklerInfoDuration; - public static String sprinklerLeft; - public static String sprinklerFull; - public static String sprinklerEmpty; - public static String sprinklerRight; - public static boolean enableFertilizerInfo; - public static double fertilizerInfoY; - public static int fertilizerInfoDuration; - public static String fertilizerInfo; - public static boolean enableParticles; - public static boolean enableAnimations; - public static double animationYOffset; - public static boolean autoGrow; - public static boolean enableCompensation; - public static boolean syncSeason; - public static World syncWorld; - public static boolean autoBackUp; - public static boolean needSkyLight; - public static int skyLightLevel; - public static boolean enableWaterCanLore; - public static boolean enablePacketLore; - public static List waterCanLore; - public static String waterBarLeft; - public static String waterBarFull; - public static String waterBarEmpty; - public static String waterBarRight; - public static boolean topOrBottom; - public static boolean enableSeasonBroadcast; - public static String[] springMsg; - public static String[] summerMsg; - public static String[] autumnMsg; - public static String[] winterMsg; - public static boolean enableSeasonChangeCmd; - public static String[] winterCmd; - public static String[] springCmd; - public static String[] summerCmd; - public static String[] autumnCmd; - public static String worldFolder; - public static boolean rightHarvestVanilla; - public static boolean preventPlantVanilla; - public static Material[] preventPlantVanillaArray; - public static boolean enableConvert; - public static boolean enableSkillBonus; - public static double bonusPerLevel; - public static HashMap vanilla2Crops; - public static int saveInterval; - public static boolean dryMakesCropDead; - public static double dryDeadChance; - public static boolean metrics; - - public static void load() { - ConfigUtil.update("config.yml"); - YamlConfiguration config = ConfigUtil.getConfig("config.yml"); - - lang = config.getString("lang","english"); - metrics = config.getBoolean("metrics", true); - - whiteOrBlack = config.getString("worlds.mode","whitelist").equals("whitelist"); - worldNameList = config.getStringList("worlds.list"); - - worldFolder = StringUtils.replace(config.getString("worlds.worlds-folder",""), "\\", File.separator); - - cropMode = config.getString("mechanics.crops-mode", "tripwire").equals("tripwire"); - limitation = config.getBoolean("optimization.limitation.enable", true); - wireAmount = config.getInt("optimization.limitation.tripwire-amount", 64); - frameAmount = config.getInt("optimization.limitation.itemframe-amount", 64); - - if (MainConfig.cropMode) AdventureUtil.consoleMessage("[CustomCrops] Crop Mode: Tripwire"); - else AdventureUtil.consoleMessage("[CustomCrops] Crop Mode: ItemFrame"); - - autoGrow = config.getBoolean("mechanics.auto-grow.enable", true); - enableCompensation = config.getBoolean("mechanics.auto-grow.time-compensation", true); - timeToGrow = config.getInt("mechanics.auto-grow.crops-grow-time", 20000); - timeToWork = config.getInt("mechanics.auto-grow.sprinkler-work-time", 300); - timeToDry = config.getInt("mechanics.auto-grow.pot-dry-time", 200); - dryGrowChance = config.getDouble("mechanics.dry-pot-grow-chance", 0.5); - dropLootsInAllWorlds = config.getBoolean("mechanics.drop-loots-in-all-worlds", false); - - dryMakesCropDead = config.getBoolean("mechanics.dry-pot-makes-crop-dead.enable", false); - dryDeadChance = config.getDouble("mechanics.dry-pot-makes-crop-dead.chance", 0.6); - - waterBucketToSprinkler = config.getInt("mechanics.fill.water-bucket-to-sprinkler", 3); - waterToWaterCan = config.getInt("mechanics.fill.waterblock-to-watering-can", 1); - wateringCanToSprinkler = config.getInt("mechanics.fill.watering-can-to-sprinkler", 1); - - canRightClickHarvest = config.getBoolean("mechanics.right-click-harvest.enable", true); - emptyHand = config.getBoolean("mechanics.right-click-harvest.require-empty-hand", true); - preventInWrongSeason = config.getBoolean("mechanics.prevent-plant-if-wrong-season", true); - notifyInWrongSeason = config.getBoolean("mechanics.should-notify-if-wrong-season", true); - - enableBoneMeal = config.getBoolean("mechanics.bone-meal.enable", true); - boneMealChance = config.getDouble("mechanics.bone-meal.chance", 0.5); - - syncSeason = config.getBoolean("mechanics.season.sync-seasons.enable", false); - syncWorld = Bukkit.getWorld(config.getString("mechanics.season.sync-seasons.world", "world")); - - autoBackUp = config.getBoolean("optimization.auto-back-up", true); - - enableParticles = !config.getBoolean("optimization.disable-water-particles", false); - enableAnimations = config.getBoolean("mechanics.sprinkler-animation.enable", true); - animationYOffset = config.getDouble("mechanics.sprinkler-animation.y-offset", 1); - - enableSeasonBroadcast = config.getBoolean("season-broadcast.enable", true); - springMsg = config.getStringList("season-broadcast.spring").toArray(new String[0]); - summerMsg = config.getStringList("season-broadcast.summer").toArray(new String[0]); - autumnMsg = config.getStringList("season-broadcast.autumn").toArray(new String[0]); - winterMsg = config.getStringList("season-broadcast.winter").toArray(new String[0]); - enableSeasonChangeCmd = config.getBoolean("season-change-command.enable", false); - springCmd = config.getStringList("season-change-command.spring").toArray(new String[0]); - summerCmd = config.getStringList("season-change-command.summer").toArray(new String[0]); - autumnCmd = config.getStringList("season-change-command.autumn").toArray(new String[0]); - winterCmd = config.getStringList("season-change-command.winter").toArray(new String[0]); - - try { - boneMealSuccess = Particle.valueOf(config.getString("mechanics.bone-meal.success-particle", "VILLAGER_HAPPY")); - } - catch (IllegalArgumentException e) { - AdventureUtil.consoleMessage("[CustomCrops] Illegal Particle Argument for Bone Meal"); - } - - enableCrow = config.getBoolean("mechanics.crow.enable", false); - crowChance = config.getDouble("mechanics.crow.chance", 0.001); - - skyLightLevel = config.getInt("mechanics.dead-if-no-sky-light.level", 10); - needSkyLight = config.getBoolean("mechanics.dead-if-no-sky-light.enable", true); - - String[] split = StringUtils.split(config.getString("mechanics.default-quality-ratio", "17/2/1"), "/"); - double[] weight = new double[3]; - assert split != null; - weight[0] = Double.parseDouble(split[0]); - weight[1] = Double.parseDouble(split[1]); - weight[2] = Double.parseDouble(split[2]); - double weightTotal = weight[0] + weight[1] + weight[2]; - qualityRatio = new QualityRatio(weight[0]/(weightTotal), 1 - weight[1]/(weightTotal)); - - enableActionBar = config.getBoolean("actionbar.enable", true); - actionBarLeft = config.getString("actionbar.left", "뀂"); - actionBarFull = config.getString("actionbar.full", "뀁뀃"); - actionBarEmpty = config.getString("actionbar.empty", "뀁뀄"); - actionBarRight = config.getString("actionbar.right", "뀁뀅"); - - enableSprinklerInfo = config.getBoolean("hologram.sprinkler-info.enable", true); - sprinklerInfoY = config.getDouble("hologram.sprinkler-info.y-offset", -0.2); - sprinklerInfoDuration = config.getInt("hologram.sprinkler-info.duration", 1); - sprinklerLeft = config.getString("hologram.sprinkler-info.left", "뀂"); - sprinklerFull = config.getString("hologram.sprinkler-info.full", "뀁뀃"); - sprinklerEmpty = config.getString("hologram.sprinkler-info.empty", "뀁뀄"); - sprinklerRight = config.getString("hologram.sprinkler-info.right", "뀁뀅"); - - enableFertilizerInfo = config.getBoolean("hologram.fertilizer-info.enable", true); - fertilizerInfoY = config.getDouble("hologram.fertilizer-info.y-offset", -0.2); - fertilizerInfoDuration = config.getInt("hologram.fertilizer-info.duration", 1); - fertilizerInfo = config.getString("hologram.fertilizer-info.text", "{fertilizer} {times}/{max_times}"); - - enableWaterCanLore = config.getBoolean("watering-can-lore.enable", true); - enablePacketLore = config.getBoolean("watering-can-lore.packets.enable", true); - topOrBottom = config.getBoolean("watering-can-lore.packets.top-or-bottom", true); - waterCanLore = config.getStringList("watering-can-lore.lore"); - waterBarLeft = config.getString("watering-can-lore.water-bar.left", "뀂"); - waterBarFull = config.getString("watering-can-lore.water-bar.full", "뀁뀃"); - waterBarEmpty = config.getString("watering-can-lore.water-bar.empty", "뀁뀄"); - waterBarRight = config.getString("watering-can-lore.water-bar.right", "뀁뀅"); - - enableSkillBonus = config.getBoolean("mechanics.skill-bonus.enable", false); - bonusPerLevel = config.getDouble("mechanics.skill-bonus.bonus-per-level", 0.001); - - rightHarvestVanilla = config.getBoolean("mechanics.vanilla-crops.right-click-harvest", false); - preventPlantVanilla = config.getBoolean("mechanics.vanilla-crops.prevent-plant.enable", false); - - List preventPlantVanillaList = new ArrayList<>(); - for (String key : config.getStringList("mechanics.vanilla-crops.prevent-plant.list")) { - try { - preventPlantVanillaList.add(Material.valueOf(key.toUpperCase())); - } - catch (Exception e) { - AdventureUtil.consoleMessage("[CustomCrops] Vanilla Block " + key + " doesn't exist"); - } - } - preventPlantVanillaArray = preventPlantVanillaList.toArray(new Material[0]); - - enableConvert = config.getBoolean("mechanics.vanilla-crops.convert-to-customcrops.enable", false); - if (enableConvert) { - vanilla2Crops = new HashMap<>(); - for (String key : config.getConfigurationSection("mechanics.vanilla-crops.convert-to-customcrops.list").getKeys(false)) { - try { - Material material = Material.valueOf(key.toUpperCase()); - vanilla2Crops.put(material, config.getString("mechanics.vanilla-crops.convert-to-customcrops.list." + key)); - } - catch (Exception e) { - AdventureUtil.consoleMessage("[CustomCrops] Vanilla Item " + key + " doesn't exist"); - } - } - } else { - vanilla2Crops = null; - } - - saveInterval = config.getInt("other-settings.data-save-interval", 3); - - internalAntiGriefs.clear(); - if (config.getBoolean("integration.Residence",false)){ - if (Bukkit.getPluginManager().getPlugin("Residence") == null) Log.warn("Failed to initialize Residence!"); - else { - internalAntiGriefs.add(new ResidenceHook()); - hookMessage("Residence"); - } - } - if (config.getBoolean("integration.Kingdoms",false)){ - if (Bukkit.getPluginManager().getPlugin("Kingdoms") == null) Log.warn("Failed to initialize Kingdoms!"); - else { - internalAntiGriefs.add(new KingdomsXHook()); - hookMessage("Kingdoms"); - } - } - if (config.getBoolean("integration.WorldGuard",false)){ - if (Bukkit.getPluginManager().getPlugin("WorldGuard") == null) Log.warn("Failed to initialize WorldGuard!"); - else { - internalAntiGriefs.add(new WorldGuardHook()); - hookMessage("WorldGuard"); - } - } - if (config.getBoolean("integration.GriefDefender",false)){ - if(Bukkit.getPluginManager().getPlugin("GriefDefender") == null) Log.warn("Failed to initialize GriefDefender!"); - else { - internalAntiGriefs.add(new GriefDefenderHook()); - hookMessage("GriefDefender"); - } - } - if (config.getBoolean("integration.PlotSquared",false)){ - if(Bukkit.getPluginManager().getPlugin("PlotSquared") == null) Log.warn("Failed to initialize PlotSquared!"); - else { - internalAntiGriefs.add(new PlotSquaredHook()); - hookMessage("PlotSquared"); - } - } - if (config.getBoolean("integration.Towny",false)){ - if (Bukkit.getPluginManager().getPlugin("Towny") == null) Log.warn("Failed to initialize Towny!"); - else { - internalAntiGriefs.add(new TownyHook()); - hookMessage("Towny"); - } - } - if (config.getBoolean("integration.Lands",false)){ - if (Bukkit.getPluginManager().getPlugin("Lands") == null) Log.warn("Failed to initialize Lands!"); - else { - internalAntiGriefs.add(new LandsHook()); - hookMessage("Lands"); - } - } - if (config.getBoolean("integration.GriefPrevention",false)){ - if (Bukkit.getPluginManager().getPlugin("GriefPrevention") == null) Log.warn("Failed to initialize GriefPrevention!"); - else { - internalAntiGriefs.add(new GriefPreventionHook()); - hookMessage("GriefPrevention"); - } - } - if (config.getBoolean("integration.CrashClaim",false)){ - if (Bukkit.getPluginManager().getPlugin("CrashClaim") == null) Log.warn("Failed to initialize CrashClaim!"); - else { - internalAntiGriefs.add(new CrashClaimHook()); - hookMessage("CrashClaim"); - } - } - if (config.getBoolean("integration.BentoBox",false)){ - if (Bukkit.getPluginManager().getPlugin("BentoBox") == null) Log.warn("Failed to initialize BentoBox!"); - else { - internalAntiGriefs.add(new BentoBoxHook()); - hookMessage("BentoBox"); - } - } - if (config.getBoolean("integration.IridiumSkyblock",false)){ - if (Bukkit.getPluginManager().getPlugin("IridiumSkyblock") == null) Log.warn("Failed to initialize IridiumSkyblock!"); - else { - internalAntiGriefs.add(new IridiumSkyblockHook()); - hookMessage("IridiumSkyblock"); - } - } - if (config.getBoolean("integration.SuperiorSkyBlock",false)){ - if (Bukkit.getPluginManager().getPlugin("SuperiorSkyBlock2") == null) Log.warn("Failed to initialize SuperiorSkyBlock!"); - else { - internalAntiGriefs.add(new SuperiorSkyBlockHook()); - hookMessage("SuperiorSkyBlock"); - } - } - - if (config.getBoolean("integration.AureliumSkills")) { - if (Bukkit.getPluginManager().getPlugin("AureliumSkills") == null) Log.warn("Failed to initialize AureliumSkills!"); - else { - skillInterface = new AureliumsHook(); - hookMessage("AureliumSkills"); - } - } - if (config.getBoolean("integration.mcMMO")) { - if (Bukkit.getPluginManager().getPlugin("mcMMO") == null) Log.warn("Failed to initialize mcMMO!"); - else { - skillInterface = new mcMMOHook(); - hookMessage("mcMMO"); - } - } - if (config.getBoolean("integration.MMOCore")) { - if (Bukkit.getPluginManager().getPlugin("MMOCore") == null) Log.warn("Failed to initialize MMOCore!"); - else { - skillInterface = new MMOCoreHook(); - hookMessage("MMOCore"); - } - } - if (config.getBoolean("integration.EcoSkills")) { - if (Bukkit.getPluginManager().getPlugin("EcoSkills") == null) Log.warn("Failed to initialize EcoSkills!"); - else { - skillInterface = new EcoSkillsHook(); - hookMessage("EcoSkills"); - } - } - if (config.getBoolean("integration.JobsReborn")) { - if (Bukkit.getPluginManager().getPlugin("Jobs") == null) Log.warn("Failed to initialize JobsReborn!"); - else { - jobInterface = new JobsRebornHook(); - hookMessage("JobsReborn"); - } - } else if (config.getBoolean("integration.EcoJobs")) { - if (Bukkit.getPluginManager().getPlugin("EcoJobs") == null) Log.warn("Failed to initialize EcoJobs!"); - else { - jobInterface = new EcoJobsHook(); - hookMessage("EcoJobs"); - } - } - - realisticSeasonHook = false; - if (config.getBoolean("integration.RealisticSeasons")) { - if (Bukkit.getPluginManager().getPlugin("RealisticSeasons") == null) Log.warn("Failed to initialize RealisticSeasons!"); - else realisticSeasonHook = true; - } - } - - public static List getWorldNameList() { - if (whiteOrBlack) { - return worldNameList; - } - else { - List allWorldNames = new ArrayList<>(); - for (World world : Bukkit.getWorlds()) { - allWorldNames.add(world.getName()); - } - allWorldNames.removeAll(worldNameList); - return allWorldNames; - } - } - - private static void hookMessage(String plugin){ - AdventureUtil.consoleMessage("[CustomCrops] " + plugin + " Hooked!"); - } - - public static void registerAntiGrief(CCAntiGrief ccAntiGrief) { - externalAntiGriefs.add(ccAntiGrief); - hookMessage(ccAntiGrief.getName()); - } - - public static void unregisterAntiGrief(CCAntiGrief ccAntiGrief) { - externalAntiGriefs.remove(ccAntiGrief); - } -} diff --git a/src/main/java/net/momirealms/customcrops/config/MessageConfig.java b/src/main/java/net/momirealms/customcrops/config/MessageConfig.java deleted file mode 100644 index 5e9d63a..0000000 --- a/src/main/java/net/momirealms/customcrops/config/MessageConfig.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.config; - -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; - -public class MessageConfig { - - public static String spring; - public static String summer; - public static String autumn; - public static String winter; - public static String seasonDisabled; - public static String autoSeasonDisabled; - public static String prefix; - public static String wrongArgs; - public static String unavailableArgs; - public static String lackArgs; - public static String reload; - public static String noPerm; - public static String limitWire; - public static String limitFrame; - public static String growSimulation; - public static String backUp; - public static String setSeason; - public static String beforePlant; - public static String noSeason; - public static String worldNotExists; - public static String seasonNotExists; - public static String wrongSeason; - public static String nonArgs; - - public static void load() { - YamlConfiguration config = ConfigUtil.getConfig("messages" + File.separator + "messages_" + MainConfig.lang +".yml"); - prefix = config.getString("messages.prefix"); - reload = config.getString("messages.reload"); - noPerm = config.getString("messages.no-perm"); - lackArgs = config.getString("messages.lack-args"); - unavailableArgs = config.getString("messages.invalid-args"); - wrongArgs = config.getString("messages.wrong-args"); - nonArgs = config.getString("messages.none-args"); - spring = config.getString("messages.spring"); - summer = config.getString("messages.summer"); - autumn = config.getString("messages.autumn"); - winter = config.getString("messages.winter"); - limitWire = config.getString("messages.limitation-tripwire"); - limitFrame = config.getString("messages.limitation-itemframe"); - growSimulation = config.getString("messages.grow-simulation"); - backUp = config.getString("messages.back-up"); - setSeason = config.getString("messages.set-season"); - beforePlant = config.getString("messages.before-plant"); - seasonDisabled = config.getString("messages.season-disabled"); - autoSeasonDisabled = config.getString("messages.auto-season-disabled"); - noSeason = config.getString("messages.no-season"); - worldNotExists = config.getString("messages.world-not-exist"); - seasonNotExists = config.getString("messages.season-not-exist"); - wrongSeason = config.getString("messages.wrong-season"); - } -} diff --git a/src/main/java/net/momirealms/customcrops/config/SeasonConfig.java b/src/main/java/net/momirealms/customcrops/config/SeasonConfig.java deleted file mode 100644 index 18f1165..0000000 --- a/src/main/java/net/momirealms/customcrops/config/SeasonConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.config; - -import org.bukkit.configuration.file.YamlConfiguration; - -public class SeasonConfig { - - public static boolean enable; - public static boolean auto; - public static int duration; - public static boolean greenhouse; - public static int effectiveRange; - - public static void load() { - - YamlConfiguration config = ConfigUtil.getConfig("config.yml"); - enable = config.getBoolean("mechanics.season.enable", true); - auto = config.getBoolean("mechanics.season.auto-season-change.enable", true); - duration = config.getInt("mechanics.season.auto-season-change.duration", 28); - greenhouse = config.getBoolean("mechanics.season.greenhouse.enable", true); - effectiveRange = config.getInt("mechanics.season.greenhouse.range", 5); - } -} diff --git a/src/main/java/net/momirealms/customcrops/config/SoundConfig.java b/src/main/java/net/momirealms/customcrops/config/SoundConfig.java deleted file mode 100644 index 72af3e3..0000000 --- a/src/main/java/net/momirealms/customcrops/config/SoundConfig.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.config; - -import net.kyori.adventure.key.Key; -import net.kyori.adventure.sound.Sound; -import net.momirealms.customcrops.objects.WrappedSound; -import org.bukkit.configuration.file.YamlConfiguration; - -public class SoundConfig { - - public static WrappedSound waterPot; - public static WrappedSound addWaterToCan; - public static WrappedSound addWaterToSprinkler; - public static WrappedSound placeSprinkler; - public static WrappedSound plantSeed; - public static WrappedSound useFertilizer; - public static WrappedSound harvestCrop; - public static WrappedSound boneMeal; - public static WrappedSound surveyor; - - public static void load(){ - YamlConfiguration config = ConfigUtil.getConfig("config.yml"); - waterPot = new WrappedSound( - Sound.Source.valueOf(config.getString("sounds.water-pot.type","player").toUpperCase()), - Key.key(config.getString("sounds.water-pot.sound", "minecraft:block.water.ambient")), - config.getBoolean("sounds.water-pot.enable", true) - ); - addWaterToCan = new WrappedSound( - Sound.Source.valueOf(config.getString("sounds.add-water-to-can.type","player").toUpperCase()), - Key.key(config.getString("sounds.add-water-to-can.sound", "minecraft:item.bucket.fill")), - config.getBoolean("sounds.add-water-to-can.enable", true) - ); - addWaterToSprinkler = new WrappedSound( - Sound.Source.valueOf(config.getString("sounds.add-water-to-sprinkler.type","player").toUpperCase()), - Key.key(config.getString("sounds.add-water-to-sprinkler.sound", "minecraft:item.bucket.fill")), - config.getBoolean("sounds.add-water-to-sprinkler.enable", true) - ); - placeSprinkler = new WrappedSound( - Sound.Source.valueOf(config.getString("sounds.place-sprinkler.type","player").toUpperCase()), - Key.key(config.getString("sounds.place-sprinkler.sound", "minecraft:block.bone_block.place")), - config.getBoolean("sounds.place-sprinkler.enable", true) - ); - plantSeed = new WrappedSound( - Sound.Source.valueOf(config.getString("sounds.plant-seed.type","player").toUpperCase()), - Key.key(config.getString("sounds.plant-seed.sound", "minecraft:item.hoe.till")), - config.getBoolean("sounds.plant-seed.enable", true) - ); - useFertilizer = new WrappedSound( - Sound.Source.valueOf(config.getString("sounds.use-fertilizer.type","player").toUpperCase()), - Key.key(config.getString("sounds.use-fertilizer.sound", "minecraft:item.hoe.till")), - config.getBoolean("sounds.use-fertilizer.enable", true) - ); - harvestCrop = new WrappedSound( - Sound.Source.valueOf(config.getString("sounds.harvest-crops.type", "player").toUpperCase()), - Key.key(config.getString("sounds.harvest-crops.sound", "minecraft:block.crop.break")), - config.getBoolean("sounds.harvest-crops.enable", true) - ); - boneMeal = new WrappedSound( - Sound.Source.valueOf(config.getString("sounds.bonemeal.type","player").toUpperCase()), - Key.key(config.getString("sounds.bonemeal.sound", "minecraft:item.hoe.till")), - config.getBoolean("sounds.bonemeal.enable", true) - ); - surveyor = new WrappedSound( - Sound.Source.valueOf(config.getString("sounds.surveyor.type","player").toUpperCase()), - Key.key(config.getString("sounds.surveyor.sound", "minecraft:block.note_block.pling")), - config.getBoolean("sounds.surveyor.enable", true) - ); - } -} diff --git a/src/main/java/net/momirealms/customcrops/config/SprinklerConfig.java b/src/main/java/net/momirealms/customcrops/config/SprinklerConfig.java deleted file mode 100644 index 960d7ab..0000000 --- a/src/main/java/net/momirealms/customcrops/config/SprinklerConfig.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.config; - -import net.momirealms.customcrops.objects.Sprinkler; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.util.HashMap; - -public class SprinklerConfig { - - public static HashMap SPRINKLERS_CONFIG; - public static HashMap SPRINKLERS_2D; - public static HashMap SPRINKLERS_3D; - - public static void load() { - SPRINKLERS_3D = new HashMap<>(8); - SPRINKLERS_2D = new HashMap<>(8); - SPRINKLERS_CONFIG = new HashMap<>(8); - YamlConfiguration config = ConfigUtil.getConfig("sprinklers_" + MainConfig.customPlugin + ".yml"); - - int amount = 0; - for (String key : config.getKeys(false)) { - - Sprinkler sprinkler = new Sprinkler( - key, - config.getInt(key + ".range", 1), - config.getInt(key + ".max-water-storage", 5) - ); - String twoD = config.getString(key + ".2Ditem"); - String threeD = config.getString(key + ".3Ditem"); - sprinkler.setTwoD(twoD); - sprinkler.setThreeD(threeD); - SPRINKLERS_CONFIG.put(key + "CONFIG", sprinkler); - SPRINKLERS_2D.put(twoD, sprinkler); - SPRINKLERS_3D.put(threeD, sprinkler); - amount++; - } - - AdventureUtil.consoleMessage("[CustomCrops] Loaded " + amount + " sprinklers"); - } -} diff --git a/src/main/java/net/momirealms/customcrops/config/WaterCanConfig.java b/src/main/java/net/momirealms/customcrops/config/WaterCanConfig.java deleted file mode 100644 index 044dbfd..0000000 --- a/src/main/java/net/momirealms/customcrops/config/WaterCanConfig.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.config; - -import net.momirealms.customcrops.objects.WaterCan; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.util.HashMap; - -public class WaterCanConfig { - - public static HashMap CANS = new HashMap<>(); - - public static void load() { - CANS = new HashMap<>(8); - YamlConfiguration config = ConfigUtil.getConfig("watercans_" + MainConfig.customPlugin + ".yml"); - for (String key : config.getKeys(false)) { - WaterCan waterCan = new WaterCan( - config.getInt(key + ".max-water-storage"), - config.getInt(key + ".width"), - config.getInt(key + ".length") - ); - CANS.put(config.getString(key + ".item"), waterCan); - } - AdventureUtil.consoleMessage("[CustomCrops] Loaded " + CANS.size() + " watering cans"); - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/helper/LibraryLoader.java b/src/main/java/net/momirealms/customcrops/helper/LibraryLoader.java index 6e03959..932e553 100644 --- a/src/main/java/net/momirealms/customcrops/helper/LibraryLoader.java +++ b/src/main/java/net/momirealms/customcrops/helper/LibraryLoader.java @@ -28,7 +28,7 @@ package net.momirealms.customcrops.helper; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import net.momirealms.customcrops.CustomCrops; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.InputStream; @@ -37,6 +37,7 @@ import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.util.Objects; +import java.util.StringJoiner; /** * Resolves {@link MavenLibrary} annotations for a class, and loads the dependency @@ -45,7 +46,7 @@ import java.util.Objects; public final class LibraryLoader { @SuppressWarnings("Guava") - private static final Supplier URL_INJECTOR = Suppliers.memoize(() -> URLClassLoaderAccess.create((URLClassLoader) CustomCrops.plugin.getClass().getClassLoader())); + private static final Supplier URL_INJECTOR = Suppliers.memoize(() -> URLClassLoaderAccess.create((URLClassLoader) CustomCrops.getInstance().getClass().getClassLoader())); /** * Resolves all {@link MavenLibrary} annotations on the given object. @@ -63,10 +64,6 @@ public final class LibraryLoader { */ public static void loadAll(Class clazz) { MavenLibrary[] libs = clazz.getDeclaredAnnotationsByType(MavenLibrary.class); - if (libs == null) { - return; - } - for (MavenLibrary lib : libs) { load(lib.groupId(), lib.artifactId(), lib.version(), lib.repo().url()); } @@ -78,7 +75,7 @@ public final class LibraryLoader { public static void load(Dependency d) { //Log.info(String.format("Loading dependency %s:%s:%s from %s", d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getRepoUrl())); - String name = d.getArtifactId() + "-" + d.getVersion(); + String name = d.artifactId() + "-" + d.version(); File saveLocation = new File(getLibFolder(d), name + ".jar"); if (!saveLocation.exists()) { @@ -109,90 +106,68 @@ public final class LibraryLoader { } private static File getLibFolder(Dependency dependency) { - File pluginDataFolder = CustomCrops.plugin.getDataFolder(); + File pluginDataFolder = CustomCrops.getInstance().getDataFolder(); File serverDir = pluginDataFolder.getParentFile().getParentFile(); File helperDir = new File(serverDir, "libraries"); - String[] split = StringUtils.split(dependency.getGroupId(), "."); + String[] split = StringUtils.split(dependency.groupId(), "."); File jarDir; - if (split.length > 1){ - jarDir = new File(helperDir, split[0] + File.separator + split[1] + File.separator + dependency.artifactId + File.separator + dependency.version ); - }else { - jarDir = new File(helperDir, dependency.getGroupId() + File.separator + dependency.artifactId + File.separator + dependency.version ); + StringJoiner stringJoiner = new StringJoiner(File.separator); + for (String str : split) { + stringJoiner.add(str); } + jarDir = new File(helperDir, stringJoiner + File.separator + dependency.artifactId + File.separator + dependency.version); jarDir.mkdirs(); return jarDir; } - public static final class Dependency { - private final String groupId; - private final String artifactId; - private final String version; - private final String repoUrl; - - public Dependency(String groupId, String artifactId, String version, String repoUrl) { - this.groupId = Objects.requireNonNull(groupId, "groupId"); - this.artifactId = Objects.requireNonNull(artifactId, "artifactId"); - this.version = Objects.requireNonNull(version, "version"); - this.repoUrl = Objects.requireNonNull(repoUrl, "repoUrl"); - } - - public String getGroupId() { - return this.groupId; - } - - public String getArtifactId() { - return this.artifactId; - } - - public String getVersion() { - return this.version; - } - - public String getRepoUrl() { - return this.repoUrl; - } - - public URL getUrl() throws MalformedURLException { - String repo = this.repoUrl; - if (!repo.endsWith("/")) { - repo += "/"; + public record Dependency(String groupId, String artifactId, String version, String repoUrl) { + public Dependency(String groupId, String artifactId, String version, String repoUrl) { + this.groupId = Objects.requireNonNull(groupId, "groupId"); + this.artifactId = Objects.requireNonNull(artifactId, "artifactId"); + this.version = Objects.requireNonNull(version, "version"); + this.repoUrl = Objects.requireNonNull(repoUrl, "repoUrl"); } - repo += "%s/%s/%s/%s-%s.jar"; - String url = String.format(repo, this.groupId.replace(".", "/"), this.artifactId, this.version, this.artifactId, this.version); - return new URL(url); - } + public URL getUrl() throws MalformedURLException { + String repo = this.repoUrl; + if (!repo.endsWith("/")) { + repo += "/"; + } + repo += "%s/%s/%s/%s-%s.jar"; - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof Dependency)) return false; - final Dependency other = (Dependency) o; - return this.getGroupId().equals(other.getGroupId()) && - this.getArtifactId().equals(other.getArtifactId()) && - this.getVersion().equals(other.getVersion()) && - this.getRepoUrl().equals(other.getRepoUrl()); - } + String url = String.format(repo, this.groupId.replace(".", "/"), this.artifactId, this.version, this.artifactId, this.version); + return new URL(url); + } - @Override - public int hashCode() { - final int PRIME = 59; - int result = 1; - result = result * PRIME + this.getGroupId().hashCode(); - result = result * PRIME + this.getArtifactId().hashCode(); - result = result * PRIME + this.getVersion().hashCode(); - result = result * PRIME + this.getRepoUrl().hashCode(); - return result; - } + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof final Dependency other)) return false; + return this.groupId().equals(other.groupId()) && + this.artifactId().equals(other.artifactId()) && + this.version().equals(other.version()) && + this.repoUrl().equals(other.repoUrl()); + } - @Override - public String toString() { - return "LibraryLoader.Dependency(" + - "groupId=" + this.getGroupId() + ", " + - "artifactId=" + this.getArtifactId() + ", " + - "version=" + this.getVersion() + ", " + - "repoUrl=" + this.getRepoUrl() + ")"; + @Override + public int hashCode() { + final int PRIME = 59; + int result = 1; + result = result * PRIME + this.groupId().hashCode(); + result = result * PRIME + this.artifactId().hashCode(); + result = result * PRIME + this.version().hashCode(); + result = result * PRIME + this.repoUrl().hashCode(); + return result; + } + + @Override + public String toString() { + return "LibraryLoader.Dependency(" + + "groupId=" + this.groupId() + ", " + + "artifactId=" + this.artifactId() + ", " + + "version=" + this.version() + ", " + + "repoUrl=" + this.repoUrl() + ")"; + } } - } } diff --git a/src/main/java/net/momirealms/customcrops/helper/Log.java b/src/main/java/net/momirealms/customcrops/helper/Log.java index d4b6600..faea565 100644 --- a/src/main/java/net/momirealms/customcrops/helper/Log.java +++ b/src/main/java/net/momirealms/customcrops/helper/Log.java @@ -37,27 +37,26 @@ import java.util.logging.Level; public final class Log { public static void info(@NotNull String s) { - CustomCrops.plugin.getLogger().info(s); + CustomCrops.getInstance().getLogger().info(s); } public static void warn(@NotNull String s) { - CustomCrops.plugin.getLogger().warning(s); + CustomCrops.getInstance().getLogger().warning(s); } public static void severe(@NotNull String s) { - CustomCrops.plugin.getLogger().severe(s); + CustomCrops.getInstance().getLogger().severe(s); } public static void warn(@NotNull String s, Throwable t) { - CustomCrops.plugin.getLogger().log(Level.WARNING, s, t); + CustomCrops.getInstance().getLogger().log(Level.WARNING, s, t); } public static void severe(@NotNull String s, Throwable t) { - CustomCrops.plugin.getLogger().log(Level.SEVERE, s, t); + CustomCrops.getInstance().getLogger().log(Level.SEVERE, s, t); } private Log() { throw new UnsupportedOperationException("This class cannot be instantiated"); } - } diff --git a/src/main/java/net/momirealms/customcrops/helper/URLClassLoaderAccess.java b/src/main/java/net/momirealms/customcrops/helper/URLClassLoaderAccess.java index e8ac038..0d7a2cc 100644 --- a/src/main/java/net/momirealms/customcrops/helper/URLClassLoaderAccess.java +++ b/src/main/java/net/momirealms/customcrops/helper/URLClassLoaderAccess.java @@ -135,5 +135,4 @@ public abstract class URLClassLoaderAccess { throw new UnsupportedOperationException(); } } - } diff --git a/src/main/java/net/momirealms/customcrops/helper/VersionHelper.java b/src/main/java/net/momirealms/customcrops/helper/VersionHelper.java index a3c3ab7..e2410f9 100644 --- a/src/main/java/net/momirealms/customcrops/helper/VersionHelper.java +++ b/src/main/java/net/momirealms/customcrops/helper/VersionHelper.java @@ -3,33 +3,58 @@ package net.momirealms.customcrops.helper; import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion; import de.tr7zw.changeme.nbtapi.utils.VersionChecker; import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.util.AdventureUtils; +import org.bukkit.Bukkit; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; import java.lang.reflect.Field; +import java.net.URL; +import java.net.URLConnection; public class VersionHelper { private boolean isNewerThan1_19_R2; - private String version; + private boolean isNewerThan1_19_R3; + private String server_version; private final CustomCrops plugin; + private final boolean isSpigot; public VersionHelper(CustomCrops plugin) { this.plugin = plugin; - isVersionNewerThan1_19_R2(); - disableUseLessInfo(); + this.initialize(); + this.disableUseLessInfo(); + this.isSpigot = plugin.getServer().getName().equals("CraftBukkit"); } public boolean isVersionNewerThan1_19_R2() { - if (version == null) { - version = plugin.getServer().getClass().getPackage().getName().split("\\.")[3]; - String[] split = version.split("_"); - int main_ver = Integer.parseInt(split[1]); - if (main_ver >= 20) isNewerThan1_19_R2 = true; - else if (main_ver == 19) isNewerThan1_19_R2 = Integer.parseInt(split[2].substring(1)) >= 2; - else isNewerThan1_19_R2 = false; + if (server_version == null) { + initialize(); } return isNewerThan1_19_R2; } + public boolean isVersionNewerThan1_19_R3() { + if (server_version == null) { + initialize(); + } + return isNewerThan1_19_R3; + } + + private void initialize() { + server_version = plugin.getServer().getClass().getPackage().getName().split("\\.")[3]; + String[] split = server_version.split("_"); + int main_ver = Integer.parseInt(split[1]); + if (main_ver >= 20) isNewerThan1_19_R2 = (isNewerThan1_19_R3 = true); + else if (main_ver == 19) { + isNewerThan1_19_R2 = Integer.parseInt(split[2].substring(1)) >= 2; + isNewerThan1_19_R3 = Integer.parseInt(split[2].substring(1)) >= 3; + } + else isNewerThan1_19_R2 = false; + } + private void disableUseLessInfo() { MinecraftVersion.disableBStats(); MinecraftVersion.disableUpdateCheck(); @@ -39,7 +64,7 @@ public class VersionHelper { field.setAccessible(true); MinecraftVersion minecraftVersion; try { - minecraftVersion = MinecraftVersion.valueOf(version.replace("v", "MC")); + minecraftVersion = MinecraftVersion.valueOf(server_version.replace("v", "MC")); } catch (IllegalArgumentException ex) { minecraftVersion = MinecraftVersion.UNKNOWN; } @@ -62,4 +87,93 @@ public class VersionHelper { throw new RuntimeException(e); } } + + public void checkUpdate() { + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + try { + URL url = new URL("https://api.polymart.org/v1/getResourceInfoSimple/?resource_id=2625&key=version"); + URLConnection conn = url.openConnection(); + conn.setConnectTimeout(10000); + conn.setReadTimeout(60000); + InputStream inputStream = conn.getInputStream(); + String newest = new BufferedReader(new InputStreamReader(inputStream)).readLine(); + String current = plugin.getDescription().getVersion(); + inputStream.close(); + + if (!compareVer(newest, current)) { + AdventureUtils.consoleMessage(ConfigManager.lang.equalsIgnoreCase("chinese") ? "[CustomCrops] 当前已是最新版本" : "[CustomCrops] You are using the latest version."); + return; + } + + if (ConfigManager.lang.equalsIgnoreCase("chinese")) { + AdventureUtils.consoleMessage("[CustomCrops] 当前版本: " + current); + AdventureUtils.consoleMessage("[CustomCrops] 最新版本: " + newest); + AdventureUtils.consoleMessage("[CustomCrops] 请到 售后群https://polymart.org/resource/customcrops.2625 获取最新版本."); + } + else { + AdventureUtils.consoleMessage("[CustomCrops] Current version: " + current); + AdventureUtils.consoleMessage("[CustomCrops] Latest version: " + newest); + AdventureUtils.consoleMessage("[CustomCrops] Update is available: https://polymart.org/resource/customcrops.2625"); + } + } catch (Exception exception) { + Log.warn("Error occurred when checking update"); + } + }); + } + + private boolean compareVer(String newV, String currentV) { + if (newV == null || currentV == null || newV.isEmpty() || currentV.isEmpty()) { + return false; + } + String[] newVS = newV.split("\\."); + String[] currentVS = currentV.split("\\."); + int maxL = Math.min(newVS.length, currentVS.length); + for (int i = 0; i < maxL; i++) { + try { + String[] newPart = newVS[i].split("-"); + String[] currentPart = currentVS[i].split("-"); + int newNum = Integer.parseInt(newPart[0]); + int currentNum = Integer.parseInt(currentPart[0]); + if (newNum > currentNum) { + return true; + } else if (newNum < currentNum) { + return false; + } else if (newPart.length > 1 && currentPart.length > 1) { + String[] newHotfix = newPart[1].split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); + String[] currentHotfix = currentPart[1].split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); + // hotfix2 & hotfix + if (newHotfix.length == 2 && currentHotfix.length == 1) return true; + // hotfix3 & hotfix2 + else if (newHotfix.length > 1 && currentHotfix.length > 1) { + int newHotfixNum = Integer.parseInt(newHotfix[1]); + int currentHotfixNum = Integer.parseInt(currentHotfix[1]); + if (newHotfixNum > currentHotfixNum) { + return true; + } else if (newHotfixNum < currentHotfixNum) { + return false; + } else { + return newHotfix[0].compareTo(currentHotfix[0]) > 0; + } + } + } else if (newPart.length > 1) { + return true; + } else if (currentPart.length > 1) { + return false; + } + } + catch (NumberFormatException ignored) { + return false; + } + } + // if common parts are the same, the longer is newer + return newVS.length > currentVS.length; + } + + public boolean isSpigot() { + return isSpigot; + } + + public String getPluginVersion() { + return plugin.getDescription().getVersion(); + } } diff --git a/src/main/java/net/momirealms/customcrops/integration/IntegrationManager.java b/src/main/java/net/momirealms/customcrops/integration/IntegrationManager.java new file mode 100644 index 0000000..6c430c7 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/integration/IntegrationManager.java @@ -0,0 +1,145 @@ +package net.momirealms.customcrops.integration; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import net.momirealms.customcrops.api.object.basic.ConfigManager; +import net.momirealms.customcrops.api.util.AdventureUtils; +import net.momirealms.customcrops.api.util.ConfigUtils; +import net.momirealms.customcrops.integration.item.DefaultImpl; +import net.momirealms.customcrops.integration.item.MMOItemsItemImpl; +import net.momirealms.customcrops.integration.job.EcoJobsImpl; +import net.momirealms.customcrops.integration.job.JobsRebornImpl; +import net.momirealms.customcrops.integration.papi.PlaceholderManager; +import net.momirealms.customcrops.integration.season.CustomCropsSeasonImpl; +import net.momirealms.customcrops.integration.season.RealisticSeasonsImpl; +import net.momirealms.customcrops.integration.skill.AureliumsImpl; +import net.momirealms.customcrops.integration.skill.EcoSkillsImpl; +import net.momirealms.customcrops.integration.skill.MMOCoreImpl; +import net.momirealms.customcrops.integration.skill.mcMMOImpl; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.PluginManager; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; + +public class IntegrationManager extends Function { + + private final CustomCrops plugin; + private SkillInterface skillInterface; + private JobInterface jobInterface; + private ItemInterface[] itemInterfaces; + private SeasonInterface seasonInterface; + private final PluginManager pluginManager; + private final PlaceholderManager placeholderManager; + + public IntegrationManager(CustomCrops plugin) { + this.plugin = plugin; + this.pluginManager = Bukkit.getPluginManager(); + this.placeholderManager = new PlaceholderManager(plugin); + } + + @Override + public void load() { + this.hookJobs(); + this.hookSkills(); + this.hookSeasons(); + this.hookItems(); + this.placeholderManager.load(); + } + + @Override + public void unload() { + this.seasonInterface = null; + this.skillInterface = null; + this.itemInterfaces = null; + this.jobInterface = null; + this.placeholderManager.unload(); + } + + private void hookItems() { + ArrayList itemInterfaceList = new ArrayList<>(); + if (pluginManager.isPluginEnabled("MythicMobs")) { + itemInterfaceList.add(new MMOItemsItemImpl()); + hookMessage("MythicMobs"); + } + if (pluginManager.isPluginEnabled("MMOItems")) { + itemInterfaceList.add(new MMOItemsItemImpl()); + hookMessage("MMOItems"); + } + itemInterfaceList.add(new DefaultImpl()); + this.itemInterfaces = itemInterfaceList.toArray(new ItemInterface[0]); + } + + private void hookSeasons() { + if (pluginManager.isPluginEnabled("RealisticSeasons")) { + this.seasonInterface = new RealisticSeasonsImpl(); + ConfigManager.rsHook = true; + hookMessage("RealisticSeasons"); + } else { + this.seasonInterface = new CustomCropsSeasonImpl(); + } + } + + private void hookJobs() { + if (pluginManager.isPluginEnabled("Jobs")) { + this.jobInterface = new JobsRebornImpl(); + hookMessage("JobsReborn"); + } else if (pluginManager.isPluginEnabled("EcoJobs")) { + this.jobInterface = new EcoJobsImpl(); + hookMessage("EcoJobs"); + } + } + + private void hookSkills() { + if (pluginManager.isPluginEnabled("mcMMO")) { + this.skillInterface = new mcMMOImpl(); + hookMessage("mcMMO"); + } else if (pluginManager.isPluginEnabled("MMOCore")) { + this.skillInterface = new MMOCoreImpl(ConfigUtils.getConfig("config.yml").getString("other-settings.MMOCore-profession-name", "farmer")); + hookMessage("MMOCore"); + } else if (pluginManager.isPluginEnabled("AureliumSkills")) { + this.skillInterface = new AureliumsImpl(); + hookMessage("AureliumSkills"); + } else if (pluginManager.isPluginEnabled("EcoSkills")) { + this.skillInterface = new EcoSkillsImpl(); + hookMessage("EcoSkills"); + } + } + + private void hookMessage(String plugin){ + AdventureUtils.consoleMessage("[CustomCrops] " + plugin + " hooked!"); + } + + @NotNull + public ItemStack build(String key) { + for (ItemInterface itemInterface : itemInterfaces) { + ItemStack itemStack = itemInterface.build(key); + if (itemStack != null) { + return itemStack; + } + } + return new ItemStack(Material.AIR); + } + + @Nullable + public SkillInterface getSkillInterface() { + return skillInterface; + } + + @NotNull + public SeasonInterface getSeasonInterface() { + return seasonInterface; + } + + @Nullable + public JobInterface getJobInterface() { + return jobInterface; + } + + public PlaceholderManager getPlaceholderManager() { + return placeholderManager; + } +} diff --git a/src/main/java/net/momirealms/customcrops/api/utils/CCSeason.java b/src/main/java/net/momirealms/customcrops/integration/ItemInterface.java similarity index 76% rename from src/main/java/net/momirealms/customcrops/api/utils/CCSeason.java rename to src/main/java/net/momirealms/customcrops/integration/ItemInterface.java index b62d981..2e79206 100644 --- a/src/main/java/net/momirealms/customcrops/api/utils/CCSeason.java +++ b/src/main/java/net/momirealms/customcrops/integration/ItemInterface.java @@ -15,14 +15,13 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.api.utils; +package net.momirealms.customcrops.integration; -public enum CCSeason { +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; - SPRING, - SUMMER, - AUTUMN, - WINTER, - UNKNOWN +public interface ItemInterface { + @Nullable + ItemStack build(String id); } diff --git a/src/main/java/net/momirealms/customcrops/integrations/JobInterface.java b/src/main/java/net/momirealms/customcrops/integration/JobInterface.java similarity index 75% rename from src/main/java/net/momirealms/customcrops/integrations/JobInterface.java rename to src/main/java/net/momirealms/customcrops/integration/JobInterface.java index b1a5347..f47a268 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/JobInterface.java +++ b/src/main/java/net/momirealms/customcrops/integration/JobInterface.java @@ -1,4 +1,4 @@ -package net.momirealms.customcrops.integrations; +package net.momirealms.customcrops.integration; import org.bukkit.entity.Player; diff --git a/src/main/java/net/momirealms/customcrops/integration/ProtectionInterface.java b/src/main/java/net/momirealms/customcrops/integration/ProtectionInterface.java new file mode 100644 index 0000000..b52dd49 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/integration/ProtectionInterface.java @@ -0,0 +1,4 @@ +package net.momirealms.customcrops.integration; + +public interface ProtectionInterface { +} diff --git a/src/main/java/net/momirealms/customcrops/objects/WorldState.java b/src/main/java/net/momirealms/customcrops/integration/SeasonInterface.java similarity index 76% rename from src/main/java/net/momirealms/customcrops/objects/WorldState.java rename to src/main/java/net/momirealms/customcrops/integration/SeasonInterface.java index a27c9b3..d066934 100644 --- a/src/main/java/net/momirealms/customcrops/objects/WorldState.java +++ b/src/main/java/net/momirealms/customcrops/integration/SeasonInterface.java @@ -15,11 +15,13 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects; +package net.momirealms.customcrops.integration; -public enum WorldState { +import net.momirealms.customcrops.api.object.season.CCSeason; - LOAD, - UNLOAD +public interface SeasonInterface { + CCSeason getSeason(String world); + + int getDate(String world); } diff --git a/src/main/java/net/momirealms/customcrops/integration/SkillInterface.java b/src/main/java/net/momirealms/customcrops/integration/SkillInterface.java new file mode 100644 index 0000000..75424ce --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/integration/SkillInterface.java @@ -0,0 +1,10 @@ +package net.momirealms.customcrops.integration; + +import org.bukkit.entity.Player; + +public interface SkillInterface { + + void addXp(Player player, double amount); + + int getLevel(Player player); +} diff --git a/src/main/java/net/momirealms/customcrops/integration/item/DefaultImpl.java b/src/main/java/net/momirealms/customcrops/integration/item/DefaultImpl.java new file mode 100644 index 0000000..148325b --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/integration/item/DefaultImpl.java @@ -0,0 +1,22 @@ +package net.momirealms.customcrops.integration.item; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.util.ConfigUtils; +import net.momirealms.customcrops.integration.ItemInterface; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class DefaultImpl implements ItemInterface { + + @Nullable + @Override + public ItemStack build(String id) { + if (ConfigUtils.isVanillaItem(id)) { + return new ItemStack(Material.valueOf(id)); + } + else { + return CustomCrops.getInstance().getPlatformInterface().getItemStack(id); + } + } +} diff --git a/src/main/java/net/momirealms/customcrops/integration/item/MMOItemsItemImpl.java b/src/main/java/net/momirealms/customcrops/integration/item/MMOItemsItemImpl.java new file mode 100644 index 0000000..a862d6c --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/integration/item/MMOItemsItemImpl.java @@ -0,0 +1,38 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.integration.item; + +import net.Indyuce.mmoitems.MMOItems; +import net.Indyuce.mmoitems.api.Type; +import net.Indyuce.mmoitems.api.item.mmoitem.MMOItem; +import net.momirealms.customcrops.integration.ItemInterface; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class MMOItemsItemImpl implements ItemInterface { + + @Nullable + @Override + public ItemStack build(String material) { + if (!material.startsWith("MMOItems:")) return null; + material = material.substring(9); + String[] split = material.split(":", 2); + MMOItem mmoItem = MMOItems.plugin.getMMOItem(Type.get(split[0]), split[1].toUpperCase()); + return mmoItem == null ? null : mmoItem.newBuilder().build(); + } +} diff --git a/src/main/java/net/momirealms/customcrops/integration/item/MythicMobsItemImpl.java b/src/main/java/net/momirealms/customcrops/integration/item/MythicMobsItemImpl.java new file mode 100644 index 0000000..713ca3e --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/integration/item/MythicMobsItemImpl.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.integration.item; + +import io.lumine.mythic.bukkit.MythicBukkit; +import net.momirealms.customcrops.integration.ItemInterface; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class MythicMobsItemImpl implements ItemInterface { + + private MythicBukkit mythicBukkit; + + public MythicMobsItemImpl() { + this.mythicBukkit = MythicBukkit.inst(); + } + + @Override + @Nullable + public ItemStack build(String material) { + if (!material.startsWith("MythicMobs:")) return null; + material = material.substring(11); + if (mythicBukkit == null || mythicBukkit.isClosed()) { + this.mythicBukkit = MythicBukkit.inst(); + } + return mythicBukkit.getItemManager().getItemStack(material); + } +} diff --git a/src/main/java/net/momirealms/customcrops/integrations/job/EcoJobsHook.java b/src/main/java/net/momirealms/customcrops/integration/job/EcoJobsImpl.java similarity index 62% rename from src/main/java/net/momirealms/customcrops/integrations/job/EcoJobsHook.java rename to src/main/java/net/momirealms/customcrops/integration/job/EcoJobsImpl.java index 20874cb..b4dbac4 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/job/EcoJobsHook.java +++ b/src/main/java/net/momirealms/customcrops/integration/job/EcoJobsImpl.java @@ -15,29 +15,30 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.integrations.job; +package net.momirealms.customcrops.integration.job; import com.willfp.ecojobs.api.EcoJobsAPI; import com.willfp.ecojobs.jobs.Job; -import com.willfp.ecojobs.jobs.Jobs; -import net.momirealms.customcrops.integrations.JobInterface; +import net.momirealms.customcrops.integration.JobInterface; import org.bukkit.entity.Player; -public class EcoJobsHook implements JobInterface { +public class EcoJobsImpl implements JobInterface { @Override public void addXp(Player player, double amount) { - Job job = EcoJobsAPI.getInstance().getActiveJob(player); - if (job == null) return; - if (job.getId().equals("farmer")) { - EcoJobsAPI.getInstance().giveJobExperience(player, job, amount); + for (Job job : EcoJobsAPI.getActiveJobs(player)) { + if (job.getId().equals("farmer")) { + EcoJobsAPI.giveJobExperience(player, job, amount); + break; + } } } @Override public int getLevel(Player player) { - Job job = Jobs.getByID("farmer"); - if (job == null) return 0; - return EcoJobsAPI.getInstance().getJobLevel(player, job); +// Job job = Jobs.getByID("farmer"); +// if (job == null) return 0; +// return EcoJobsAPI.getJobLevel(player, job); + return 0; } } diff --git a/src/main/java/net/momirealms/customcrops/integrations/job/JobsRebornHook.java b/src/main/java/net/momirealms/customcrops/integration/job/JobsRebornImpl.java similarity index 79% rename from src/main/java/net/momirealms/customcrops/integrations/job/JobsRebornHook.java rename to src/main/java/net/momirealms/customcrops/integration/job/JobsRebornImpl.java index b7802ce..eda7088 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/job/JobsRebornHook.java +++ b/src/main/java/net/momirealms/customcrops/integration/job/JobsRebornImpl.java @@ -15,18 +15,18 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.integrations.job; +package net.momirealms.customcrops.integration.job; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobsPlayer; -import net.momirealms.customcrops.integrations.JobInterface; +import net.momirealms.customcrops.integration.JobInterface; import org.bukkit.entity.Player; import java.util.List; -public class JobsRebornHook implements JobInterface { +public class JobsRebornImpl implements JobInterface { @Override public void addXp(Player player, double amount) { @@ -34,10 +34,12 @@ public class JobsRebornHook implements JobInterface { if (jobsPlayer != null) { List jobs = jobsPlayer.getJobProgression(); Job job = Jobs.getJob("Farmer"); - for (JobProgression progression : jobs) - if (progression.getJob().equals(job)){ + for (JobProgression progression : jobs) { + if (progression.getJob().equals(job)) { progression.addExperience(amount); + break; } + } } } @@ -47,10 +49,11 @@ public class JobsRebornHook implements JobInterface { if (jobsPlayer != null) { List jobs = jobsPlayer.getJobProgression(); Job job = Jobs.getJob("Farmer"); - for (JobProgression progression : jobs) - if (progression.getJob().equals(job)){ + for (JobProgression progression : jobs) { + if (progression.getJob().equals(job)) { return progression.getLevel(); } + } } return 0; } diff --git a/src/main/java/net/momirealms/customcrops/objects/actions/ActionInterface.java b/src/main/java/net/momirealms/customcrops/integration/papi/ParseUtil.java similarity index 62% rename from src/main/java/net/momirealms/customcrops/objects/actions/ActionInterface.java rename to src/main/java/net/momirealms/customcrops/integration/papi/ParseUtil.java index 4857171..fca8180 100644 --- a/src/main/java/net/momirealms/customcrops/objects/actions/ActionInterface.java +++ b/src/main/java/net/momirealms/customcrops/integration/papi/ParseUtil.java @@ -15,12 +15,19 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.objects.actions; +package net.momirealms.customcrops.integration.papi; +import me.clip.placeholderapi.PlaceholderAPI; +import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; -public interface ActionInterface { - void performOn(Player player); +public class ParseUtil { - double getChance(); -} \ No newline at end of file + public static String setPlaceholders(Player player, String text) { + return PlaceholderAPI.setPlaceholders(player, text); + } + + public static String setPlaceholders(OfflinePlayer player, String text) { + return PlaceholderAPI.setPlaceholders(player, text); + } +} diff --git a/src/main/java/net/momirealms/customcrops/integration/papi/PlaceholderManager.java b/src/main/java/net/momirealms/customcrops/integration/papi/PlaceholderManager.java new file mode 100644 index 0000000..0abce6c --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/integration/papi/PlaceholderManager.java @@ -0,0 +1,34 @@ +package net.momirealms.customcrops.integration.papi; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.Function; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +public class PlaceholderManager extends Function { + + private SeasonPapi seasonPapi; + private boolean hasPapi; + + public PlaceholderManager(CustomCrops plugin) { + this.hasPapi = false; + if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { + this.seasonPapi = new SeasonPapi(plugin); + this.hasPapi = true; + } + } + + @Override + public void load() { + if (seasonPapi != null) seasonPapi.register(); + } + + @Override + public void unload() { + if (seasonPapi != null) seasonPapi.unregister(); + } + + public String parse(Player player, String text) { + return hasPapi ? ParseUtil.setPlaceholders(player, text) : text; + } +} diff --git a/src/main/java/net/momirealms/customcrops/integration/papi/SeasonPapi.java b/src/main/java/net/momirealms/customcrops/integration/papi/SeasonPapi.java new file mode 100644 index 0000000..7725242 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/integration/papi/SeasonPapi.java @@ -0,0 +1,71 @@ +package net.momirealms.customcrops.integration.papi; + +import com.comphenix.protocol.PacketType; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.customplugin.PlatformManager; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class SeasonPapi extends PlaceholderExpansion { + + private CustomCrops plugin; + + public SeasonPapi(CustomCrops plugin) { + this.plugin = plugin; + } + + @Override + public @NotNull String getIdentifier() { + return "customcrops"; + } + + @Override + public @NotNull String getAuthor() { + return "XiaoMoMi"; + } + + @Override + public @NotNull String getVersion() { + return "3.0"; + } + + @Override + public boolean persist() { + return true; + } + + @Override + public @Nullable String onRequest(OfflinePlayer player, @NotNull String params) { + String[] split = params.split("_"); + switch (split.length) { + case 1 -> { + switch (split[0]) { + case "season" -> { + Player online_player = player.getPlayer(); + if (online_player == null) return null; + return plugin.getIntegrationManager().getSeasonInterface().getSeason(player.getPlayer().getWorld().getName()).toString(); + } + case "date" -> { + Player online_player = player.getPlayer(); + if (online_player == null) return null; + return String.valueOf(plugin.getIntegrationManager().getSeasonInterface().getDate(player.getPlayer().getWorld().getName())); + } + } + } + case 2 -> { + switch (split[0]) { + case "season" -> { + return plugin.getIntegrationManager().getSeasonInterface().getSeason(split[1]).toString(); + } + case "date" -> { + return String.valueOf(plugin.getIntegrationManager().getSeasonInterface().getDate(split[1])); + } + } + } + } + return null; + } +} diff --git a/src/main/java/net/momirealms/customcrops/integration/season/CustomCropsSeasonImpl.java b/src/main/java/net/momirealms/customcrops/integration/season/CustomCropsSeasonImpl.java new file mode 100644 index 0000000..ae87f68 --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/integration/season/CustomCropsSeasonImpl.java @@ -0,0 +1,18 @@ +package net.momirealms.customcrops.integration.season; + +import net.momirealms.customcrops.CustomCrops; +import net.momirealms.customcrops.api.object.season.CCSeason; +import net.momirealms.customcrops.integration.SeasonInterface; + +public class CustomCropsSeasonImpl implements SeasonInterface { + + @Override + public CCSeason getSeason(String world) { + return CustomCrops.getInstance().getSeasonManager().getSeason(world); + } + + @Override + public int getDate(String world) { + return CustomCrops.getInstance().getSeasonManager().getDate(world); + } +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/integration/season/RealisticSeasonsImpl.java b/src/main/java/net/momirealms/customcrops/integration/season/RealisticSeasonsImpl.java new file mode 100644 index 0000000..bbfab2a --- /dev/null +++ b/src/main/java/net/momirealms/customcrops/integration/season/RealisticSeasonsImpl.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customcrops.integration.season; + +import me.casperge.realisticseasons.api.SeasonsAPI; +import net.momirealms.customcrops.api.object.season.CCSeason; +import net.momirealms.customcrops.integration.SeasonInterface; +import org.bukkit.Bukkit; + +public class RealisticSeasonsImpl implements SeasonInterface { + + @Override + public CCSeason getSeason(String world) { + return switch (SeasonsAPI.getInstance().getSeason(Bukkit.getWorld(world))) { + case WINTER -> CCSeason.WINTER; + case SPRING -> CCSeason.SPRING; + case SUMMER -> CCSeason.SUMMER; + case FALL -> CCSeason.AUTUMN; + case DISABLED, RESTORE -> CCSeason.UNKNOWN; + }; + } + + @Override + public int getDate(String world) { + return SeasonsAPI.getInstance().getDate(Bukkit.getWorld(world)).getDay(); + } +} diff --git a/src/main/java/net/momirealms/customcrops/integrations/skill/AureliumsHook.java b/src/main/java/net/momirealms/customcrops/integration/skill/AureliumsImpl.java similarity index 73% rename from src/main/java/net/momirealms/customcrops/integrations/skill/AureliumsHook.java rename to src/main/java/net/momirealms/customcrops/integration/skill/AureliumsImpl.java index dc54d5b..ed17b43 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/skill/AureliumsHook.java +++ b/src/main/java/net/momirealms/customcrops/integration/skill/AureliumsImpl.java @@ -15,18 +15,23 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.integrations.skill; +package net.momirealms.customcrops.integration.skill; import com.archyx.aureliumskills.api.AureliumAPI; import com.archyx.aureliumskills.leveler.Leveler; import com.archyx.aureliumskills.skills.Skill; -import net.momirealms.customcrops.integrations.SkillInterface; +import net.momirealms.customcrops.integration.SkillInterface; import org.bukkit.entity.Player; -public class AureliumsHook implements SkillInterface { +public class AureliumsImpl implements SkillInterface { - private static final Leveler leveler = AureliumAPI.getPlugin().getLeveler(); - private static final Skill skill = AureliumAPI.getPlugin().getSkillRegistry().getSkill("farming"); + private final Leveler leveler; + private final Skill skill; + + public AureliumsImpl() { + leveler = AureliumAPI.getPlugin().getLeveler(); + skill = AureliumAPI.getPlugin().getSkillRegistry().getSkill("farming"); + } @Override public void addXp(Player player, double amount) { diff --git a/src/main/java/net/momirealms/customcrops/integrations/skill/EcoSkillsHook.java b/src/main/java/net/momirealms/customcrops/integration/skill/EcoSkillsImpl.java similarity index 68% rename from src/main/java/net/momirealms/customcrops/integrations/skill/EcoSkillsHook.java rename to src/main/java/net/momirealms/customcrops/integration/skill/EcoSkillsImpl.java index f2532e6..6269262 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/skill/EcoSkillsHook.java +++ b/src/main/java/net/momirealms/customcrops/integration/skill/EcoSkillsImpl.java @@ -15,22 +15,28 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.integrations.skill; +package net.momirealms.customcrops.integration.skill; import com.willfp.ecoskills.api.EcoSkillsAPI; import com.willfp.ecoskills.skills.Skills; -import net.momirealms.customcrops.integrations.SkillInterface; +import net.momirealms.customcrops.integration.SkillInterface; import org.bukkit.entity.Player; -public class EcoSkillsHook implements SkillInterface { +public class EcoSkillsImpl implements SkillInterface { + + public EcoSkillsAPI ecoSkillsAPI; + + public EcoSkillsImpl() { + ecoSkillsAPI = EcoSkillsAPI.getInstance(); + } @Override public void addXp(Player player, double amount) { - EcoSkillsAPI.getInstance().giveSkillExperience(player, Skills.FARMING, amount); + ecoSkillsAPI.giveSkillExperience(player, Skills.FARMING, amount); } @Override public int getLevel(Player player) { - return EcoSkillsAPI.getInstance().getSkillLevel(player, Skills.FARMING); + return ecoSkillsAPI.getSkillLevel(player, Skills.FISHING); } } diff --git a/src/main/java/net/momirealms/customcrops/integrations/skill/MMOCoreHook.java b/src/main/java/net/momirealms/customcrops/integration/skill/MMOCoreImpl.java similarity index 58% rename from src/main/java/net/momirealms/customcrops/integrations/skill/MMOCoreHook.java rename to src/main/java/net/momirealms/customcrops/integration/skill/MMOCoreImpl.java index 4a0a338..a1cc6a7 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/skill/MMOCoreHook.java +++ b/src/main/java/net/momirealms/customcrops/integration/skill/MMOCoreImpl.java @@ -15,23 +15,34 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.integrations.skill; +package net.momirealms.customcrops.integration.skill; import net.Indyuce.mmocore.MMOCore; import net.Indyuce.mmocore.experience.EXPSource; import net.Indyuce.mmocore.experience.Profession; -import net.momirealms.customcrops.integrations.SkillInterface; +import net.Indyuce.mmocore.manager.data.PlayerDataManager; +import net.momirealms.customcrops.integration.SkillInterface; import org.bukkit.entity.Player; -public class MMOCoreHook implements SkillInterface { +public class MMOCoreImpl implements SkillInterface { + + private final Profession profession; + private final PlayerDataManager playerDataManager; + + public MMOCoreImpl(String name) { + profession = MMOCore.plugin.professionManager.get(name); + playerDataManager = MMOCore.plugin.dataProvider.getDataManager(); + } + @Override public void addXp(Player player, double amount) { - Profession profession = MMOCore.plugin.professionManager.get("farming"); - profession.giveExperience(MMOCore.plugin.dataProvider.getDataManager().get(player), amount, null ,EXPSource.OTHER); + if (profession != null) { + profession.giveExperience(playerDataManager.get(player), amount, null ,EXPSource.OTHER); + } } @Override public int getLevel(Player player) { - return 0; + return playerDataManager.get(player).getLevel(); } -} +} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/integrations/skill/mcMMOHook.java b/src/main/java/net/momirealms/customcrops/integration/skill/mcMMOImpl.java similarity index 86% rename from src/main/java/net/momirealms/customcrops/integrations/skill/mcMMOHook.java rename to src/main/java/net/momirealms/customcrops/integration/skill/mcMMOImpl.java index 2ae474c..48c2842 100644 --- a/src/main/java/net/momirealms/customcrops/integrations/skill/mcMMOHook.java +++ b/src/main/java/net/momirealms/customcrops/integration/skill/mcMMOImpl.java @@ -15,14 +15,14 @@ * along with this program. If not, see . */ -package net.momirealms.customcrops.integrations.skill; +package net.momirealms.customcrops.integration.skill; import com.gmail.nossr50.api.ExperienceAPI; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; -import net.momirealms.customcrops.integrations.SkillInterface; +import net.momirealms.customcrops.integration.SkillInterface; import org.bukkit.entity.Player; -public class mcMMOHook implements SkillInterface { +public class mcMMOImpl implements SkillInterface { @Override public void addXp(Player player, double amount) { diff --git a/src/main/java/net/momirealms/customcrops/integrations/CCAntiGrief.java b/src/main/java/net/momirealms/customcrops/integrations/CCAntiGrief.java deleted file mode 100644 index 2fe7539..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/CCAntiGrief.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations; - -import net.momirealms.customcrops.config.MainConfig; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public interface CCAntiGrief { - - String getName(); - - boolean canBreak(Location location, Player player); - - boolean canPlace(Location location, Player player); - - static boolean testBreak(Player player, Location location) { - if (player.isOp()) return true; - for (CCAntiGrief CCAntiGrief : MainConfig.internalAntiGriefs) { - if(!CCAntiGrief.canBreak(location, player)) { - return false; - } - } - for (CCAntiGrief CCAntiGrief : MainConfig.externalAntiGriefs) { - if(!CCAntiGrief.canBreak(location, player)) { - return false; - } - } - return true; - } - - static boolean testPlace(Player player, Location location) { - if (player.isOp()) return true; - for (CCAntiGrief CCAntiGrief : MainConfig.internalAntiGriefs) { - if(!CCAntiGrief.canPlace(location, player)) { - return false; - } - } - for (CCAntiGrief CCAntiGrief : MainConfig.externalAntiGriefs) { - if(!CCAntiGrief.canPlace(location, player)) { - return false; - } - } - return true; - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/CustomInterface.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/CustomInterface.java deleted file mode 100644 index 8933c25..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/CustomInterface.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin; - -import net.momirealms.customcrops.api.crop.Crop; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.ItemFrame; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Nullable; - -public interface CustomInterface { - - void removeBlock(Location location); - - void placeWire(Location location, String crop); - - void placeNoteBlock(Location location, String blockID); - - @Nullable - String getBlockID(Location location); - - @Nullable - ItemStack getItemStack(String id); - - @Nullable - String getItemID(ItemStack itemStack); - - @Nullable - ItemFrame placeFurniture(Location location, String id); - - void removeFurniture(Entity entity); - - boolean doesExist(String itemID); - - boolean hasNextStage(String id); - - String getNextStage(String id); - - @Nullable - Crop getCropFromID(String id); - - Location getFrameCropLocation(Location seedLoc); - - void addFrameStage(ItemFrame itemFrame, String stage, boolean rotate); - - void addWireStage(Location seedLoc, String stage); - - @Nullable - String getEntityID(Entity entity); -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/HandlerP.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/HandlerP.java deleted file mode 100644 index 00e460a..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/HandlerP.java +++ /dev/null @@ -1,655 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin; - -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTItem; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.api.event.*; -import net.momirealms.customcrops.api.utils.CCSeason; -import net.momirealms.customcrops.api.utils.SeasonUtils; -import net.momirealms.customcrops.config.*; -import net.momirealms.customcrops.managers.CropManager; -import net.momirealms.customcrops.managers.CustomWorld; -import net.momirealms.customcrops.managers.listener.InteractListener; -import net.momirealms.customcrops.objects.Function; -import net.momirealms.customcrops.objects.Sprinkler; -import net.momirealms.customcrops.objects.WaterCan; -import net.momirealms.customcrops.objects.fertilizer.Fertilizer; -import net.momirealms.customcrops.objects.requirements.PlayerCondition; -import net.momirealms.customcrops.objects.requirements.RequirementInterface; -import net.momirealms.customcrops.utils.AdventureUtil; -import net.momirealms.customcrops.utils.FurnitureUtil; -import net.momirealms.customcrops.utils.HologramUtil; -import net.momirealms.customcrops.utils.LimitationUtil; -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; -import java.util.List; - -public abstract class HandlerP extends Function { - - protected CropManager cropManager; - protected CustomInterface customInterface; - private final InteractListener interactListener; - protected HashMap coolDown = new HashMap<>(); - - public HandlerP(CropManager cropManager) { - this.cropManager = cropManager; - this.customInterface = cropManager.getCustomInterface(); - this.interactListener = new InteractListener(this); - } - - @Override - public void load() { - super.load(); - Bukkit.getPluginManager().registerEvents(interactListener, CustomCrops.plugin); - } - - @Override - public void unload() { - super.unload(); - HandlerList.unregisterAll(interactListener); - } - - public void onPlayerInteract(PlayerInteractEvent event) { - //null - } - - public void onInteractSprinkler(Location location, Player player, @Nullable ItemStack itemStack, Sprinkler config) { - - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld == null) return; - - Sprinkler sprinkler = customWorld.getSprinklerCache(location); - if (sprinkler == null) { - sprinkler = new Sprinkler(config.getKey(), config.getRange(), 0); - customWorld.addSprinklerCache(location, sprinkler); - } - - if (itemStack != null) { - - if (itemStack.getType() == Material.WATER_BUCKET) { - - WaterBucketFillSprinklerEvent waterBucketFillSprinklerEvent = new WaterBucketFillSprinklerEvent(player, itemStack); - Bukkit.getPluginManager().callEvent(waterBucketFillSprinklerEvent); - if (waterBucketFillSprinklerEvent.isCancelled()) { - return; - } - - itemStack.setType(Material.BUCKET); - int water = sprinkler.getWater() + MainConfig.waterBucketToSprinkler; - if (water > config.getWater()) water = config.getWater(); - sprinkler.setWater(water); - - if (SoundConfig.addWaterToSprinkler.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.addWaterToSprinkler.getSource(), - SoundConfig.addWaterToSprinkler.getKey(), - 1,1 - ); - } - } - else if (itemStack.getType() != Material.AIR) { - - String canID = customInterface.getItemID(itemStack); - WaterCan canConfig = WaterCanConfig.CANS.get(canID); - if (canConfig != null) { - - NBTItem nbtItem = new NBTItem(itemStack); - int canWater = nbtItem.getInteger("WaterAmount"); - if (canWater > 0) { - - WaterCanFillSprinklerEvent waterCanFillSprinklerEvent = new WaterCanFillSprinklerEvent(player, nbtItem); - Bukkit.getPluginManager().callEvent(waterCanFillSprinklerEvent); - if (waterCanFillSprinklerEvent.isCancelled()) { - return; - } - - nbtItem.setInteger("WaterAmount", --canWater); - - int water = sprinkler.getWater() + MainConfig.wateringCanToSprinkler; - if (water > config.getWater()) water = config.getWater(); - sprinkler.setWater(water); - - if (SoundConfig.addWaterToSprinkler.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.addWaterToSprinkler.getSource(), - SoundConfig.addWaterToSprinkler.getKey(), - 1,1 - ); - } - - if (MainConfig.enableActionBar) { - AdventureUtil.playerActionbar( - player, - (MainConfig.actionBarLeft + - MainConfig.actionBarFull.repeat(canWater) + - MainConfig.actionBarEmpty.repeat(canConfig.getMax() - canWater) + - MainConfig.actionBarRight) - .replace("{max_water}", String.valueOf(canConfig.getMax())) - .replace("{water}", String.valueOf(canWater)) - ); - } - - if (MainConfig.enableWaterCanLore && !MainConfig.enablePacketLore) { - addWaterLore(nbtItem, canConfig, canWater); - } - - itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); - - if (MainConfig.enableWaterCanLore && MainConfig.enablePacketLore) { - player.updateInventory(); - } - } - } - } - } - - if (MainConfig.enableSprinklerInfo) - HologramUtil.showHolo( - (MainConfig.sprinklerLeft + - MainConfig.sprinklerFull.repeat(sprinkler.getWater()) + - MainConfig.sprinklerEmpty.repeat(config.getWater() - sprinkler.getWater()) + - MainConfig.sprinklerRight) - .replace("{max_water}", String.valueOf(config.getWater())) - .replace("{water}", String.valueOf(sprinkler.getWater())), - player, - location.add(0, MainConfig.sprinklerInfoY - 1,0), - MainConfig.sprinklerInfoDuration); - } - - public boolean useSurveyor(Location potLoc, String id, Player player) { - - if (!id.equals(BasicItemConfig.soilSurveyor)) return false; - - CustomWorld customWorld = cropManager.getCustomWorld(potLoc.getWorld()); - if (customWorld == null) return false; - Fertilizer fertilizer = customWorld.getFertilizerCache(potLoc); - - SurveyorUseEvent surveyorUseEvent = new SurveyorUseEvent(player, fertilizer, potLoc); - Bukkit.getPluginManager().callEvent(surveyorUseEvent); - if (surveyorUseEvent.isCancelled()) { - return true; - } - - if (fertilizer != null) { - - Fertilizer config = FertilizerConfig.FERTILIZERS.get(fertilizer.getKey()); - if (config == null) return true; - - if (SoundConfig.surveyor.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.surveyor.getSource(), - SoundConfig.surveyor.getKey(), - 0.5f,1 - ); - } - - HologramUtil.showHolo( - MainConfig.fertilizerInfo - .replace("{fertilizer}", fertilizer.getName()) - .replace("{times}", String.valueOf(fertilizer.getTimes())) - .replace("{max_times}", String.valueOf(config.getTimes())), - player, - potLoc.add(0.5, MainConfig.fertilizerInfoY, 0.5), - MainConfig.fertilizerInfoDuration); - } - return true; - } - - public void onBreakUnripeCrop(Location location) { - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld == null) return; - customWorld.removeCropCache(location); - } - - public void onBreakRipeCrop(Location location, Crop crop, Player player, boolean instant) { - if (isInCoolDown(player, 50)) return; - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld != null) { - customWorld.removeCropCache(location); - Fertilizer fertilizer = customWorld.getFertilizerCache(location.clone().subtract(0,1,0)); - if (instant) { - //To prevent some unhooked region plugin duplication - Bukkit.getScheduler().runTaskLater(CustomCrops.plugin, ()-> { - if (location.getBlock().getType() != Material.AIR) return; - cropManager.proceedHarvest(crop, player, location, fertilizer, false); - },1); - } - else { - cropManager.proceedHarvest(crop, player, location, fertilizer, false); - } - } - else if (MainConfig.dropLootsInAllWorlds) { - if (instant) { - Bukkit.getScheduler().runTaskLater(CustomCrops.plugin, ()-> { - if (location.getBlock().getType() != Material.AIR) return; - cropManager.proceedHarvest(crop, player, location, null, false); - },1); - } - else { - cropManager.proceedHarvest(crop, player, location, null, false); - } - } - } - - public void removeScarecrowCache(Location location) { - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld == null) return; - customWorld.removeScarecrowCache(location); - } - - public boolean placeSprinkler(String id, Location location, Player player, ItemStack item) { - - Sprinkler config = SprinklerConfig.SPRINKLERS_2D.get(id); - if (config != null) { - Location sprinklerLoc; - if (MainConfig.OraxenHook) sprinklerLoc = location.clone().add(0.5, 1.03125, 0.5); - else sprinklerLoc = location.clone().add(0.5, 1.5, 0.5); - - if (FurnitureUtil.hasFurniture(sprinklerLoc)) return false; - Sprinkler sprinkler = new Sprinkler(config.getKey(), config.getRange(), 0); - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld == null) return false; - - if (MainConfig.limitation && LimitationUtil.reachFrameLimit(location)) { - AdventureUtil.playerMessage(player, MessageConfig.prefix + MessageConfig.limitFrame.replace("{max}", String.valueOf(MainConfig.frameAmount))); - return true; - } - - SprinklerPlaceEvent sprinklerPlaceEvent = new SprinklerPlaceEvent(player, sprinklerLoc); - Bukkit.getPluginManager().callEvent(sprinklerPlaceEvent); - if (sprinklerPlaceEvent.isCancelled()) { - return true; - } - - if (SoundConfig.placeSprinkler.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.placeSprinkler.getSource(), - SoundConfig.placeSprinkler.getKey(), - 1,1 - ); - } - - if (player.getGameMode() != GameMode.CREATIVE) item.setAmount(item.getAmount() - 1); - customWorld.addSprinklerCache(sprinklerLoc, sprinkler); - customInterface.placeFurniture(sprinklerLoc, config.getThreeD()); - return true; - } - return false; - } - - public boolean fillWaterCan(String id, NBTItem nbtItem, ItemStack itemStack, Player player) { - WaterCan config = WaterCanConfig.CANS.get(id); - if (config != null) { - int water = nbtItem.getInteger("WaterAmount"); - List lineOfSight = player.getLineOfSight(null, 5); - - for (Block block : lineOfSight) { - if (block.getType() == Material.WATER) { - if (config.getMax() > water) { - - water += MainConfig.waterToWaterCan; - if (water > config.getMax()) water = config.getMax(); - - WateringCanFillEvent wateringCanFillEvent = new WateringCanFillEvent(player, nbtItem, water); - Bukkit.getPluginManager().callEvent(wateringCanFillEvent); - if (wateringCanFillEvent.isCancelled()) { - return true; - } - - water = wateringCanFillEvent.getCurrentWater(); - - if (water > config.getMax()) water = config.getMax(); - nbtItem.setInteger("WaterAmount", water); - - if (SoundConfig.addWaterToCan.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.addWaterToCan.getSource(), - SoundConfig.addWaterToCan.getKey(), - 1,1 - ); - } - - if (MainConfig.enableParticles) { - player.getWorld().spawnParticle(Particle.WATER_SPLASH, block.getLocation().add(0.5,1, 0.5),10,0.1,0.1,0.1); - } - - if (MainConfig.enableWaterCanLore && !MainConfig.enablePacketLore) { - addWaterLore(nbtItem, config, water); - } - - itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); - - if (MainConfig.enableWaterCanLore && MainConfig.enablePacketLore) { - player.updateInventory(); - } - } - - break; - } - } - - if (MainConfig.enableActionBar) { - AdventureUtil.playerActionbar( - player, - (MainConfig.actionBarLeft + - MainConfig.actionBarFull.repeat(water) + - MainConfig.actionBarEmpty.repeat(config.getMax() - water) + - MainConfig.actionBarRight) - .replace("{max_water}", String.valueOf(config.getMax())) - .replace("{water}", String.valueOf(water)) - ); - } - return true; - } - return false; - } - - protected void addWaterLore(NBTItem nbtItem, WaterCan config, int water) { - NBTCompound display = nbtItem.getCompound("display"); - List lore = display.getStringList("Lore"); - lore.clear(); - for (String text : MainConfig.waterCanLore) { - lore.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize( - text.replace("{water_bar}", - MainConfig.waterBarLeft + - MainConfig.waterBarFull.repeat(water) + - MainConfig.waterBarEmpty.repeat(config.getMax() - water) + - MainConfig.waterBarRight - ) - .replace("{water}", String.valueOf(water)) - .replace("{max_water}", String.valueOf(config.getMax())) - ))); - } - } - - public boolean useFertilizer(Location potLoc, String id, Player player, ItemStack itemStack) { - Fertilizer fertilizer = FertilizerConfig.FERTILIZERS.get(id); - if (fertilizer == null) return false; - CustomWorld customWorld = cropManager.getCustomWorld(potLoc.getWorld()); - if (customWorld == null) return false; - - if (fertilizer.isBefore()) { - Location above; - if (MainConfig.OraxenHook) above = potLoc.clone().add(0.5,1.03125,0.5); - else above = potLoc.clone().add(0.5,1.5,0.5); - - if (FurnitureUtil.hasFurniture(above)) { - AdventureUtil.playerMessage(player, MessageConfig.prefix + MessageConfig.beforePlant); - return true; - } - if (above.getBlock().getType() == Material.TRIPWIRE) { - AdventureUtil.playerMessage(player, MessageConfig.prefix + MessageConfig.beforePlant); - return true; - } - } - - FertilizerUseEvent fertilizerUseEvent = new FertilizerUseEvent(player, fertilizer, potLoc); - Bukkit.getPluginManager().callEvent(fertilizerUseEvent); - if (fertilizerUseEvent.isCancelled()) { - return true; - } - - if (fertilizer.getParticle() != null) { - potLoc.getWorld().spawnParticle(fertilizer.getParticle(), potLoc.clone().add(0.5,1.1,0.5), 5,0.25,0.1,0.25, 0); - } - - if (SoundConfig.useFertilizer.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.useFertilizer.getSource(), - SoundConfig.useFertilizer.getKey(), - 1, 1 - ); - } - - if (player.getGameMode() != GameMode.CREATIVE) itemStack.setAmount(itemStack.getAmount() - 1); - customWorld.addFertilizerCache(potLoc, fertilizer.getWithTimes(fertilizer.getTimes())); - return true; - } - - public void onBreakSprinkler(Location location) { - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld == null) return; - customWorld.removeSprinklerCache(location); - } - - public void onBreakPot(Location location) { - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld == null) return; - //remove fertilizer - customWorld.removeFertilizerCache(location); - customWorld.removePotFromWatered(location); - } - - public void onQuit(Player player) { - coolDown.remove(player); - } - - public void waterPot(int width, int length, Location location, float yaw){ - - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld == null) return; - - int extend = width / 2; - if (yaw < 45 && yaw > -135) { - if (yaw > -45) { - for (int i = -extend; i <= extend; i++) { - Location tempLoc = location.clone().add(i, 0, -1); - for (int j = 0; j < length; j++){ - tempLoc.add(0,0,1); - customWorld.setPlayerWatered(tempLoc); - waterPot(tempLoc); - } - } - } - else { - for (int i = -extend; i <= extend; i++) { - Location tempLoc = location.clone().add(-1, 0, i); - for (int j = 0; j < length; j++){ - tempLoc.add(1,0,0); - customWorld.setPlayerWatered(tempLoc); - waterPot(tempLoc); - } - } - } - } - else { - if (yaw > 45 && yaw < 135) { - for (int i = -extend; i <= extend; i++) { - Location tempLoc = location.clone().add(1, 0, i); - for (int j = 0; j < length; j++){ - tempLoc.subtract(1,0,0); - customWorld.setPlayerWatered(tempLoc); - waterPot(tempLoc); - } - } - } - else { - for (int i = -extend; i <= extend; i++) { - Location tempLoc = location.clone().add(i, 0, 1); - for (int j = 0; j < length; j++){ - tempLoc.subtract(0,0,1); - customWorld.setPlayerWatered(tempLoc); - waterPot(tempLoc); - } - } - } - } - } - - private void waterPot(Location tempLoc) { - String blockID = customInterface.getBlockID(tempLoc); - if(blockID != null){ - if(blockID.equals(BasicItemConfig.dryPot)){ - customInterface.removeBlock(tempLoc); - customInterface.placeNoteBlock(tempLoc, BasicItemConfig.wetPot); - if (MainConfig.enableParticles) { - tempLoc.getWorld().spawnParticle(Particle.WATER_SPLASH, tempLoc.clone().add(0.5,1, 0.5),3,0.1,0.1,0.1); - } - } - } - } - - protected void onInteractRipeCrop(Location location, Crop crop, Player player) { - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld != null) { - Fertilizer fertilizer = customWorld.getFertilizerCache(location.clone().subtract(0,1,0)); - cropManager.proceedHarvest(crop, player, location, fertilizer, true); - String returnStage = crop.getReturnStage(); - if (returnStage == null) customWorld.removeCropCache(location); - else customWorld.addCropCache(location, crop.getKey(), Integer.parseInt(returnStage.substring(returnStage.indexOf("_stage_") + 7))); - } - else if (MainConfig.dropLootsInAllWorlds) { - cropManager.proceedHarvest(crop, player, location, null, true); - } - } - - public boolean plantSeed(Location seedLoc, String cropName, @Nullable Player player, @Nullable ItemStack itemInHand) { - Crop crop = CropConfig.CROPS.get(cropName); - if (crop == null) return false; - - CustomWorld customWorld = cropManager.getCustomWorld(seedLoc.getWorld()); - if (customWorld == null) return false; - - if (FurnitureUtil.hasFurniture(customInterface.getFrameCropLocation(seedLoc)) || seedLoc.getBlock().getType() != Material.AIR) return false; - - if (player != null) { - PlayerCondition playerCondition = new PlayerCondition(seedLoc, player); - if (crop.getPlantRequirements() != null) { - for (RequirementInterface requirement : crop.getPlantRequirements()) { - if (!requirement.isConditionMet(playerCondition)) { - return false; - } - } - } - } - - CCSeason[] seasons = crop.getSeasons(); - if (SeasonConfig.enable && seasons != null) { - if (cropManager.isWrongSeason(seedLoc, seasons)) { - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < seasons.length; i++) { - if (i < seasons.length - 1) stringBuilder.append(SeasonUtils.getSeasonText(seasons[i])).append(", "); - else stringBuilder.append(SeasonUtils.getSeasonText(seasons[i])); - } - if (MainConfig.notifyInWrongSeason) AdventureUtil.playerMessage(player, MessageConfig.prefix + MessageConfig.wrongSeason.replace("{season}", SeasonUtils.getSeasonText(SeasonUtils.getSeason(seedLoc.getWorld()))) - .replace("{suitable}", stringBuilder.toString())); - if (MainConfig.preventInWrongSeason) return false; - } - } - - if (MainConfig.limitation) { - if (MainConfig.cropMode) { - if (LimitationUtil.reachWireLimit(seedLoc)) { - if (player != null) AdventureUtil.playerMessage(player, MessageConfig.prefix + MessageConfig.limitWire.replace("{max}", String.valueOf(MainConfig.wireAmount))); - return false; - } - } - else { - if (LimitationUtil.reachFrameLimit(seedLoc)) { - if (player != null) AdventureUtil.playerMessage(player, MessageConfig.prefix + MessageConfig.limitFrame.replace("{max}", String.valueOf(MainConfig.frameAmount))); - return false; - } - } - } - - SeedPlantEvent seedPlantEvent = new SeedPlantEvent(player, seedLoc, crop); - Bukkit.getPluginManager().callEvent(seedPlantEvent); - if (seedPlantEvent.isCancelled()) { - return false; - } - - if (SoundConfig.plantSeed.isEnable() && player != null) { - AdventureUtil.playerSound( - player, - SoundConfig.plantSeed.getSource(), - SoundConfig.plantSeed.getKey(), - 1,1 - ); - } - - if (itemInHand != null && player != null && player.getGameMode() != GameMode.CREATIVE) itemInHand.setAmount(itemInHand.getAmount() - 1); - if (MainConfig.cropMode) customInterface.placeWire(seedLoc, CropConfig.namespace + cropName + "_stage_1"); - else { - ItemFrame itemFrame = customInterface.placeFurniture(seedLoc, CropConfig.namespace + cropName + "_stage_1"); - if (itemFrame == null) return false; - if (crop.canRotate()) itemFrame.setRotation(FurnitureUtil.getRandomRotation()); - } - customWorld.addCropCache(seedLoc, cropName, 1); - return true; - } - - protected boolean useBucket(Location potLoc, Player player, ItemStack itemInHand) { - if (itemInHand.getType() == Material.WATER_BUCKET) { - WaterPotEvent waterPotEvent = new WaterPotEvent(player, potLoc, itemInHand, 0); - Bukkit.getPluginManager().callEvent(waterPotEvent); - if (waterPotEvent.isCancelled()) { - return false; - } - itemInHand.setType(Material.BUCKET); - waterPot(1,1, potLoc, 0); - return true; - } - return false; - } - - protected boolean isInCoolDown(Player player, int delay) { - long time = System.currentTimeMillis(); - if (time - (coolDown.getOrDefault(player, time - delay)) < delay) return true; - coolDown.put(player, time); - return false; - } - - public boolean isRipe(String id) { - Crop crop = customInterface.getCropFromID(id); - if (crop == null) return false; - int stage = Integer.parseInt(id.substring(id.indexOf("_stage_") + 7)); - return stage == crop.getMax_stage(); - } - - protected boolean checkHarvestRequirements(Player player, Location location, Crop crop) { - if (player.getGameMode() == GameMode.CREATIVE) return true; - PlayerCondition playerCondition = new PlayerCondition(location, player); - if (crop.getHarvestRequirements() != null) { - for (RequirementInterface requirement : crop.getHarvestRequirements()) { - if (!requirement.isConditionMet(playerCondition)) { - return false; - } - } - } - return true; - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderFrameHandler.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderFrameHandler.java deleted file mode 100644 index d4241d0..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderFrameHandler.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.itemsadder; - -import dev.lone.itemsadder.api.CustomBlock; -import dev.lone.itemsadder.api.CustomFurniture; -import dev.lone.itemsadder.api.CustomStack; -import dev.lone.itemsadder.api.Events.CustomBlockBreakEvent; -import dev.lone.itemsadder.api.Events.FurnitureBreakEvent; -import dev.lone.itemsadder.api.Events.FurnitureInteractEvent; -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.config.BasicItemConfig; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.config.SoundConfig; -import net.momirealms.customcrops.config.SprinklerConfig; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import net.momirealms.customcrops.managers.CropManager; -import net.momirealms.customcrops.objects.Sprinkler; -import net.momirealms.customcrops.utils.AdventureUtil; -import net.momirealms.customcrops.utils.FurnitureUtil; -import net.momirealms.customcrops.utils.MiscUtils; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Entity; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.Player; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; - -public class ItemsAdderFrameHandler extends ItemsAdderHandler { - - public ItemsAdderFrameHandler(CropManager cropManager) { - super(cropManager); - } - - public void onInteractFurniture(FurnitureInteractEvent event) { - if (event.isCancelled()) return; - - final String entityNamespacedID = event.getNamespacedID(); - if (entityNamespacedID == null) return; - - final Player player = event.getPlayer(); - final Entity entity = event.getBukkitEntity(); - final Location entityLocation = entity.getLocation();; - - Sprinkler sprinkler = SprinklerConfig.SPRINKLERS_3D.get(entityNamespacedID); - if (sprinkler != null) { - if (!CCAntiGrief.testPlace(player, entity.getLocation())) return; - super.onInteractSprinkler(entity.getLocation(), player, player.getInventory().getItemInMainHand(), sprinkler); - return; - } - - if (!entityNamespacedID.contains("_stage_")) return; - if (!entityNamespacedID.equals(BasicItemConfig.deadCrop)) { - ItemStack itemInHand = player.getInventory().getItemInMainHand(); - if (isRipe(entityNamespacedID)) { - if (MainConfig.canRightClickHarvest && !(MainConfig.emptyHand && itemInHand.getType() != Material.AIR)) { - if (!CCAntiGrief.testBreak(player, entity.getLocation())) return; - Crop crop = customInterface.getCropFromID(entityNamespacedID); - if (crop == null) return; - if (!checkHarvestRequirements(player, entityLocation, crop)) { - event.setCancelled(true); - return; - } - customInterface.removeFurniture(entity); - if (entity.isValid()) entity.remove(); - super.onInteractRipeCrop(entityLocation, crop, player); - if (crop.getReturnStage() != null) { - CustomFurniture customFurniture = CustomFurniture.spawn(crop.getReturnStage(), entityLocation.getBlock()); - if (crop.canRotate() && customFurniture instanceof ItemFrame itemFrame) itemFrame.setRotation(FurnitureUtil.getRandomRotation()); - } - return; - } - } - else if (MainConfig.enableBoneMeal && itemInHand.getType() == Material.BONE_MEAL) { - if (!CCAntiGrief.testPlace(player, entityLocation)) return; - if (player.getGameMode() != GameMode.CREATIVE) itemInHand.setAmount(itemInHand.getAmount() - 1); - if (Math.random() < MainConfig.boneMealChance) { - entity.getWorld().spawnParticle(MainConfig.boneMealSuccess, entityLocation.clone().add(0,0.5, 0),3,0.2,0.2,0.2); - if (SoundConfig.boneMeal.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.boneMeal.getSource(), - SoundConfig.boneMeal.getKey(), - 1,1 - ); - } - customInterface.removeFurniture(entity); - customInterface.placeFurniture(entityLocation, customInterface.getNextStage(entityNamespacedID)); - } - return; - } - } - super.tryMisc(player, player.getInventory().getItemInMainHand(), MiscUtils.getItemFrameBlockLocation(entityLocation.clone().subtract(0,1,0))); - } - - public void onBreakFurniture(FurnitureBreakEvent event) { - if (event.isCancelled()) return; - - final String entityNamespacedId = event.getNamespacedID(); - if (entityNamespacedId == null) return; - - final Location entityLocation = event.getBukkitEntity().getLocation(); - final Player player = event.getPlayer(); - - Sprinkler sprinkler = SprinklerConfig.SPRINKLERS_3D.get(entityNamespacedId); - if (sprinkler != null) { - super.onBreakSprinkler(entityLocation); - return; - } - - if (MainConfig.enableCrow && entityNamespacedId.equals(BasicItemConfig.scarecrow)) { - super.removeScarecrowCache(event.getBukkitEntity().getLocation()); - return; - } - - if (entityNamespacedId.contains("_stage_") && !entityNamespacedId.equals(BasicItemConfig.deadCrop)) { - if (!isRipe(entityNamespacedId)) { - super.onBreakUnripeCrop(entityLocation); - } else { - Crop crop = customInterface.getCropFromID(entityNamespacedId); - if (crop == null) return; - if (!checkHarvestRequirements(player, entityLocation, crop)) { - event.setCancelled(true); - return; - } - super.onBreakRipeCrop(entityLocation, crop, player, false); - } - } - } - - @Override - public void onPlayerInteract(PlayerInteractEvent event) { - final Player player = event.getPlayer(); - if (event.getHand() != EquipmentSlot.HAND) return; - super.onPlayerInteract(event); - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - Block block = event.getClickedBlock(); - if (block == null) return; - CustomBlock cb = CustomBlock.byAlreadyPlaced(block); - if (cb == null) return; - - final String blockID = cb.getNamespacedID(); - - if (!blockID.equals(BasicItemConfig.wetPot) && !blockID.equals(BasicItemConfig.dryPot)) return; - Location seedLoc = block.getLocation().clone().add(0,1,0); - - ItemStack itemInHand = event.getItem(); - Location potLoc = block.getLocation(); - if (super.tryMisc(player, itemInHand, potLoc)) return; - if (event.getBlockFace() != BlockFace.UP) return; - - CustomStack customStack = CustomStack.byItemStack(itemInHand); - if (customStack != null) { - String id = customStack.getId(); - if (id.endsWith("_seeds")) { - String cropName = customStack.getId().substring(0, customStack.getId().length() - 6); - plantSeed(seedLoc, cropName, player, itemInHand); - } - } - else if (MainConfig.enableConvert) { - String cropName = MainConfig.vanilla2Crops.get(itemInHand.getType()); - if (cropName == null) return; - plantSeed(seedLoc, cropName, player, itemInHand); - } - } - - @Override - public void onBreakBlock(CustomBlockBreakEvent event) { - if (event.isCancelled()) return; - - final String namespacedId = event.getNamespacedID(); - final Player player = event.getPlayer(); - final Location location = event.getBlock().getLocation(); - - if (!CCAntiGrief.testBreak(player, location)) return; - - if (namespacedId.equals(BasicItemConfig.dryPot) || namespacedId.equals(BasicItemConfig.wetPot)) { - label_out: { - Location seedLoc = location.clone().add(0,1,0); - ItemFrame itemFrame = FurnitureUtil.getItemFrame(customInterface.getFrameCropLocation(seedLoc)); - if (itemFrame == null) break label_out; - CustomFurniture customFurniture = CustomFurniture.byAlreadySpawned(itemFrame); - if (customFurniture == null) break label_out; - String seedID = customFurniture.getNamespacedID(); - if (seedID.contains("_stage_")) { - if (seedID.equals(BasicItemConfig.deadCrop)) { - CustomFurniture.remove(itemFrame, false); - if (itemFrame.isValid()) itemFrame.remove(); - break label_out; - } - if (!isRipe(seedID)) { - CustomFurniture.remove(itemFrame, false); - if (itemFrame.isValid()) itemFrame.remove(); - super.onBreakUnripeCrop(location.clone().add(0,1,0)); - } - else { - Crop crop = customInterface.getCropFromID(seedID); - if (crop == null) break label_out; - if (!checkHarvestRequirements(player, seedLoc, crop)) { - event.setCancelled(true); - return; - } - CustomFurniture.remove(itemFrame, false); - if (itemFrame.isValid()) itemFrame.remove(); - super.onBreakRipeCrop(seedLoc, crop, player, true); - } - } - } - super.onBreakPot(location); - } - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderHandler.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderHandler.java deleted file mode 100644 index cfc7c0e..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderHandler.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.itemsadder; - -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTItem; -import dev.lone.itemsadder.api.CustomStack; -import dev.lone.itemsadder.api.Events.CustomBlockBreakEvent; -import dev.lone.itemsadder.api.Events.FurnitureBreakEvent; -import dev.lone.itemsadder.api.Events.FurnitureInteractEvent; -import dev.lone.itemsadder.api.Events.FurniturePlaceSuccessEvent; -import net.kyori.adventure.key.Key; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.event.WaterPotEvent; -import net.momirealms.customcrops.config.BasicItemConfig; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.config.SoundConfig; -import net.momirealms.customcrops.config.WaterCanConfig; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import net.momirealms.customcrops.integrations.customplugin.HandlerP; -import net.momirealms.customcrops.integrations.customplugin.itemsadder.listeners.ItemsAdderBlockListener; -import net.momirealms.customcrops.integrations.customplugin.itemsadder.listeners.ItemsAdderFurnitureListener; -import net.momirealms.customcrops.managers.CropManager; -import net.momirealms.customcrops.managers.CustomWorld; -import net.momirealms.customcrops.objects.WaterCan; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -public abstract class ItemsAdderHandler extends HandlerP { - - private final ItemsAdderBlockListener itemsAdderBlockListener; - private final ItemsAdderFurnitureListener itemsAdderFurnitureListener; - - public ItemsAdderHandler(CropManager cropManager) { - super(cropManager); - this.itemsAdderBlockListener = new ItemsAdderBlockListener(this); - this.itemsAdderFurnitureListener = new ItemsAdderFurnitureListener(this); - } - - @Override - public void load() { - super.load(); - Bukkit.getPluginManager().registerEvents(this.itemsAdderBlockListener, CustomCrops.plugin); - Bukkit.getPluginManager().registerEvents(this.itemsAdderFurnitureListener, CustomCrops.plugin); - } - - @Override - public void unload() { - super.unload(); - HandlerList.unregisterAll(this.itemsAdderBlockListener); - HandlerList.unregisterAll(this.itemsAdderFurnitureListener); - } - - public void placeScarecrow(FurniturePlaceSuccessEvent event) { - if (!MainConfig.enableCrow) return; - String id = event.getNamespacedID(); - if (id == null || !id.equals(BasicItemConfig.scarecrow)) return; - Location location = event.getBukkitEntity().getLocation(); - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld == null) return; - customWorld.addScarecrowCache(location); - } - - @Override - public void onPlayerInteract(PlayerInteractEvent event) { - - final Player player = event.getPlayer(); - final Action action = event.getAction(); - - if (action == Action.RIGHT_CLICK_BLOCK || action == Action.RIGHT_CLICK_AIR) { - - Block block = event.getClickedBlock(); - - if (block != null && ((block.getType().isInteractable() && block.getType() != Material.NOTE_BLOCK) || block.getType() == Material.TRIPWIRE)) return; - - ItemStack item = event.getItem(); - if (item == null || item.getType() == Material.AIR) return; - NBTItem nbtItem = new NBTItem(item); - NBTCompound iaCompound = nbtItem.getCompound("itemsadder"); - if (iaCompound == null) return; - String namespace = iaCompound.getString("namespace"); - String id = iaCompound.getString("id"); - String namespacedID = namespace + ":" + id; - - if (fillWaterCan(namespacedID, nbtItem, item, player)) { - return; - } - - if (block == null) return; - - Location location = block.getLocation(); - if (!CCAntiGrief.testPlace(player, location)) return; - if (event.getBlockFace() == BlockFace.UP) { - placeSprinkler(namespacedID, event.getClickedBlock().getLocation(), player, item); - } - } - } - - public boolean tryMisc(Player player, ItemStack itemInHand, Location potLoc) { - if (!CCAntiGrief.testPlace(player, potLoc)) return true; - if (itemInHand == null || itemInHand.getType() == Material.AIR) return true; - - if (useBucket(potLoc, player, itemInHand)) { - return true; - } - - CustomStack customStack = CustomStack.byItemStack(itemInHand); - if (customStack == null) return false; - String itemID = customStack.getNamespacedID(); - - if (useSurveyor(potLoc, itemID, player)) { - return true; - } - if (useFertilizer(potLoc, itemID, player, itemInHand)){ - return true; - } - if (useWateringCan(potLoc, itemID, player, customStack)) { - return true; - } - - return false; - } - - private boolean useWateringCan(Location potLoc, String namespacedID, Player player, @NotNull CustomStack can) { - - WaterCan canConfig = WaterCanConfig.CANS.get(namespacedID); - if (canConfig == null) return false; - - ItemStack itemStack = can.getItemStack(); - NBTItem nbtItem = new NBTItem(itemStack); - int water = nbtItem.getInteger("WaterAmount"); - if (water > 0) { - - WaterPotEvent waterPotEvent = new WaterPotEvent(player, potLoc, itemStack, --water); - Bukkit.getPluginManager().callEvent(waterPotEvent); - if (waterPotEvent.isCancelled()) { - return true; - } - nbtItem = new NBTItem(waterPotEvent.getItemStack()); - NBTCompound nbtCompound = nbtItem.getCompound("itemsadder"); - if (nbtCompound.hasTag("custom_durability")){ - int dur = nbtCompound.getInteger("custom_durability"); - int max_dur = nbtCompound.getInteger("max_custom_durability"); - if (dur > 0) { - nbtCompound.setInteger("custom_durability", dur - 1); - nbtCompound.setDouble("fake_durability", (int) itemStack.getType().getMaxDurability() * (double) (dur/max_dur)); - nbtItem.setInteger("Damage", (int) (itemStack.getType().getMaxDurability() * (1 - (double) dur/max_dur))); - } - else { - AdventureUtil.playerSound(player, net.kyori.adventure.sound.Sound.Source.PLAYER, Key.key("minecraft:item.shield.break"), 1, 1); - itemStack.setAmount(itemStack.getAmount() - 1); - } - } - - nbtItem.setInteger("WaterAmount", waterPotEvent.getCurrentWater()); - - if (SoundConfig.waterPot.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.waterPot.getSource(), - SoundConfig.waterPot.getKey(), - 1,1 - ); - } - - if (MainConfig.enableActionBar) { - AdventureUtil.playerActionbar( - player, - (MainConfig.actionBarLeft + - MainConfig.actionBarFull.repeat(water) + - MainConfig.actionBarEmpty.repeat(canConfig.getMax() - water) + - MainConfig.actionBarRight) - .replace("{max_water}", String.valueOf(canConfig.getMax())) - .replace("{water}", String.valueOf(water)) - ); - } - - if (MainConfig.enableWaterCanLore && !MainConfig.enablePacketLore) { - addWaterLore(nbtItem, canConfig, water); - } - - itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); - - if (MainConfig.enableWaterCanLore && MainConfig.enablePacketLore) { - player.updateInventory(); - } - - super.waterPot(canConfig.getWidth(), canConfig.getLength(), potLoc, player.getLocation().getYaw()); - } - - return true; - } - - public void onBreakBlock(CustomBlockBreakEvent event) { - //null - } - - public void onInteractFurniture(FurnitureInteractEvent event) { - //null - } - - public void onBreakFurniture(FurnitureBreakEvent event) { - //null - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderHook.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderHook.java deleted file mode 100644 index 926a5e9..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderHook.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.itemsadder; - -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTItem; -import dev.lone.itemsadder.api.CustomBlock; -import dev.lone.itemsadder.api.CustomFurniture; -import dev.lone.itemsadder.api.CustomStack; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.config.CropConfig; -import net.momirealms.customcrops.integrations.customplugin.CustomInterface; -import net.momirealms.customcrops.utils.FurnitureUtil; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Entity; -import org.bukkit.entity.ItemFrame; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Nullable; - -public class ItemsAdderHook implements CustomInterface { - - @Override - public void removeBlock(Location location) { - CustomBlock.remove(location); - } - - @Override - public void placeWire(Location location, String crop) { - CustomBlock.place(crop, location); - } - - @Override - public void placeNoteBlock(Location location, String blockID) { - CustomBlock.place(blockID, location); - } - - @Override - @Nullable - public String getBlockID(Location location) { - CustomBlock cb = CustomBlock.byAlreadyPlaced(location.getBlock()); - if (cb == null) return null; - return cb.getNamespacedID(); - } - - @Override - @Nullable - public ItemStack getItemStack(String id) { - if (id == null) return null; - CustomStack cs = CustomStack.getInstance(id); - if (cs == null) return null; - return cs.getItemStack(); - } - - @Override - @Nullable - public String getItemID(ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) return null; - NBTItem nbtItem = new NBTItem(itemStack); - NBTCompound nbtCompound = nbtItem.getCompound("itemsadder"); - if (nbtCompound == null) return null; - return nbtCompound.getString("namespace") + ":" + nbtCompound.getString("id"); - } - - @Override - @Nullable - public ItemFrame placeFurniture(Location location, String id) { - CustomFurniture customFurniture = CustomFurniture.spawn(id, location.getBlock()); - Entity entity = customFurniture.getArmorstand(); - if (entity instanceof ItemFrame itemFrame) { - return itemFrame; - } - else { - customFurniture.remove(false); - return null; - } - } - - @Override - public void removeFurniture(Entity entity) { - CustomFurniture.remove(entity,false); - } - - @Override - public boolean doesExist(String itemID) { - return CustomStack.getInstance(itemID) != null; - } - - @Override - public boolean hasNextStage(String id) { - return doesExist(getNextStage(id)); - } - - @Override - public String getNextStage(String id) { - String stageStr = id.substring(id.indexOf("_stage_") + 7); - int nextStage = Integer.parseInt(stageStr) + 1; - return id.substring(0, id.length() - stageStr.length()) + nextStage; - } - - @Override - public @Nullable Crop getCropFromID(String id) { - String cropNameWithoutNS = StringUtils.split(id, ":")[1]; - return CropConfig.CROPS.get(cropNameWithoutNS.substring(0, cropNameWithoutNS.indexOf("_stage_"))); - } - - @Override - public Location getFrameCropLocation(Location seedLoc) { - return seedLoc.clone().add(0.5,0.5,0.5); - } - - @Override - public void addFrameStage(ItemFrame itemFrame, String stage, boolean rotate) { - CustomFurniture.remove(itemFrame, false); - CustomFurniture customFurniture = CustomFurniture.spawn(stage, itemFrame.getLocation().getBlock()); - if (rotate && customFurniture.getArmorstand() instanceof ItemFrame frame) { - frame.setRotation(FurnitureUtil.getRandomRotation()); - } - } - - @Override - public void addWireStage(Location seedLoc, String stage) { - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - removeBlock(seedLoc); - placeWire(seedLoc, stage); - }); - } - - @Override - @Nullable - public String getEntityID(Entity entity) { - CustomFurniture customFurniture = CustomFurniture.byAlreadySpawned(entity); - if (customFurniture == null) return null; - return customFurniture.getNamespacedID(); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderWireHandler.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderWireHandler.java deleted file mode 100644 index e5b12f0..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/ItemsAdderWireHandler.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.itemsadder; - -import dev.lone.itemsadder.api.CustomBlock; -import dev.lone.itemsadder.api.CustomStack; -import dev.lone.itemsadder.api.Events.CustomBlockBreakEvent; -import dev.lone.itemsadder.api.Events.FurnitureBreakEvent; -import dev.lone.itemsadder.api.Events.FurnitureInteractEvent; -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.config.BasicItemConfig; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.config.SoundConfig; -import net.momirealms.customcrops.config.SprinklerConfig; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import net.momirealms.customcrops.managers.CropManager; -import net.momirealms.customcrops.objects.Sprinkler; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; - -public class ItemsAdderWireHandler extends ItemsAdderHandler { - - public ItemsAdderWireHandler(CropManager cropManager) { - super(cropManager); - } - - //interact sprinkler - public void onInteractFurniture(FurnitureInteractEvent event) { - if (event.isCancelled()) return; - final Player player = event.getPlayer(); - Entity entity = event.getBukkitEntity(); - if (!CCAntiGrief.testPlace(player, entity.getLocation())) return; - String namespacedID = event.getNamespacedID(); - if (namespacedID == null) return; - Sprinkler sprinkler = SprinklerConfig.SPRINKLERS_3D.get(namespacedID); - if (sprinkler != null) { - super.onInteractSprinkler(entity.getLocation(), event.getPlayer(), player.getInventory().getItemInMainHand(), sprinkler); - } - } - - //break sprinkler - public void onBreakFurniture(FurnitureBreakEvent event) { - if (event.isCancelled()) return; - String namespacedID = event.getNamespacedID(); - if (namespacedID == null) return; - Sprinkler sprinkler = SprinklerConfig.SPRINKLERS_3D.get(namespacedID); - if (sprinkler != null) { - super.onBreakSprinkler(event.getBukkitEntity().getLocation()); - return; - } - if (MainConfig.enableCrow && namespacedID.equals(BasicItemConfig.scarecrow)) { - super.removeScarecrowCache(event.getBukkitEntity().getLocation()); - } - } - - @Override - public void onPlayerInteract(PlayerInteractEvent event) { - final Player player = event.getPlayer(); - if (event.getHand() != EquipmentSlot.HAND) return; - super.onPlayerInteract(event); - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - Block block = event.getClickedBlock(); - if (block == null) return; - CustomBlock cb = CustomBlock.byAlreadyPlaced(block); - if (cb == null) return; - Location location = block.getLocation(); - final String blockID = cb.getNamespacedID(); - if (blockID.contains("_stage_")) { - ItemStack itemInHand = event.getItem(); - if (!blockID.equals(BasicItemConfig.deadCrop)) { - if (isRipe(blockID)) { - ItemStack mainHand = player.getInventory().getItemInMainHand(); - ItemStack offHand = player.getInventory().getItemInOffHand(); - if (MainConfig.canRightClickHarvest && !(MainConfig.emptyHand && (mainHand.getType() != Material.AIR || offHand.getType() != Material.AIR))) { - if (!CCAntiGrief.testBreak(player, location)) return; - Crop crop = customInterface.getCropFromID(blockID); - if (crop == null) return; - if (!checkHarvestRequirements(player, location, crop)) { - event.setCancelled(true); - return; - } - CustomBlock.remove(location); - super.onInteractRipeCrop(location, crop, player); - if (crop.getReturnStage() != null) CustomBlock.place(crop.getReturnStage(), location); - return; - } - } - //has next stage - else if (MainConfig.enableBoneMeal && itemInHand != null && itemInHand.getType() == Material.BONE_MEAL) { - if (!CCAntiGrief.testPlace(player, location)) return; - if (player.getGameMode() != GameMode.CREATIVE) itemInHand.setAmount(itemInHand.getAmount() - 1); - if (Math.random() < MainConfig.boneMealChance) { - location.getWorld().spawnParticle(MainConfig.boneMealSuccess, location.clone().add(0.5,0.5, 0.5),3,0.2,0.2,0.2); - if (SoundConfig.boneMeal.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.boneMeal.getSource(), - SoundConfig.boneMeal.getKey(), - 1,1 - ); - } - CustomBlock.remove(location); - CustomBlock.place(customInterface.getNextStage(blockID), location); - } - return; - } - } - super.tryMisc(player, itemInHand, location.clone().subtract(0,1,0)); - } - - //interact pot (must have an item) - else if (blockID.equals(BasicItemConfig.wetPot) || blockID.equals(BasicItemConfig.dryPot)) { - ItemStack itemInHand = event.getItem(); - if (super.tryMisc(player, itemInHand, location)) return; - if (event.getBlockFace() != BlockFace.UP) return; - - Location seedLoc = location.clone().add(0,1,0); - CustomStack customStack = CustomStack.byItemStack(itemInHand); - if (customStack != null) { - String id = customStack.getId(); - if (id.endsWith("_seeds")) { - String cropName = customStack.getId().substring(0, id.length() - 6); - plantSeed(seedLoc, cropName, player, itemInHand); - } - } - else if (MainConfig.enableConvert) { - String cropName = MainConfig.vanilla2Crops.get(itemInHand.getType()); - if (cropName == null) return; - plantSeed(seedLoc, cropName, player, itemInHand); - } - } - } - - @Override - public void onBreakBlock(CustomBlockBreakEvent event) { - if (event.isCancelled()) return; - final Player player = event.getPlayer(); - final String namespacedId = event.getNamespacedID(); - final Location location = event.getBlock().getLocation(); - - if (!CCAntiGrief.testBreak(player, location)) return; - - if (namespacedId.contains("_stage_")) { - if (player.getInventory().getItemInMainHand().containsEnchantment(Enchantment.SILK_TOUCH) || player.getInventory().getItemInMainHand().getType() == Material.SHEARS){ - event.setCancelled(true); - CustomBlock.place(namespacedId, location); - if (player.getGameMode() != GameMode.CREATIVE) CustomBlock.byAlreadyPlaced(location.getBlock()).getLoot().forEach(itemStack -> location.getWorld().dropItemNaturally(location, itemStack)); - CustomBlock.remove(location); - } - if (namespacedId.equals(BasicItemConfig.deadCrop)) return; - if (!isRipe(namespacedId)) super.onBreakUnripeCrop(location); - else { - Crop crop = customInterface.getCropFromID(namespacedId); - if (crop == null) return; - if (!checkHarvestRequirements(player, location, crop)) { - event.setCancelled(true); - return; - } - super.onBreakRipeCrop(location, crop, player, true); - } - } - else if (namespacedId.equals(BasicItemConfig.dryPot) || namespacedId.equals(BasicItemConfig.wetPot)) { - label_out: { - Location seedLocation = location.clone().add(0,1,0); - CustomBlock customBlock = CustomBlock.byAlreadyPlaced(seedLocation.getBlock()); - if (customBlock == null) break label_out; - String seedID = customBlock.getNamespacedID(); - if (seedID.contains("_stage_")) { - if (seedID.equals(BasicItemConfig.deadCrop)) { - CustomBlock.remove(seedLocation); - break label_out; - } - if (!isRipe(seedID)) { - CustomBlock.remove(seedLocation); - customBlock.getLoot().forEach(loot -> location.getWorld().dropItemNaturally(seedLocation.getBlock().getLocation(), loot)); - } - else { - Crop crop = customInterface.getCropFromID(seedID); - if (crop == null) break label_out; - if (!checkHarvestRequirements(player, seedLocation, crop)) { - event.setCancelled(true); - return; - } - CustomBlock.remove(seedLocation); - super.onBreakRipeCrop(seedLocation, crop, player, false); - } - } - } - super.onBreakPot(location); - } - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/listeners/ItemsAdderBlockListener.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/listeners/ItemsAdderBlockListener.java deleted file mode 100644 index 0d2ced5..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/listeners/ItemsAdderBlockListener.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.itemsadder.listeners; - -import dev.lone.itemsadder.api.Events.CustomBlockBreakEvent; -import net.momirealms.customcrops.integrations.customplugin.itemsadder.ItemsAdderHandler; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -public class ItemsAdderBlockListener implements Listener { - - private final ItemsAdderHandler handler; - - public ItemsAdderBlockListener(ItemsAdderHandler handler) { - this.handler = handler; - } - - @EventHandler - public void onBreakBlock(CustomBlockBreakEvent event) { - handler.onBreakBlock(event); - } - -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/listeners/ItemsAdderFurnitureListener.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/listeners/ItemsAdderFurnitureListener.java deleted file mode 100644 index dbfdc13..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/itemsadder/listeners/ItemsAdderFurnitureListener.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.itemsadder.listeners; - -import dev.lone.itemsadder.api.Events.FurnitureBreakEvent; -import dev.lone.itemsadder.api.Events.FurnitureInteractEvent; -import dev.lone.itemsadder.api.Events.FurniturePlaceSuccessEvent; -import net.momirealms.customcrops.integrations.customplugin.itemsadder.ItemsAdderHandler; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -public class ItemsAdderFurnitureListener implements Listener { - - private final ItemsAdderHandler handler; - - public ItemsAdderFurnitureListener(ItemsAdderHandler handler) { - this.handler = handler; - } - - @EventHandler - public void onInteractFurniture(FurnitureInteractEvent event) { - handler.onInteractFurniture(event); - } - - @EventHandler - public void onBreakFurniture(FurnitureBreakEvent event) { - handler.onBreakFurniture(event); - } - - @EventHandler - public void onPlaceFurniture(FurniturePlaceSuccessEvent event) { - handler.placeScarecrow(event); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenFrameHandler.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenFrameHandler.java deleted file mode 100644 index 68b9ec1..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenFrameHandler.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.oraxen; - -import io.th0rgal.oraxen.api.OraxenBlocks; -import io.th0rgal.oraxen.api.OraxenItems; -import io.th0rgal.oraxen.api.events.OraxenFurnitureBreakEvent; -import io.th0rgal.oraxen.api.events.OraxenFurnitureInteractEvent; -import io.th0rgal.oraxen.api.events.OraxenNoteBlockBreakEvent; -import io.th0rgal.oraxen.mechanics.provided.gameplay.furniture.FurnitureFactory; -import io.th0rgal.oraxen.mechanics.provided.gameplay.furniture.FurnitureMechanic; -import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanic; -import io.th0rgal.oraxen.utils.drops.Drop; -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.config.BasicItemConfig; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.config.SoundConfig; -import net.momirealms.customcrops.config.SprinklerConfig; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import net.momirealms.customcrops.managers.CropManager; -import net.momirealms.customcrops.objects.Sprinkler; -import net.momirealms.customcrops.utils.AdventureUtil; -import net.momirealms.customcrops.utils.FurnitureUtil; -import net.momirealms.customcrops.utils.MiscUtils; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Entity; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.Player; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.bukkit.persistence.PersistentDataType; - -public class OraxenFrameHandler extends OraxenHandler { - - public OraxenFrameHandler(CropManager cropManager) { - super(cropManager); - } - - @Override - public void onBreakNoteBlock(OraxenNoteBlockBreakEvent event) { - if (event.isCancelled()) return; - - final String id = event.getMechanic().getItemID(); - final Player player = event.getPlayer(); - final Location location = event.getBlock().getLocation(); - - if (!id.equals(BasicItemConfig.dryPot) && !id.equals(BasicItemConfig.wetPot)) return; - if (!CCAntiGrief.testBreak(player, location)) { - event.setCancelled(true); - return; - } - - label_out: { - Location seedLocation = location.clone().add(0,1,0); - ItemFrame itemFrame = FurnitureUtil.getItemFrame(customInterface.getFrameCropLocation(seedLocation)); - if (itemFrame == null) break label_out; - String furnitureID = itemFrame.getPersistentDataContainer().get(OraxenHook.FURNITURE, PersistentDataType.STRING); - if (furnitureID == null) break label_out; - if (furnitureID.contains("_stage_")) { - if (furnitureID.equals(BasicItemConfig.deadCrop)) { - itemFrame.remove(); - break label_out; - } - if (!isRipe(furnitureID)) { - itemFrame.remove(); - FurnitureMechanic mechanic = (FurnitureMechanic) FurnitureFactory.instance.getMechanic(furnitureID); - if (mechanic == null) break label_out; - Drop drop = mechanic.getDrop(); - if (drop != null && player.getGameMode() != GameMode.CREATIVE) { - drop.spawns(seedLocation, new ItemStack(Material.AIR)); - } - super.onBreakUnripeCrop(seedLocation); - } - else { - Crop crop = customInterface.getCropFromID(furnitureID); - if (crop == null) break label_out; - if (!checkHarvestRequirements(player, seedLocation, crop)) { - event.setCancelled(true); - return; - } - itemFrame.remove(); - super.onBreakRipeCrop(seedLocation, crop, player, false); - } - } - } - super.onBreakPot(location); - } - - @Override - public void onBreakFurniture(OraxenFurnitureBreakEvent event) { - if (event.isCancelled()) return; - - String id = event.getMechanic().getItemID(); - if (id == null) return; - - Sprinkler sprinkler = SprinklerConfig.SPRINKLERS_3D.get(id); - if (sprinkler != null) { - super.onBreakSprinkler(event.getBlock().getLocation()); - return; - } - - if (MainConfig.enableCrow && id.equals(BasicItemConfig.scarecrow)) { - super.removeScarecrowCache(event.getBlock().getLocation()); - return; - } - - if (id.contains("_stage_")) { - if (id.equals(BasicItemConfig.deadCrop)) return; - Location seedLoc = event.getBlock().getLocation(); - if (!isRipe(id)) super.onBreakUnripeCrop(seedLoc); - else { - Crop crop = customInterface.getCropFromID(id); - if (crop == null) return; - if (!checkHarvestRequirements(event.getPlayer(), seedLoc, crop)) { - event.setCancelled(true); - return; - } - super.onBreakRipeCrop(seedLoc, crop, event.getPlayer(), false); - } - } - } - -// @Override -// public void onInteractNoteBlock(OraxenNoteBlockInteractEvent event) { -// final Player player = event.getPlayer(); -// final ItemStack itemInHand = event.getItemInHand(); -// final Block block = event.getBlock(); -// -// String blockID = event.getMechanic().getItemID(); -// if (!blockID.equals(BasicItemConfig.dryPot) && !blockID.equals(BasicItemConfig.wetPot)) return; -// -// Location potLoc = block.getLocation(); -// Location seedLoc = potLoc.clone().add(0,1,0); -// -// if (super.tryMisc(player, itemInHand, potLoc)) return; -// if (event.getBlockFace() != BlockFace.UP) return; -// -// String id = OraxenItems.getIdByItem(itemInHand); -// if (id != null) { -// if (id.endsWith("_seeds")) { -// String cropName = id.substring(0, id.length() - 6); -// plantSeed(seedLoc, cropName, player, itemInHand); -// } -// } -// else if (MainConfig.enableConvert) { -// String cropName = MainConfig.vanilla2Crops.get(itemInHand.getType()); -// if (cropName == null) return; -// plantSeed(seedLoc, cropName, player, itemInHand); -// } -// } - - @Override - public void onPlayerInteract(PlayerInteractEvent event) { - final Player player = event.getPlayer(); - if (event.getHand() != EquipmentSlot.HAND) return; - super.onPlayerInteract(event); - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - if (event.getBlockFace() != BlockFace.UP) return; - Block block = event.getClickedBlock(); - if (block == null) return; - NoteBlockMechanic noteBlockMechanic = OraxenBlocks.getNoteBlockMechanic(block); - if (noteBlockMechanic != null) { - final String blockID = noteBlockMechanic.getItemID(); - if (!blockID.equals(BasicItemConfig.wetPot) && !blockID.equals(BasicItemConfig.dryPot)) return; - Location seedLoc = block.getLocation().clone().add(0,1,0); - ItemStack itemInHand = event.getItem(); - Location potLoc = block.getLocation(); - if (super.tryMisc(player, itemInHand, potLoc)) return; - String id = OraxenItems.getIdByItem(itemInHand); - if (id != null) { - if (id.endsWith("_seeds")) { - String cropName = id.substring(0, id.length() - 6); - plantSeed(seedLoc, cropName, player, itemInHand); - } - } - else if (MainConfig.enableConvert) { - String cropName = MainConfig.vanilla2Crops.get(itemInHand.getType()); - if (cropName == null) return; - plantSeed(seedLoc, cropName, player, itemInHand); - } - } - } - - @Override - public void onInteractFurniture(OraxenFurnitureInteractEvent event) { - if (event.isCancelled()) return; - - String id = event.getMechanic().getItemID(); - if (id == null) return; - - final Player player = event.getPlayer(); - final Entity entity = event.getBaseEntity(); - if (!(entity instanceof ItemFrame itemFrame)) return; - final Location location = itemFrame.getLocation(); - - Sprinkler sprinkler = SprinklerConfig.SPRINKLERS_3D.get(id); - if (sprinkler != null) { - if (!CCAntiGrief.testPlace(player, itemFrame.getLocation())) return; - super.onInteractSprinkler(location, player, player.getInventory().getItemInMainHand(), sprinkler); - return; - } - - if (!id.contains("_stage_")) return; - if (!id.equals(BasicItemConfig.deadCrop)) { - ItemStack itemInHand = player.getInventory().getItemInMainHand(); - if (isRipe(id)) { - if (MainConfig.canRightClickHarvest && !(MainConfig.emptyHand && itemInHand.getType() != Material.AIR)) { - if (!CCAntiGrief.testBreak(player, location)) return; - Crop crop = customInterface.getCropFromID(id); - if (crop == null) return; - if (!checkHarvestRequirements(player, location, crop)) { - event.setCancelled(true); - return; - } - itemFrame.remove(); - super.onInteractRipeCrop(location, crop, player); - if (crop.getReturnStage() != null) { - ItemFrame placedFurniture = cropManager.getCustomInterface().placeFurniture(location, crop.getReturnStage()); - if (crop.canRotate() && placedFurniture != null) itemFrame.setRotation(FurnitureUtil.getRandomRotation()); - } - return; - } - } - else if (MainConfig.enableBoneMeal && itemInHand.getType() == Material.BONE_MEAL) { - if (!CCAntiGrief.testPlace(player, location)) return; - if (player.getGameMode() != GameMode.CREATIVE) itemInHand.setAmount(itemInHand.getAmount() - 1); - if (Math.random() < MainConfig.boneMealChance) { - itemFrame.getWorld().spawnParticle(MainConfig.boneMealSuccess, location.clone().add(0,0.5, 0),3,0.2,0.2,0.2); - if (SoundConfig.boneMeal.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.boneMeal.getSource(), - SoundConfig.boneMeal.getKey(), - 1,1 - ); - } - String nextStage = customInterface.getNextStage(id); - itemFrame.setItem(customInterface.getItemStack(nextStage)); - itemFrame.getPersistentDataContainer().set(OraxenHook.FURNITURE, PersistentDataType.STRING, nextStage); - } - return; - } - } - super.tryMisc(player, player.getInventory().getItemInMainHand(), MiscUtils.getItemFrameBlockLocation(location.clone().subtract(0,1,0))); - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenHandler.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenHandler.java deleted file mode 100644 index f5752a3..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenHandler.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.oraxen; - -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTItem; -import io.th0rgal.oraxen.api.OraxenItems; -import io.th0rgal.oraxen.api.events.*; -import io.th0rgal.oraxen.mechanics.provided.gameplay.furniture.FurnitureMechanic; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.event.WaterPotEvent; -import net.momirealms.customcrops.config.BasicItemConfig; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.config.SoundConfig; -import net.momirealms.customcrops.config.WaterCanConfig; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import net.momirealms.customcrops.integrations.customplugin.HandlerP; -import net.momirealms.customcrops.integrations.customplugin.oraxen.listeners.OraxenBlockListener; -import net.momirealms.customcrops.integrations.customplugin.oraxen.listeners.OraxenFurnitureListener; -import net.momirealms.customcrops.managers.CropManager; -import net.momirealms.customcrops.managers.CustomWorld; -import net.momirealms.customcrops.objects.WaterCan; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -public abstract class OraxenHandler extends HandlerP { - - private final OraxenBlockListener oraxenBlockListener; - private final OraxenFurnitureListener oraxenFurnitureListener; - - public OraxenHandler(CropManager cropManager) { - super(cropManager); - this.oraxenBlockListener = new OraxenBlockListener(this); - this.oraxenFurnitureListener = new OraxenFurnitureListener(this); - } - - @Override - public void load() { - super.load(); - Bukkit.getPluginManager().registerEvents(this.oraxenBlockListener, CustomCrops.plugin); - Bukkit.getPluginManager().registerEvents(this.oraxenFurnitureListener, CustomCrops.plugin); - } - - @Override - public void unload() { - super.unload(); - HandlerList.unregisterAll(this.oraxenBlockListener); - HandlerList.unregisterAll(this.oraxenFurnitureListener); - } - - //scarecrow place - public void placeScarecrow(OraxenFurniturePlaceEvent event) { - if (!MainConfig.enableCrow) return; - FurnitureMechanic mechanic = event.getMechanic(); - String id = mechanic.getItemID(); - if (!id.equals(BasicItemConfig.scarecrow)) return; - Location location = event.getBaseEntity().getLocation(); - CustomWorld customWorld = cropManager.getCustomWorld(location.getWorld()); - if (customWorld == null) return; - customWorld.addScarecrowCache(location); - } - - public boolean tryMisc(Player player, ItemStack itemInHand, Location potLoc) { - if (!CCAntiGrief.testPlace(player, potLoc)) return true; - if (itemInHand == null || itemInHand.getType() == Material.AIR) return true; - - if (useBucket(potLoc, player, itemInHand)) { - return true; - } - - String id = OraxenItems.getIdByItem(itemInHand); - if (id == null) return false; - - if (useSurveyor(potLoc, id, player)) { - return true; - } - if (useFertilizer(potLoc, id, player, itemInHand)){ - return true; - } - if (useWateringCan(potLoc, id, player, itemInHand)) { - return true; - } - - return false; - //for future misc - } - - @Override - public void onPlayerInteract(PlayerInteractEvent event) { - final Player player = event.getPlayer(); - final Action action = event.getAction(); - - if (action == Action.RIGHT_CLICK_BLOCK || action == Action.RIGHT_CLICK_AIR) { - - Block block = event.getClickedBlock(); - - if (block != null && ((block.getType().isInteractable() && block.getType() != Material.NOTE_BLOCK) || block.getType() == Material.TRIPWIRE)) return; - - ItemStack item = event.getItem(); - if (item == null || item.getType() == Material.AIR) return; - NBTItem nbtItem = new NBTItem(item); - - NBTCompound bukkitCompound = nbtItem.getCompound("PublicBukkitValues"); - if (bukkitCompound != null) { - String id = bukkitCompound.getString("oraxen:id"); - if (id == null || id.equals("")) return; - - if (fillWaterCan(id, nbtItem, item, player)) { - return; - } - - if (block == null) return; - - if (!CCAntiGrief.testPlace(player, block.getLocation())) return; - - if (event.getBlockFace() == BlockFace.UP && placeSprinkler(id, block.getLocation(), player, item)) { - return; - } - } - } - } - - private boolean useWateringCan(Location potLoc, String id, Player player, @NotNull ItemStack can) { - - WaterCan canConfig = WaterCanConfig.CANS.get(id); - if (canConfig == null) return false; - - NBTItem nbtItem = new NBTItem(can); - int water = nbtItem.getInteger("WaterAmount"); - if (water > 0) { - - WaterPotEvent waterPotEvent = new WaterPotEvent(player, potLoc, can, --water); - Bukkit.getPluginManager().callEvent(waterPotEvent); - if (waterPotEvent.isCancelled()) { - return true; - } - - nbtItem = new NBTItem(waterPotEvent.getItemStack()); - nbtItem.setInteger("WaterAmount", waterPotEvent.getCurrentWater()); - - if (SoundConfig.waterPot.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.waterPot.getSource(), - SoundConfig.waterPot.getKey(), - 1,1 - ); - } - - if (MainConfig.enableActionBar) { - AdventureUtil.playerActionbar( - player, - (MainConfig.actionBarLeft + - MainConfig.actionBarFull.repeat(water) + - MainConfig.actionBarEmpty.repeat(canConfig.getMax() - water) + - MainConfig.actionBarRight) - .replace("{max_water}", String.valueOf(canConfig.getMax())) - .replace("{water}", String.valueOf(water)) - ); - } - - if (MainConfig.enableWaterCanLore && !MainConfig.enablePacketLore) { - addWaterLore(nbtItem, canConfig, water); - } - - if (MainConfig.enableWaterCanLore && MainConfig.enablePacketLore) { - player.updateInventory(); - } - - super.waterPot(canConfig.getWidth(), canConfig.getLength(), potLoc, player.getLocation().getYaw()); - - can.setItemMeta(nbtItem.getItem().getItemMeta()); - } - return true; - } - - public void onBreakNoteBlock(OraxenNoteBlockBreakEvent event) { - } - - public void onBreakStringBlock(OraxenStringBlockBreakEvent event) { - } - - public void onInteractStringBlock(OraxenStringBlockInteractEvent event) { - } - - public void onInteractNoteBlock(OraxenNoteBlockInteractEvent event) { - } - - public void onBreakFurniture(OraxenFurnitureBreakEvent event) { - } - - public void onInteractFurniture(OraxenFurnitureInteractEvent event) { - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenHook.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenHook.java deleted file mode 100644 index eb0734f..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenHook.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.oraxen; - -import io.th0rgal.oraxen.OraxenPlugin; -import io.th0rgal.oraxen.api.OraxenBlocks; -import io.th0rgal.oraxen.api.OraxenItems; -import io.th0rgal.oraxen.items.ItemBuilder; -import io.th0rgal.oraxen.mechanics.provided.gameplay.furniture.FurnitureFactory; -import io.th0rgal.oraxen.mechanics.provided.gameplay.furniture.FurnitureMechanic; -import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanic; -import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanicFactory; -import io.th0rgal.oraxen.mechanics.provided.gameplay.stringblock.StringBlockMechanic; -import io.th0rgal.oraxen.mechanics.provided.gameplay.stringblock.StringBlockMechanicFactory; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.config.CropConfig; -import net.momirealms.customcrops.integrations.customplugin.CustomInterface; -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Entity; -import org.bukkit.entity.ItemFrame; -import org.bukkit.inventory.ItemStack; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataType; -import org.jetbrains.annotations.Nullable; - -public class OraxenHook implements CustomInterface { - - public static NamespacedKey FURNITURE = new NamespacedKey(OraxenPlugin.get(), "furniture"); - - @Override - public void removeBlock(Location location) { - OraxenBlocks.remove(location, null); - } - - @Override - public void placeWire(Location location, String crop) { - StringBlockMechanicFactory.setBlockModel(location.getBlock(), crop); - } - - @Override - public void placeNoteBlock(Location location, String id) { - NoteBlockMechanicFactory.setBlockModel(location.getBlock(), id); - } - - @Override - @Nullable - public String getBlockID(Location location) { - Block block = location.getBlock(); - if (block.getType() == Material.TRIPWIRE) { - StringBlockMechanic mechanic = OraxenBlocks.getStringMechanic(block); - if (mechanic == null) return null; - else return mechanic.getItemID(); - } - else if (block.getType() == Material.NOTE_BLOCK) { - NoteBlockMechanic mechanic = OraxenBlocks.getNoteBlockMechanic(block); - if (mechanic == null) return null; - else return mechanic.getItemID(); - } - return null; - } - - @Override - @Nullable - public ItemStack getItemStack(String id) { - ItemBuilder ib = OraxenItems.getItemById(id); - if (ib == null) return null; - return ib.build(); - } - - @Override - @Nullable - public String getItemID(ItemStack itemStack) { - return OraxenItems.getIdByItem(itemStack); - } - - @Override - @Nullable - public ItemFrame placeFurniture(Location location, String id) { - FurnitureMechanic mechanic = (FurnitureMechanic) FurnitureFactory.getInstance().getMechanic(id); - return (ItemFrame) mechanic.place(location, 0, Rotation.NONE, BlockFace.UP); - } - - @Override - public void removeFurniture(Entity entity) { - entity.remove(); - } - - @Override - public boolean doesExist(String itemID) { - return OraxenItems.getItemById(itemID) != null; - } - - @Override - public boolean hasNextStage(String id) { - return doesExist(getNextStage(id)); - } - - @Override - public String getNextStage(String id) { - String stageStr = id.substring(id.indexOf("_stage_") + 7); - int nextStage = Integer.parseInt(stageStr) + 1; - return id.substring(0, id.length() - stageStr.length()) + nextStage; - } - - @Override - public @Nullable Crop getCropFromID(String id) { - return CropConfig.CROPS.get(id.substring(0, id.indexOf("_stage_"))); - } - - @Override - public Location getFrameCropLocation(Location seedLoc) { - return seedLoc.clone().add(0.5,0.03125,0.5); - } - - @Override - public void addFrameStage(ItemFrame itemFrame, String stage, boolean rotate) { - itemFrame.setItem(getItemStack(stage), false); - itemFrame.getPersistentDataContainer().set(OraxenHook.FURNITURE, PersistentDataType.STRING, stage); - } - - @Override - public void addWireStage(Location seedLoc, String stage) { - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> placeWire(seedLoc, stage)); - } - - @Override - @Nullable - public String getEntityID(Entity entity) { - PersistentDataContainer pdc = entity.getPersistentDataContainer(); - return pdc.get(FURNITURE, PersistentDataType.STRING); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenWireHandler.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenWireHandler.java deleted file mode 100644 index b532b25..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/OraxenWireHandler.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.oraxen; - -import io.th0rgal.oraxen.api.OraxenItems; -import io.th0rgal.oraxen.api.events.OraxenFurnitureBreakEvent; -import io.th0rgal.oraxen.api.events.OraxenFurnitureInteractEvent; -import io.th0rgal.oraxen.api.events.OraxenNoteBlockBreakEvent; -import io.th0rgal.oraxen.api.events.OraxenStringBlockBreakEvent; -import io.th0rgal.oraxen.mechanics.provided.gameplay.furniture.FurnitureFactory; -import io.th0rgal.oraxen.mechanics.provided.gameplay.furniture.FurnitureMechanic; -import io.th0rgal.oraxen.mechanics.provided.gameplay.stringblock.StringBlockMechanic; -import io.th0rgal.oraxen.utils.drops.Drop; -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.config.BasicItemConfig; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.config.SoundConfig; -import net.momirealms.customcrops.config.SprinklerConfig; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import net.momirealms.customcrops.managers.CropManager; -import net.momirealms.customcrops.objects.Sprinkler; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; - -public class OraxenWireHandler extends OraxenHandler{ - - public OraxenWireHandler(CropManager cropManager) { - super(cropManager); - } - - @Override - public void onBreakStringBlock(OraxenStringBlockBreakEvent event) { - if (event.isCancelled()) return; - - StringBlockMechanic mechanic = event.getMechanic(); - String id = mechanic.getItemID(); - - final Player player = event.getPlayer(); - if (!id.contains("_stage_")) return; - - final Block block = event.getBlock(); - Location location = block.getLocation(); - - if (!CCAntiGrief.testBreak(player, location)) { - event.setCancelled(true); - return; - } - - if (player.getInventory().getItemInMainHand().containsEnchantment(Enchantment.SILK_TOUCH) || player.getInventory().getItemInMainHand().getType() == Material.SHEARS){ - event.setCancelled(true); - Drop drop = mechanic.getDrop(); - if (player.getGameMode() != GameMode.CREATIVE && drop != null) - drop.spawns(location, new ItemStack(Material.AIR)); - block.setType(Material.AIR); - } - - if (id.equals(BasicItemConfig.deadCrop)) return; - if (!isRipe(id)) super.onBreakUnripeCrop(location); - else { - Crop crop = customInterface.getCropFromID(id); - if (crop == null) return; - if (!checkHarvestRequirements(player, location, crop)) { - event.setCancelled(true); - return; - } - super.onBreakRipeCrop(location, crop, player, true); - } - } - - @Override - public void onBreakFurniture(OraxenFurnitureBreakEvent event) { - if (event.isCancelled()) return; - - FurnitureMechanic mechanic = event.getMechanic(); - if (mechanic == null) return; - String id = mechanic.getItemID(); - Sprinkler sprinkler = SprinklerConfig.SPRINKLERS_3D.get(id); - if (sprinkler != null) { - super.onBreakSprinkler(event.getBlock().getLocation()); - return; - } - if (MainConfig.enableCrow && id.equals(BasicItemConfig.scarecrow)) { - super.removeScarecrowCache(event.getBlock().getLocation()); - } - } - - @Override - public void onInteractFurniture(OraxenFurnitureInteractEvent event) { - if (event.isCancelled()) return; - - final Player player = event.getPlayer(); - final Location blockLoc = event.getBaseEntity().getLocation(); - - if (!CCAntiGrief.testPlace(player, blockLoc)) return; - - FurnitureMechanic mechanic = event.getMechanic(); - if (mechanic == null) return; - String id = mechanic.getItemID(); - Sprinkler sprinkler = SprinklerConfig.SPRINKLERS_3D.get(id); - if (sprinkler != null) { - super.onInteractSprinkler(blockLoc, player, player.getInventory().getItemInMainHand(), sprinkler); - } - } - -// @Override -// public void onInteractNoteBlock(OraxenNoteBlockInteractEvent event) { -// if (event.isCancelled()) return; -// if (event.getHand() != EquipmentSlot.HAND) return; -// -// final ItemStack itemInHand = event.getItemInHand(); -// final Location potLoc = event.getBlock().getLocation(); -// final Player player = event.getPlayer(); -// -// if (super.tryMisc(event.getPlayer(), itemInHand, potLoc)) return; -// if (event.getBlockFace() != BlockFace.UP) return; -// -// Location seedLoc = potLoc.clone().add(0,1,0); -// -// String id = OraxenItems.getIdByItem(itemInHand); -// if (id != null) { -// if (id.endsWith("_seeds")) { -// String cropName = id.substring(0, id.length() - 6); -// plantSeed(seedLoc, cropName, player, itemInHand); -// } -// } -// else if (MainConfig.enableConvert) { -// String cropName = MainConfig.vanilla2Crops.get(itemInHand.getType()); -// if (cropName == null) return; -// plantSeed(seedLoc, cropName, player, itemInHand); -// } -// } - - @Override - public void onPlayerInteract(PlayerInteractEvent event) { - final Player player = event.getPlayer(); - if (event.getHand() != EquipmentSlot.HAND) return; - super.onPlayerInteract(event); - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - Block block = event.getClickedBlock(); - if (block == null) return; - Location location = block.getLocation(); - final String blockID = customInterface.getBlockID(location); - if (blockID == null) return; - if (blockID.contains("_stage_")) { - ItemStack itemInHand = event.getItem(); - if (!blockID.equals(BasicItemConfig.deadCrop)) { - if (isRipe(blockID)) { - ItemStack mainHand = player.getInventory().getItemInMainHand(); - ItemStack offHand = player.getInventory().getItemInOffHand(); - if (MainConfig.canRightClickHarvest && !(MainConfig.emptyHand && (mainHand.getType() != Material.AIR || offHand.getType() != Material.AIR))) { - if (!CCAntiGrief.testBreak(player, location)) return; - Crop crop = customInterface.getCropFromID(blockID); - if (crop == null) return; - if (!checkHarvestRequirements(player, location, crop)) { - event.setCancelled(true); - return; - } - block.setType(Material.AIR); - super.onInteractRipeCrop(location, crop, player); - if (crop.getReturnStage() != null) customInterface.placeWire(location, crop.getReturnStage()); - return; - } - } - //has next stage - else if (MainConfig.enableBoneMeal && itemInHand != null && itemInHand.getType() == Material.BONE_MEAL) { - if (!CCAntiGrief.testPlace(player, location)) return; - if (player.getGameMode() != GameMode.CREATIVE) itemInHand.setAmount(itemInHand.getAmount() - 1); - if (Math.random() < MainConfig.boneMealChance) { - location.getWorld().spawnParticle(MainConfig.boneMealSuccess, location.clone().add(0.5,0.5, 0.5),3,0.2,0.2,0.2); - if (SoundConfig.boneMeal.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.boneMeal.getSource(), - SoundConfig.boneMeal.getKey(), - 1,1 - ); - } - block.setType(Material.AIR); - customInterface.placeWire(location, customInterface.getNextStage(blockID)); - } - return; - } - } - super.tryMisc(player, itemInHand, location.clone().subtract(0,1,0)); - } - //interact pot (must have an item) - else if (blockID.equals(BasicItemConfig.wetPot) || blockID.equals(BasicItemConfig.dryPot)) { - ItemStack itemInHand = event.getItem(); - if (super.tryMisc(player, itemInHand, location)) return; - if (event.getBlockFace() != BlockFace.UP) return; - Location seedLoc = location.clone().add(0,1,0); - String id = OraxenItems.getIdByItem(itemInHand); - if (id != null) { - if (id.endsWith("_seeds")) { - String cropName = id.substring(0, id.length() - 6); - plantSeed(seedLoc, cropName, player, itemInHand); - } - } - else if (MainConfig.enableConvert) { - String cropName = MainConfig.vanilla2Crops.get(itemInHand.getType()); - if (cropName == null) return; - plantSeed(seedLoc, cropName, player, itemInHand); - } - } - } - -// @Override -// public void onInteractStringBlock(OraxenStringBlockInteractEvent event) { -// if (event.isCancelled()) return; -// if (event.getHand() != EquipmentSlot.HAND) return; -// -// final Player player = event.getPlayer(); -// final Block block = event.getBlock(); -// final String id = event.getMechanic().getItemID(); -// -// if (!id.contains("_stage_")) return; -// -// Location seedLoc = block.getLocation(); -// ItemStack itemInHand = event.getItemInHand(); -// if (!id.equals(BasicItemConfig.deadCrop)) { -// if (isRipe(id)) { -// if (MainConfig.canRightClickHarvest && !(MainConfig.emptyHand && itemInHand != null && itemInHand.getType() != Material.AIR)) { -// if (!CCAntiGrief.testBreak(player, seedLoc)) return; -// Crop crop = customInterface.getCropFromID(id); -// if (crop == null) return; -// if (!checkHarvestRequirements(player, seedLoc, crop)) { -// event.setCancelled(true); -// return; -// } -// block.setType(Material.AIR); -// super.onInteractRipeCrop(seedLoc, crop, player); -// if (crop.getReturnStage() != null) StringBlockMechanicFactory.setBlockModel(seedLoc.getBlock(), crop.getReturnStage()); -// return; -// } -// } -// //has next stage -// else if (MainConfig.enableBoneMeal && itemInHand != null && itemInHand.getType() == Material.BONE_MEAL) { -// if (!CCAntiGrief.testPlace(player, seedLoc)) return; -// if (player.getGameMode() != GameMode.CREATIVE) itemInHand.setAmount(itemInHand.getAmount() - 1); -// if (Math.random() < MainConfig.boneMealChance) { -// seedLoc.getWorld().spawnParticle(MainConfig.boneMealSuccess, seedLoc.clone().add(0.5,0.5, 0.5),3,0.2,0.2,0.2); -// if (SoundConfig.boneMeal.isEnable()) { -// AdventureUtil.playerSound( -// player, -// SoundConfig.boneMeal.getSource(), -// SoundConfig.boneMeal.getKey(), -// 1,1 -// ); -// } -// StringBlockMechanicFactory.setBlockModel(block, customInterface.getNextStage(id)); -// } -// return; -// } -// } -// super.tryMisc(player, event.getItemInHand(), block.getLocation().clone().subtract(0,1,0)); -// } - - @Override - public void onBreakNoteBlock(OraxenNoteBlockBreakEvent event) { - if (event.isCancelled()) return; - - final String id = event.getMechanic().getItemID(); - final Player player = event.getPlayer(); - final Location location = event.getBlock().getLocation(); - - if (!id.equals(BasicItemConfig.dryPot) && !id.equals(BasicItemConfig.wetPot)) return; - if (!CCAntiGrief.testBreak(player, location)) return; - - label_out: { - Location seedLocation = location.clone().add(0,1,0); - String blockID = customInterface.getBlockID(seedLocation); - if (blockID == null) break label_out; - if (blockID.contains("_stage_")) { - if (blockID.equals(BasicItemConfig.deadCrop)) { - customInterface.removeBlock(seedLocation); - break label_out; - } - if (!isRipe(blockID)) { - StringBlockMechanic mechanic = (StringBlockMechanic) FurnitureFactory.instance.getMechanic(blockID); - if (mechanic == null) break label_out; - Drop drop = mechanic.getDrop(); - if (drop != null && player.getGameMode() != GameMode.CREATIVE) { - drop.spawns(seedLocation, new ItemStack(Material.AIR)); - } - customInterface.removeBlock(seedLocation); - super.onBreakUnripeCrop(seedLocation); - } - else { - Crop crop = customInterface.getCropFromID(id); - if (crop == null) break label_out; - if (!checkHarvestRequirements(player, seedLocation, crop)) { - event.setCancelled(true); - return; - } - customInterface.removeBlock(seedLocation); - super.onBreakRipeCrop(seedLocation, crop, player, false); - } - } - } - super.onBreakPot(location); - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/listeners/OraxenBlockListener.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/listeners/OraxenBlockListener.java deleted file mode 100644 index a26139c..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/listeners/OraxenBlockListener.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.oraxen.listeners; - -import io.th0rgal.oraxen.api.events.OraxenNoteBlockBreakEvent; -import io.th0rgal.oraxen.api.events.OraxenNoteBlockInteractEvent; -import io.th0rgal.oraxen.api.events.OraxenStringBlockBreakEvent; -import io.th0rgal.oraxen.api.events.OraxenStringBlockInteractEvent; -import net.momirealms.customcrops.integrations.customplugin.oraxen.OraxenHandler; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -public class OraxenBlockListener implements Listener { - - private final OraxenHandler handler; - - public OraxenBlockListener(OraxenHandler handler) { - this.handler = handler; - } - - @EventHandler - public void onBreakNote(OraxenNoteBlockBreakEvent event) { - handler.onBreakNoteBlock(event); - } - - @EventHandler - public void onInteractNote(OraxenNoteBlockInteractEvent event) { - handler.onInteractNoteBlock(event); - } - - @EventHandler - public void onBreakString(OraxenStringBlockBreakEvent event) { - handler.onBreakStringBlock(event); - } - - @EventHandler - public void onInteractString(OraxenStringBlockInteractEvent event) { - handler.onInteractStringBlock(event); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/listeners/OraxenFurnitureListener.java b/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/listeners/OraxenFurnitureListener.java deleted file mode 100644 index 762372b..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/customplugin/oraxen/listeners/OraxenFurnitureListener.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.customplugin.oraxen.listeners; - -import io.th0rgal.oraxen.api.events.OraxenFurnitureBreakEvent; -import io.th0rgal.oraxen.api.events.OraxenFurnitureInteractEvent; -import io.th0rgal.oraxen.api.events.OraxenFurniturePlaceEvent; -import net.momirealms.customcrops.integrations.customplugin.oraxen.OraxenHandler; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -public class OraxenFurnitureListener implements Listener { - - private final OraxenHandler handler; - - public OraxenFurnitureListener(OraxenHandler handler) { - this.handler = handler; - } - - @EventHandler - public void onInteractFurniture(OraxenFurnitureInteractEvent event) { - handler.onInteractFurniture(event); - } - - @EventHandler - public void onBreakFurniture(OraxenFurnitureBreakEvent event) { - handler.onBreakFurniture(event); - } - - @EventHandler - public void onPlaceFurniture(OraxenFurniturePlaceEvent event) { - handler.placeScarecrow(event); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/item/MMOItemsHook.java b/src/main/java/net/momirealms/customcrops/integrations/item/MMOItemsHook.java deleted file mode 100644 index a26579a..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/item/MMOItemsHook.java +++ /dev/null @@ -1,17 +0,0 @@ -package net.momirealms.customcrops.integrations.item; - -import net.Indyuce.mmoitems.MMOItems; -import net.Indyuce.mmoitems.api.Type; -import net.Indyuce.mmoitems.api.item.mmoitem.MMOItem; -import org.apache.commons.lang.StringUtils; -import org.bukkit.inventory.ItemStack; - -public class MMOItemsHook { - - public static ItemStack get(String id) { - id = id.substring(9); - String[] split = StringUtils.split(id, ":"); - MMOItem mmoItem = MMOItems.plugin.getMMOItem(Type.get(split[0]), split[1]); - return mmoItem == null ? null : mmoItem.newBuilder().build(); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/item/MythicMobsHook.java b/src/main/java/net/momirealms/customcrops/integrations/item/MythicMobsHook.java deleted file mode 100644 index 372d419..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/item/MythicMobsHook.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.momirealms.customcrops.integrations.item; - -import io.lumine.mythic.bukkit.MythicBukkit; -import io.lumine.mythic.core.items.ItemExecutor; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Nullable; - -public class MythicMobsHook { - - private static ItemExecutor itemManager; - - @Nullable - public static ItemStack get(String id) { - id = id.substring(11); - if (itemManager == null) { - itemManager = MythicBukkit.inst().getItemManager(); - } - return itemManager.getItemStack(id); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/papi/PlaceholderManager.java b/src/main/java/net/momirealms/customcrops/integrations/papi/PlaceholderManager.java deleted file mode 100644 index b2bdb15..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/papi/PlaceholderManager.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.papi; - -import me.clip.placeholderapi.PlaceholderAPI; -import net.momirealms.customcrops.config.SeasonConfig; -import net.momirealms.customcrops.objects.Function; -import org.bukkit.entity.Player; - -public class PlaceholderManager extends Function { - - private final SeasonPapi seasonPapi; - - public PlaceholderManager() { - this.seasonPapi = new SeasonPapi(); - load(); - } - - @Override - public void load() { - super.load(); - if (SeasonConfig.enable) { - this.seasonPapi.register(); - } - } - - @Override - public void unload() { - super.unload(); - this.seasonPapi.unregister(); - } - - public String parse(Player player, String text) { - return PlaceholderAPI.setPlaceholders(player, text); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/papi/SeasonPapi.java b/src/main/java/net/momirealms/customcrops/integrations/papi/SeasonPapi.java deleted file mode 100644 index caad426..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/papi/SeasonPapi.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.papi; - -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import net.momirealms.customcrops.api.utils.CCSeason; -import net.momirealms.customcrops.api.utils.SeasonUtils; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.config.MessageConfig; -import net.momirealms.customcrops.config.SeasonConfig; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class SeasonPapi extends PlaceholderExpansion { - - @Override - public @NotNull String getIdentifier() { - return "cseason"; - } - - @Override - public @NotNull String getAuthor() { - return "XiaoMoMi"; - } - - @Override - public @NotNull String getVersion() { - return "1.0"; - } - - @Override - public boolean persist() { - return true; - } - - @Override - public @Nullable String onPlaceholderRequest(Player player, @NotNull String params) { - if (!SeasonConfig.enable) return MessageConfig.seasonDisabled; - switch (params) { - case "current" -> { - if (!MainConfig.getWorldNameList().contains(player.getWorld().getName())) return MessageConfig.noSeason; - return getSeasonText(player.getWorld()); - } - case "days_left" -> { - if (!SeasonConfig.auto) return MessageConfig.autoSeasonDisabled; - if (!MainConfig.getWorldNameList().contains(player.getWorld().getName())) return MessageConfig.noSeason; - return String.valueOf(SeasonConfig.duration - ((int) ((player.getWorld().getFullTime() / 24000L) % (SeasonConfig.duration * 4)) % SeasonConfig.duration)); - } - case "days_gone" -> { - if (!SeasonConfig.auto) return MessageConfig.autoSeasonDisabled; - if (!MainConfig.getWorldNameList().contains(player.getWorld().getName())) return MessageConfig.noSeason; - return String.valueOf((int) ((player.getWorld().getFullTime() / 24000L) % (SeasonConfig.duration * 4)) % SeasonConfig.duration + 1); - } - default -> { - if (params.startsWith("current_")) { - World world = Bukkit.getWorld(params.substring(8)); - if (world == null) return MessageConfig.noSeason; - if (!MainConfig.getWorldNameList().contains(world.getName())) return MessageConfig.noSeason; - return getSeasonText(world); - } - if (params.startsWith("days_left_")) { - if (!SeasonConfig.auto) return MessageConfig.autoSeasonDisabled; - World world = Bukkit.getWorld(params.substring(10)); - if (world == null) return MessageConfig.noSeason; - if (!MainConfig.getWorldNameList().contains(world.getName())) return MessageConfig.noSeason; - return String.valueOf(SeasonConfig.duration - ((int) ((world.getFullTime() / 24000L) % (SeasonConfig.duration * 4)) % SeasonConfig.duration)); - } - if (params.startsWith("days_gone_")) { - if (!SeasonConfig.auto) return MessageConfig.autoSeasonDisabled; - World world = Bukkit.getWorld(params.substring(10)); - if (world == null) return MessageConfig.noSeason; - if (!MainConfig.getWorldNameList().contains(world.getName())) return MessageConfig.noSeason; - return String.valueOf((int) ((world.getFullTime() / 24000L) % (SeasonConfig.duration * 4)) % SeasonConfig.duration + 1); - } - } - } - return "null"; - } - - private String getSeasonText(World world) { - CCSeason season = SeasonUtils.getSeason(world); - return SeasonUtils.getSeasonText(season); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/BentoBoxHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/BentoBoxHook.java deleted file mode 100644 index 5fc842a..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/BentoBoxHook.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import world.bentobox.bentobox.BentoBox; -import world.bentobox.bentobox.api.user.User; -import world.bentobox.bentobox.database.objects.Island; -import world.bentobox.bentobox.lists.Flags; - -import java.util.Optional; - -public class BentoBoxHook implements CCAntiGrief { - - @Override - public String getName() { - return "BentoBox"; - } - - @Override - public boolean canBreak(Location location, Player player) { - User user = User.getInstance(player); - Optional islandOptional = BentoBox.getInstance().getIslands().getIslandAt(location); - return islandOptional.map(island -> island.isAllowed(user, Flags.BREAK_BLOCKS)).orElse(true); - } - - @Override - public boolean canPlace(Location location, Player player) { - User user = User.getInstance(player); - Optional islandOptional = BentoBox.getInstance().getIslands().getIslandAt(location); - return islandOptional.map(island -> island.isAllowed(user, Flags.PLACE_BLOCKS)).orElse(true); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/CrashClaimHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/CrashClaimHook.java deleted file mode 100644 index 5e41144..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/CrashClaimHook.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import net.crashcraft.crashclaim.api.CrashClaimAPI; -import net.crashcraft.crashclaim.permissions.PermissionRoute; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class CrashClaimHook implements CCAntiGrief { - - @Override - public String getName() { - return "CrashClaim"; - } - - @Override - public boolean canBreak(Location location, Player player) { - CrashClaimAPI crashClaimAPI = net.crashcraft.crashclaim.CrashClaim.getPlugin().getApi(); - return crashClaimAPI.getPermissionHelper().hasPermission(player.getUniqueId(), location, PermissionRoute.BUILD); - } - - @Override - public boolean canPlace(Location location, Player player) { - CrashClaimAPI crashClaimAPI = net.crashcraft.crashclaim.CrashClaim.getPlugin().getApi(); - return crashClaimAPI.getPermissionHelper().hasPermission(player.getUniqueId(), location, PermissionRoute.BUILD); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/GriefDefenderHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/GriefDefenderHook.java deleted file mode 100644 index 0886e6f..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/GriefDefenderHook.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class GriefDefenderHook implements CCAntiGrief { - - @Override - public String getName() { - return "GriefDefender"; - } - - @Override - public boolean canBreak(Location location, Player player) { - return com.griefdefender.api.GriefDefender.getCore().getUser(player.getUniqueId()).canBreak(location); - } - - @Override - public boolean canPlace(Location location, Player player) { - return com.griefdefender.api.GriefDefender.getCore().getUser(player.getUniqueId()).canPlace(player.getInventory().getItemInMainHand(), location); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/GriefPreventionHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/GriefPreventionHook.java deleted file mode 100644 index 2977432..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/GriefPreventionHook.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class GriefPreventionHook implements CCAntiGrief { - - @Override - public String getName() { - return "GriefPrevention"; - } - - @Override - public boolean canBreak(Location location, Player player) { - return me.ryanhamshire.GriefPrevention.GriefPrevention.instance.allowBreak(player, location.getBlock(), location) == null; - } - - @Override - public boolean canPlace(Location location, Player player) { - return me.ryanhamshire.GriefPrevention.GriefPrevention.instance.allowBuild(player, location) == null; - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/IridiumSkyblockHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/IridiumSkyblockHook.java deleted file mode 100644 index f69d8b7..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/IridiumSkyblockHook.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import com.iridium.iridiumskyblock.PermissionType; -import com.iridium.iridiumskyblock.api.IridiumSkyblockAPI; -import com.iridium.iridiumskyblock.database.Island; -import com.iridium.iridiumskyblock.database.User; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.util.Optional; - -public class IridiumSkyblockHook implements CCAntiGrief { - - @Override - public String getName() { - return "IridiumSkyblock"; - } - - private final IridiumSkyblockAPI api; - - public IridiumSkyblockHook() { - this.api = IridiumSkyblockAPI.getInstance(); - } - - @Override - public boolean canBreak(Location location, Player player) { - Optional island = api.getIslandViaLocation(location); - User user = api.getUser(player); - return island.map(value -> api.getIslandPermission(value, user, PermissionType.BLOCK_BREAK)).orElse(true); - } - - @Override - public boolean canPlace(Location location, Player player) { - Optional island = api.getIslandViaLocation(location); - User user = api.getUser(player); - return island.map(value -> api.getIslandPermission(value, user, PermissionType.BLOCK_PLACE)).orElse(true); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/KingdomsXHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/KingdomsXHook.java deleted file mode 100644 index 0ad1c27..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/KingdomsXHook.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.kingdoms.constants.group.Kingdom; -import org.kingdoms.constants.land.Land; -import org.kingdoms.constants.player.KingdomPlayer; - -public class KingdomsXHook implements CCAntiGrief { - - @Override - public String getName() { - return "KingdomsX"; - } - - @Override - public boolean canBreak(Location location, Player player) { - return kingdomsCheck(location, player); - } - - @Override - public boolean canPlace(Location location, Player player) { - return kingdomsCheck(location, player); - } - - private boolean kingdomsCheck(Location location, Player player) { - Land land = Land.getLand(location); - if (land == null) return true; - if (land.isClaimed()) { - KingdomPlayer kp = KingdomPlayer.getKingdomPlayer(player); - Kingdom cropKingdom = land.getKingdom(); - if (kp.getKingdom() != null) { - Kingdom kingdom = kp.getKingdom(); - return kingdom != cropKingdom; - } - else return false; - } - else return true; - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/LandsHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/LandsHook.java deleted file mode 100644 index 9a8b48d..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/LandsHook.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import me.angeschossen.lands.api.LandsIntegration; -import me.angeschossen.lands.api.flags.types.RoleFlag; -import me.angeschossen.lands.api.land.LandWorld; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class LandsHook implements CCAntiGrief { - - @Override - public String getName() { - return "Lands"; - } - - private final LandsIntegration api; - - public LandsHook() { - api = LandsIntegration.of(CustomCrops.plugin);; - } - - @Override - public boolean canBreak(Location location, Player player) { - LandWorld world = api.getWorld(location.getWorld()); - if (world != null) { - return world.hasRoleFlag(player.getUniqueId(), location, RoleFlag.of("BLOCK_BREAK")); - } - return true; - } - - @Override - public boolean canPlace(Location location, Player player) { - LandWorld world = api.getWorld(location.getWorld()); - if (world != null) { - return world.hasRoleFlag(player.getUniqueId(), location, RoleFlag.of("BLOCK_PLACE")); - } - return true; - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/PlotSquaredHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/PlotSquaredHook.java deleted file mode 100644 index 398e873..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/PlotSquaredHook.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import com.plotsquared.core.location.Location; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.entity.Player; - -public class PlotSquaredHook implements CCAntiGrief { - - @Override - public String getName() { - return "PlotSquared"; - } - - @Override - public boolean canBreak(org.bukkit.Location location, Player player) { - return isAllowed(location, player); - } - - @Override - public boolean canPlace(org.bukkit.Location location, Player player) { - return isAllowed(location, player); - } - - private boolean isAllowed(org.bukkit.Location location, Player player) { - Location plotLoc = Location.at(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (plotLoc.isPlotRoad()) return false; - if (plotLoc.getPlotArea() != null) return plotLoc.getPlotArea().getPlot(plotLoc).isAdded(player.getUniqueId()); - else return true; - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/ResidenceHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/ResidenceHook.java deleted file mode 100644 index 556665e..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/ResidenceHook.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import com.bekvon.bukkit.residence.containers.Flags; -import com.bekvon.bukkit.residence.protection.ClaimedResidence; -import com.bekvon.bukkit.residence.protection.ResidencePermissions; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class ResidenceHook implements CCAntiGrief { - - @Override - public String getName() { - return "Residence"; - } - - @Override - public boolean canBreak(Location location, Player player) { - ClaimedResidence res = com.bekvon.bukkit.residence.Residence.getInstance().getResidenceManager().getByLoc(location); - if (res != null) { - ResidencePermissions perms = res.getPermissions(); - return perms.playerHas(player, Flags.destroy, true); - } - return true; - } - - @Override - public boolean canPlace(Location location, Player player) { - ClaimedResidence res = com.bekvon.bukkit.residence.Residence.getInstance().getResidenceManager().getByLoc(location); - if (res != null) { - ResidencePermissions perms = res.getPermissions(); - return perms.playerHas(player, Flags.build, true); - } - return true; - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/SuperiorSkyBlockHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/SuperiorSkyBlockHook.java deleted file mode 100644 index b2d4264..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/SuperiorSkyBlockHook.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import com.bgsoftware.superiorskyblock.api.SuperiorSkyblockAPI; -import com.bgsoftware.superiorskyblock.api.island.Island; -import com.bgsoftware.superiorskyblock.api.island.IslandPrivilege; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class SuperiorSkyBlockHook implements CCAntiGrief { - - @Override - public String getName() { - return "SuperiorSkyBlock"; - } - - @Override - public boolean canBreak(Location location, Player player) { - Island island = SuperiorSkyblockAPI.getIslandAt(location); - if (island == null) return true; - return island.hasPermission(SuperiorSkyblockAPI.getPlayer(player), IslandPrivilege.getByName("BREAK")); - } - - @Override - public boolean canPlace(Location location, Player player) { - Island island = SuperiorSkyblockAPI.getIslandAt(location); - if (island == null) return true; - return island.hasPermission(SuperiorSkyblockAPI.getPlayer(player), IslandPrivilege.getByName("BUILD")); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/TownyHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/TownyHook.java deleted file mode 100644 index 22b1845..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/TownyHook.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import com.palmergames.bukkit.towny.object.TownyPermission; -import com.palmergames.bukkit.towny.utils.PlayerCacheUtil; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class TownyHook implements CCAntiGrief { - - @Override - public String getName() { - return "Towny"; - } - - @Override - public boolean canBreak(Location location, Player player) { - return TownyPermission(player, location, TownyPermission.ActionType.DESTROY); - } - - @Override - public boolean canPlace(Location location, Player player) { - return TownyPermission(player, location, TownyPermission.ActionType.BUILD); - } - - private boolean TownyPermission(Player player, Location location, TownyPermission.ActionType actionType){ - return PlayerCacheUtil.getCachePermission(player, location, location.getBlock().getType(), actionType); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/protection/WorldGuardHook.java b/src/main/java/net/momirealms/customcrops/integrations/protection/WorldGuardHook.java deleted file mode 100644 index 35f0f22..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/protection/WorldGuardHook.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.protection; - -import com.sk89q.worldedit.bukkit.BukkitAdapter; -import com.sk89q.worldguard.LocalPlayer; -import com.sk89q.worldguard.WorldGuard; -import com.sk89q.worldguard.bukkit.WorldGuardPlugin; -import com.sk89q.worldguard.internal.platform.WorldGuardPlatform; -import com.sk89q.worldguard.protection.flags.StateFlag; -import com.sk89q.worldguard.protection.flags.registry.FlagRegistry; -import com.sk89q.worldguard.protection.regions.RegionQuery; -import net.momirealms.customcrops.integrations.CCAntiGrief; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class WorldGuardHook implements CCAntiGrief { - - @Override - public String getName() { - return "WorldGuard"; - } - - public static StateFlag HARVEST_FLAG; - public static StateFlag PLACE_FLAG; - - public static void initialize() { - FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); - if (HARVEST_FLAG == null) { - HARVEST_FLAG = new StateFlag("customcrops-harvest", false); - registry.register(HARVEST_FLAG); - } - if (PLACE_FLAG == null) { - PLACE_FLAG = new StateFlag("customcrops-place", false); - registry.register(PLACE_FLAG); - } - } - - @Override - public boolean canPlace(Location location, Player player) { - LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player); - WorldGuardPlatform platform = WorldGuard.getInstance().getPlatform(); - RegionQuery query = platform.getRegionContainer().createQuery(); - return query.testBuild(BukkitAdapter.adapt(location), localPlayer, PLACE_FLAG); - } - - @Override - public boolean canBreak(Location location, Player player) { - LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player); - WorldGuardPlatform platform = WorldGuard.getInstance().getPlatform(); - RegionQuery query = platform.getRegionContainer().createQuery(); - return query.testBuild(BukkitAdapter.adapt(location), localPlayer, HARVEST_FLAG); - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/integrations/quest/BattlePassCCQuest.java b/src/main/java/net/momirealms/customcrops/integrations/quest/BattlePassCCQuest.java deleted file mode 100644 index a521caf..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/quest/BattlePassCCQuest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.quest; - -import io.github.battlepass.BattlePlugin; -import io.github.battlepass.quests.quests.external.executor.ExternalQuestExecutor; -import io.github.battlepass.registry.quest.QuestRegistry; -import net.momirealms.customcrops.api.event.CropHarvestEvent; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -public class BattlePassCCQuest extends ExternalQuestExecutor implements Listener { - - public static void register() { - QuestRegistry questRegistry = BattlePlugin.getApi().getQuestRegistry(); - questRegistry.hook("customcrops", BattlePassCCQuest::new); - } - - public BattlePassCCQuest(BattlePlugin battlePlugin) { - super(battlePlugin, "customcrops"); - } - - @EventHandler - public void onHarvest(CropHarvestEvent event) { - if (event.isCancelled()) return; - Player player = event.getPlayer(); - this.execute("harvest", player, (var1x) -> var1x.root(event.getCrop().getKey())); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/quest/ClueScrollCCQuest.java b/src/main/java/net/momirealms/customcrops/integrations/quest/ClueScrollCCQuest.java deleted file mode 100644 index 13caffd..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/quest/ClueScrollCCQuest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.quest; - -import com.electro2560.dev.cluescrolls.api.*; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.event.CropHarvestEvent; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -public class ClueScrollCCQuest implements Listener { - - private final CustomClue commonClue; - - public ClueScrollCCQuest() { - commonClue = ClueScrollsAPI.getInstance().registerCustomClue(CustomCrops.plugin, "harvest", new ClueConfigData("crop_id", DataType.STRING)); - } - - @EventHandler - public void onHarvest(CropHarvestEvent event) { - if (event.isCancelled()) return; - commonClue.handle(event.getPlayer(), 1, new ClueDataPair("crop_id", event.getCrop().getKey())); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/quest/NewBetonQuestCCQuest.java b/src/main/java/net/momirealms/customcrops/integrations/quest/NewBetonQuestCCQuest.java deleted file mode 100644 index 08e4699..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/quest/NewBetonQuestCCQuest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.quest; - -import net.momirealms.customcrops.api.event.CropHarvestEvent; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.betonquest.betonquest.BetonQuest; -import org.betonquest.betonquest.Instruction; -import org.betonquest.betonquest.VariableNumber; -import org.betonquest.betonquest.api.CountingObjective; -import org.betonquest.betonquest.api.profiles.OnlineProfile; -import org.betonquest.betonquest.api.profiles.Profile; -import org.betonquest.betonquest.exceptions.InstructionParseException; -import org.betonquest.betonquest.utils.PlayerConverter; -import org.betonquest.betonquest.utils.location.CompoundLocation; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.event.EventHandler; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; - -import java.util.Collections; -import java.util.HashSet; - -public class NewBetonQuestCCQuest extends CountingObjective implements Listener { - - private final CompoundLocation playerLocation; - private final VariableNumber rangeVar; - private final HashSet crop_ids; - - public NewBetonQuestCCQuest(Instruction instruction) throws InstructionParseException { - super(instruction, "crop_to_harvest"); - crop_ids = new HashSet<>(); - Collections.addAll(crop_ids, instruction.getArray()); - targetAmount = instruction.getInt(); - - final String pack = instruction.getPackage().getQuestPath(); - final String loc = instruction.getOptional("playerLocation"); - final String range = instruction.getOptional("range"); - if (loc != null && range != null) { - playerLocation = new CompoundLocation(pack, loc); - rangeVar = new VariableNumber(pack, range); - } else { - playerLocation = null; - rangeVar = null; - } - - if (targetAmount <= 0) { - throw new InstructionParseException("Crop amount cannot be less than 0"); - } - } - - public static void register() { - BetonQuest.getInstance().registerObjectives("customcrops", NewBetonQuestCCQuest.class); - } - - @EventHandler - public void onHarvest(CropHarvestEvent event) { - OnlineProfile onlineProfile = PlayerConverter.getID(event.getPlayer()); - if (!containsPlayer(onlineProfile)) { - return; - } - if (isInvalidLocation(event, onlineProfile)) { - return; - } - if (this.crop_ids.contains(event.getCrop().getKey()) && this.checkConditions(onlineProfile)) { - getCountingData(onlineProfile).progress(1); - completeIfDoneOrNotify(onlineProfile); - } - } - - private boolean isInvalidLocation(CropHarvestEvent event, final Profile profile) { - if (playerLocation == null || rangeVar == null) { - return false; - } - - final Location targetLocation; - try { - targetLocation = playerLocation.getLocation(profile); - } catch (final org.betonquest.betonquest.exceptions.QuestRuntimeException e) { - AdventureUtil.consoleMessage(e.getMessage()); - return true; - } - final int range = rangeVar.getInt(profile); - final Location playerLoc = event.getPlayer().getLocation(); - return !playerLoc.getWorld().equals(targetLocation.getWorld()) || targetLocation.distanceSquared(playerLoc) > range * range; - } - - @Override - public void start() { - Bukkit.getPluginManager().registerEvents(this, BetonQuest.getInstance()); - } - - @Override - public void stop() { - HandlerList.unregisterAll(this); - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/quest/OldBetonQuestCCQuest.java b/src/main/java/net/momirealms/customcrops/integrations/quest/OldBetonQuestCCQuest.java deleted file mode 100644 index dd35437..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/quest/OldBetonQuestCCQuest.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.quest; - -import net.momirealms.customcrops.api.event.CropHarvestEvent; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import pl.betoncraft.betonquest.BetonQuest; -import pl.betoncraft.betonquest.Instruction; -import pl.betoncraft.betonquest.api.Objective; -import pl.betoncraft.betonquest.config.Config; -import pl.betoncraft.betonquest.exceptions.InstructionParseException; -import pl.betoncraft.betonquest.exceptions.QuestRuntimeException; -import pl.betoncraft.betonquest.utils.LogUtils; -import pl.betoncraft.betonquest.utils.PlayerConverter; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Locale; -import java.util.logging.Level; - -public class OldBetonQuestCCQuest extends Objective implements Listener { - - private final HashSet crop_ids = new HashSet<>(); - private final int amount; - private final boolean notify; - private final int notifyInterval; - - public OldBetonQuestCCQuest(Instruction instruction) throws InstructionParseException { - super(instruction); - this.template = CropData.class; - this.notifyInterval = instruction.getInt(instruction.getOptional("notify"), 1); - this.notify = instruction.hasArgument("notify") || this.notifyInterval > 1; - this.amount = instruction.getInt(instruction.getOptional("amount"), 1); - Collections.addAll(this.crop_ids, instruction.getArray()); - } - - public static void register() { - BetonQuest.getInstance().registerObjectives("customfishing", OldBetonQuestCCQuest.class); - } - - @Override - public void start() { - Bukkit.getPluginManager().registerEvents(this, BetonQuest.getInstance()); - } - - @Override - public void stop() { - HandlerList.unregisterAll(this); - } - - @Override - public String getDefaultDataInstruction() { - return Integer.toString(this.amount); - } - - @Override - public String getProperty(String name, String playerID) { - return switch (name.toLowerCase(Locale.ROOT)) { - case "amount" -> - Integer.toString(this.amount - ((OldBetonQuestCCQuest.CropData) this.dataMap.get(playerID)).getAmount()); - case "left" -> Integer.toString(((OldBetonQuestCCQuest.CropData) this.dataMap.get(playerID)).getAmount()); - case "total" -> Integer.toString(this.amount); - default -> ""; - }; - } - - private boolean isValidPlayer(Player player) { - if (player == null) { - return false; - } else { - return player.isOnline() && player.isValid(); - } - } - - @EventHandler - public void onHarvest(CropHarvestEvent event) { - String playerID = PlayerConverter.getID(event.getPlayer()); - if (this.containsPlayer(playerID)) { - if (this.crop_ids.contains(event.getCrop().getKey())) { - if (this.checkConditions(playerID)) { - if (!isValidPlayer(event.getPlayer())) { - return; - } - CropData cropData = (CropData) this.dataMap.get(playerID); - cropData.harvest(1); - if (cropData.finished()) { - this.completeObjective(playerID); - } - else if (this.notify && cropData.getAmount() % this.notifyInterval == 0) { - try { - Config.sendNotify(this.instruction.getPackage().getName(), playerID, "crop_to_harvest", new String[]{String.valueOf(cropData.getAmount())}, "crop_to_harvest,info"); - } catch (QuestRuntimeException e1) { - try { - LogUtils.getLogger().log(Level.WARNING, "The notify system was unable to play a sound for the 'crop_to_harvest' category in '" + this.instruction.getObjective().getFullID() + "'. Error was: '" + e1.getMessage() + "'"); - } catch (InstructionParseException e2) { - LogUtils.logThrowableReport(e2); - } - } - } - } - } - } - } - - public static class CropData extends Objective.ObjectiveData { - private int amount; - - public CropData(String instruction, String playerID, String objID) { - super(instruction, playerID, objID); - try { - this.amount = Integer.parseInt(instruction); - } - catch (NumberFormatException e) { - AdventureUtil.consoleMessage("[CustomCrops] NumberFormatException"); - this.amount = 1; - } - } - - public void harvest(int caughtAmount) { - this.amount -= caughtAmount; - this.update(); - } - - public int getAmount() { - return this.amount; - } - - public String toString() { - return String.valueOf(this.amount); - } - - public boolean finished() { - return this.amount <= 0; - } - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/integrations/season/InternalSeason.java b/src/main/java/net/momirealms/customcrops/integrations/season/InternalSeason.java deleted file mode 100644 index 8bc44e6..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/season/InternalSeason.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.season; - -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.utils.CCSeason; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.config.SeasonConfig; -import net.momirealms.customcrops.objects.Function; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; -import java.util.concurrent.ConcurrentHashMap; - -public class InternalSeason extends Function implements SeasonInterface { - - private ConcurrentHashMap seasonHashMap; - private BukkitTask task; - - public InternalSeason() { - load(); - } - - @Override - public void load() { - super.load(); - this.seasonHashMap = new ConcurrentHashMap<>(); - startTimer(); - } - - @Override - public void unload() { - super.unload(); - this.seasonHashMap.clear(); - if (task != null) task.cancel(); - } - - @Override - public boolean isWrongSeason(World world, @Nullable CCSeason[] seasonList) { - if (seasonList == null) return false; - for (CCSeason season : seasonList) { - if (season == getSeason(world)) { - return false; - } - } - return true; - } - - @Override - public void unloadWorld(World world) { - seasonHashMap.remove(world); - } - - @Override - @NotNull - public CCSeason getSeason(World world) { - CCSeason season; - if (MainConfig.syncSeason) season = seasonHashMap.get(MainConfig.syncWorld); - else season = seasonHashMap.get(world); - if (season == null) { - season = countSeason(world); - setSeason(season, world); - } - return season; - } - - @Override - public void setSeason(CCSeason season, World world) { - if (season == CCSeason.UNKNOWN) { - setSeason(countSeason(world), world); - } - else { - if (MainConfig.syncSeason && world != MainConfig.syncWorld) { - seasonHashMap.put(world, getSeason(MainConfig.syncWorld)); - return; - } - CCSeason oldSeason = seasonHashMap.put(world, season); - if (!MainConfig.enableSeasonBroadcast && !MainConfig.enableSeasonChangeCmd) return; - if (oldSeason == null) return; - // season changed - if (oldSeason != season) { - if (MainConfig.enableSeasonBroadcast) { - Collection players; - if (MainConfig.syncSeason) players = Bukkit.getOnlinePlayers(); - else players = world.getPlayers(); - - switch (season) { - case SPRING -> players.forEach(player -> { - for (String msg : MainConfig.springMsg) { - AdventureUtil.playerMessage(player, msg); - } - }); - case SUMMER -> players.forEach(player -> { - for (String msg : MainConfig.summerMsg) { - AdventureUtil.playerMessage(player, msg); - } - }); - case AUTUMN -> players.forEach(player -> { - for (String msg : MainConfig.autumnMsg) { - AdventureUtil.playerMessage(player, msg); - } - }); - case WINTER -> players.forEach(player -> { - for (String msg : MainConfig.winterMsg) { - AdventureUtil.playerMessage(player, msg); - } - }); - } - } - if (MainConfig.enableSeasonChangeCmd) { - switch (season) { - case SPRING -> { - for (String cmd : MainConfig.springCmd) - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); - } - case SUMMER -> { - for (String cmd : MainConfig.summerCmd) - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); - } - case AUTUMN -> { - for (String cmd : MainConfig.autumnCmd) - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); - } - case WINTER -> { - for (String cmd : MainConfig.winterCmd) - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); - } - } - } - } - } - } - - private void startTimer() { - this.task = new BukkitRunnable() { - @Override - public void run() { - if (!SeasonConfig.auto) return; - for (String world_name : MainConfig.getWorldNameList()) { - World world = Bukkit.getWorld(world_name); - if (world != null) { - if (world.getTime() < 100) { - setSeason(countSeason(world), world); - } - } - } - } - }.runTaskTimerAsynchronously(CustomCrops.plugin, 0, 100); - } - - private CCSeason countSeason(World world) { - int season = (int) ((world.getFullTime() / 24000L) % (SeasonConfig.duration * 4)) / SeasonConfig.duration; - return switch (season) { - case 0 -> CCSeason.SPRING; - case 1 -> CCSeason.SUMMER; - case 2 -> CCSeason.AUTUMN; - case 3 -> CCSeason.WINTER; - default -> CCSeason.UNKNOWN; - }; - } -} diff --git a/src/main/java/net/momirealms/customcrops/integrations/season/RealisticSeasonsHook.java b/src/main/java/net/momirealms/customcrops/integrations/season/RealisticSeasonsHook.java deleted file mode 100644 index f96bdef..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/season/RealisticSeasonsHook.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.season; - -import me.casperge.realisticseasons.api.SeasonsAPI; -import net.momirealms.customcrops.api.utils.CCSeason; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.objects.Function; -import org.bukkit.World; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class RealisticSeasonsHook extends Function implements SeasonInterface { - - private SeasonsAPI api; - - public RealisticSeasonsHook() { - load(); - } - - @Override - public void load() { - super.load(); - this.api = SeasonsAPI.getInstance(); - } - - @Override - public void unload() { - super.unload(); - } - - @Override - public boolean isWrongSeason(World world, @Nullable CCSeason[] seasonList) { - if (seasonList == null) return false; - for (CCSeason season : seasonList) { - if (season == getSeason(world)) { - return false; - } - } - return true; - } - - @Override - public void unloadWorld(World world) { - } - - /** - * Get the season from RealisticSeasons - * @param world world - * @return CustomCrops Season - */ - @Override - @NotNull - public CCSeason getSeason(World world){ - if (!MainConfig.syncSeason) { - switch (api.getSeason(world)){ - case SPRING -> {return CCSeason.SPRING;} - case SUMMER -> {return CCSeason.SUMMER;} - case WINTER -> {return CCSeason.WINTER;} - case FALL -> {return CCSeason.AUTUMN;} - } - } - else { - switch (api.getSeason(MainConfig.syncWorld)){ - case SPRING -> {return CCSeason.SPRING;} - case SUMMER -> {return CCSeason.SUMMER;} - case WINTER -> {return CCSeason.WINTER;} - case FALL -> {return CCSeason.AUTUMN;} - } - } - return CCSeason.UNKNOWN; - } - - @Override - public void setSeason(CCSeason season, World world) { - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/integrations/season/SeasonInterface.java b/src/main/java/net/momirealms/customcrops/integrations/season/SeasonInterface.java deleted file mode 100644 index 48df5e5..0000000 --- a/src/main/java/net/momirealms/customcrops/integrations/season/SeasonInterface.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.integrations.season; - -import net.momirealms.customcrops.api.utils.CCSeason; -import org.bukkit.World; - -public interface SeasonInterface { - - CCSeason getSeason(World world); - - void setSeason(CCSeason season, World world); - - void load(); - - void unload(); - - boolean isWrongSeason(World world, CCSeason[] seasonList); - - void unloadWorld(World world); - -} diff --git a/src/main/java/net/momirealms/customcrops/managers/CropManager.java b/src/main/java/net/momirealms/customcrops/managers/CropManager.java deleted file mode 100644 index fc5a88d..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/CropManager.java +++ /dev/null @@ -1,606 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.managers; - -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.api.event.CropHarvestEvent; -import net.momirealms.customcrops.api.event.CrowAttackEvent; -import net.momirealms.customcrops.api.utils.CCSeason; -import net.momirealms.customcrops.config.*; -import net.momirealms.customcrops.integrations.customplugin.CustomInterface; -import net.momirealms.customcrops.integrations.customplugin.HandlerP; -import net.momirealms.customcrops.integrations.customplugin.itemsadder.ItemsAdderFrameHandler; -import net.momirealms.customcrops.integrations.customplugin.itemsadder.ItemsAdderHook; -import net.momirealms.customcrops.integrations.customplugin.itemsadder.ItemsAdderWireHandler; -import net.momirealms.customcrops.integrations.customplugin.oraxen.OraxenFrameHandler; -import net.momirealms.customcrops.integrations.customplugin.oraxen.OraxenHook; -import net.momirealms.customcrops.integrations.customplugin.oraxen.OraxenWireHandler; -import net.momirealms.customcrops.integrations.item.MMOItemsHook; -import net.momirealms.customcrops.integrations.item.MythicMobsHook; -import net.momirealms.customcrops.integrations.season.InternalSeason; -import net.momirealms.customcrops.integrations.season.RealisticSeasonsHook; -import net.momirealms.customcrops.integrations.season.SeasonInterface; -import net.momirealms.customcrops.managers.listener.*; -import net.momirealms.customcrops.managers.timer.CrowTask; -import net.momirealms.customcrops.managers.timer.TimerTask; -import net.momirealms.customcrops.objects.*; -import net.momirealms.customcrops.objects.actions.ActionInterface; -import net.momirealms.customcrops.objects.fertilizer.*; -import net.momirealms.customcrops.utils.AdventureUtil; -import net.momirealms.customcrops.utils.ArmorStandUtil; -import net.momirealms.customcrops.utils.FurnitureUtil; -import net.momirealms.customcrops.utils.MiscUtils; -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.entity.Item; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Nullable; - -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ThreadLocalRandom; - -public class CropManager extends Function { - - private TimerTask timerTask; - private ConcurrentHashMap customWorlds; - private SeasonInterface seasonInterface; - private CustomInterface customInterface; - private ArmorStandUtil armorStandUtil; - private ContainerListener containerListener; - private PlayerModeListener playerModeListener; - private VanillaCropPlaceListener vanillaCropPlaceListener; - private VanillaCropHarvestListener vanillaCropHarvestListener; - private ItemSpawnListener itemSpawnListener; - private WorldListener worldListener; - private HandlerP handler; - - public CropManager() { - load(); - } - - @Override - public void load() { - - this.customWorlds = new ConcurrentHashMap<>(); - this.itemSpawnListener = new ItemSpawnListener(this); - this.worldListener = new WorldListener(this); - this.armorStandUtil = new ArmorStandUtil(this); - this.vanillaCropPlaceListener = new VanillaCropPlaceListener(); - this.vanillaCropHarvestListener = new VanillaCropHarvestListener(); - this.containerListener = new ContainerListener(this); - this.playerModeListener = new PlayerModeListener(); - - Bukkit.getPluginManager().registerEvents(itemSpawnListener, CustomCrops.plugin); - Bukkit.getPluginManager().registerEvents(worldListener, CustomCrops.plugin); - - this.reload(); - - for (World world : Bukkit.getWorlds()) { - onWorldLoad(world); - } - - this.timerTask = new TimerTask(this); - this.timerTask.runTaskTimerAsynchronously(CustomCrops.plugin, 1,100); - } - - public void reload() { - - unloadMode(); - loadMode(); - - unloadSeason(); - loadSeason(); - - unloadPacket(); - loadPacket(); - - unloadVanillaMechanic(); - loadVanillaMechanic(); - } - - @Override - public void unload() { - HandlerList.unregisterAll(this.itemSpawnListener); - HandlerList.unregisterAll(this.worldListener); - if (this.handler != null) handler.unload(); - if (this.timerTask != null) this.timerTask.cancel(); - - for (CustomWorld customWorld : customWorlds.values()) { - customWorld.unload(true); - } - customWorlds.clear(); - - if (this.seasonInterface != null) seasonInterface.unload(); - if (this.containerListener != null) CustomCrops.protocolManager.removePacketListener(containerListener); - } - - public void loadVanillaMechanic() { - if (MainConfig.preventPlantVanilla) Bukkit.getPluginManager().registerEvents(vanillaCropPlaceListener, CustomCrops.plugin); - if (MainConfig.rightHarvestVanilla) Bukkit.getPluginManager().registerEvents(vanillaCropHarvestListener, CustomCrops.plugin); - } - - public void unloadVanillaMechanic() { - HandlerList.unregisterAll(vanillaCropHarvestListener); - HandlerList.unregisterAll(vanillaCropPlaceListener); - } - - public void unloadMode() { - if (this.handler != null) { - handler.unload(); - handler = null; - } - } - - public void loadMode() { - //Custom Plugin - if (MainConfig.customPlugin.equals("itemsadder")) { - customInterface = new ItemsAdderHook(); - if (MainConfig.cropMode) { - this.handler = new ItemsAdderWireHandler(this); - this.handler.load(); - } - else { - this.handler = new ItemsAdderFrameHandler(this); - this.handler.load(); - } - } - else if (MainConfig.customPlugin.equals("oraxen")){ - customInterface = new OraxenHook(); - if (MainConfig.cropMode) { - this.handler = new OraxenWireHandler(this); - this.handler.load(); - } - else { - this.handler = new OraxenFrameHandler(this); - this.handler.load(); - } - } - } - - public void loadSeason() { - if (!SeasonConfig.enable) return; - if (MainConfig.realisticSeasonHook) seasonInterface = new RealisticSeasonsHook(); - else seasonInterface = new InternalSeason(); - } - - public void unloadSeason() { - for (CustomWorld customWorld : customWorlds.values()) { - customWorld.unloadSeason(); - } - if (seasonInterface != null) seasonInterface.unload(); - } - - public void loadPacket() { - if (!MainConfig.enableWaterCanLore || !MainConfig.enablePacketLore) return; - CustomCrops.protocolManager.addPacketListener(containerListener); - Bukkit.getPluginManager().registerEvents(playerModeListener, CustomCrops.plugin); - } - - public void unloadPacket() { - CustomCrops.protocolManager.removePacketListener(containerListener); - HandlerList.unregisterAll(playerModeListener); - } - - public void onItemSpawn(Item item) { - String id = customInterface.getItemID(item.getItemStack()); - if (id == null) return; - if (id.contains("_stage_")) item.remove(); - if (id.equals(BasicItemConfig.wetPot)) { - ItemStack dryPots = customInterface.getItemStack(BasicItemConfig.dryPot); - if (dryPots == null) return; - dryPots.setAmount(item.getItemStack().getAmount()); - item.setItemStack(dryPots); - } - } - - public void onWorldLoad(World world) { - CustomWorld cw = customWorlds.get(world); - if (cw != null) return; - if (MainConfig.getWorldNameList().contains(world.getName())) { - CustomWorld customWorld = new CustomWorld(world, this); - customWorlds.put(world, customWorld); - if (MainConfig.autoGrow && MainConfig.enableCompensation) { - if (world.getTime() > 1200) { - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.plugin, () -> grow(world, MainConfig.timeToGrow, 0, 0, true, false), 100); - } - } - } - } - - public void onWorldUnload(World world, boolean disable) { - CustomWorld customWorld = customWorlds.get(world); - if (customWorld == null) return; - customWorld.unload(disable); - customWorlds.remove(world); - seasonInterface.unloadWorld(world); - } - - public void grow(World world, int cropTime, int sprinklerTime, int dryTime, boolean compensation, boolean force) { - CustomWorld customWorld = customWorlds.get(world); - if (customWorld == null) return; - if (MainConfig.cropMode) customWorld.growWire(cropTime, sprinklerTime, dryTime, compensation, force); - else customWorld.growFrame(cropTime, sprinklerTime, dryTime, compensation, force); - } - - public SeasonInterface getSeasonAPI() { - return seasonInterface; - } - - public boolean hasGlass(Location location) { - for(int i = 1; i <= SeasonConfig.effectiveRange; i++){ - String blockID = customInterface.getBlockID(location.clone().add(0,i,0)); - if (blockID != null && blockID.equals(BasicItemConfig.greenHouseGlass)) return true; - } - return false; - } - - public boolean hasScarecrow(Location location) { - CustomWorld customWorld = customWorlds.get(location.getWorld()); - if (customWorld == null) return true; - return customWorld.hasScarecrowCache(location); - } - - public CustomInterface getCustomInterface() { - return customInterface; - } - - public boolean isWrongSeason(Location location, CCSeason[] seasonList) { - if (!SeasonConfig.enable) return false; - if (seasonInterface.isWrongSeason(location.getWorld(), seasonList)) { - if (SeasonConfig.greenhouse) return !hasGlass(location); - else return true; - } - return false; - } - - @Nullable - public Fertilizer getFertilizer(Location potLoc) { - World world = potLoc.getWorld(); - CustomWorld customWorld = customWorlds.get(world); - if (customWorld == null) return null; - return customWorld.getFertilizerCache(potLoc); - } - - public void makePotDry(Location potLoc) { - String potID = customInterface.getBlockID(potLoc); - if (potID == null) return; - if (!potID.equals(BasicItemConfig.wetPot)) return; - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - customInterface.removeBlock(potLoc); - customInterface.placeNoteBlock(potLoc, BasicItemConfig.dryPot); - }); - } - - public void dry(Location potLoc) { - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - customInterface.removeBlock(potLoc); - customInterface.placeNoteBlock(potLoc, BasicItemConfig.dryPot); - }); - } - - public void makePotWet(Location potLoc) { - String potID = customInterface.getBlockID(potLoc); - if (potID == null) return; - if (!potID.equals(BasicItemConfig.dryPot)) return; - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - customInterface.removeBlock(potLoc); - customInterface.placeNoteBlock(potLoc, BasicItemConfig.wetPot); - }); - } - - @Nullable - public CustomWorld getCustomWorld(World world) { - return customWorlds.get(world); - } - - public void proceedHarvest(Crop crop, Player player, Location location, @Nullable Fertilizer fertilizer, boolean isRightClick) { - //Call harvest event - CropHarvestEvent cropHarvestEvent = new CropHarvestEvent(player, crop, location, fertilizer); - Bukkit.getPluginManager().callEvent(cropHarvestEvent); - if (cropHarvestEvent.isCancelled()) return; - - if (!isRightClick && player.getGameMode() == GameMode.CREATIVE) return; - ActionInterface[] actions = crop.getActions(); - if (actions != null) performActions(actions, player); - - if (SoundConfig.harvestCrop.isEnable()) { - AdventureUtil.playerSound( - player, - SoundConfig.harvestCrop.getSource(), - SoundConfig.harvestCrop.getKey(), - 1,1 - ); - } - QualityLoot qualityLoot = crop.getQualityLoot(); - if (qualityLoot != null) { - int amount = ThreadLocalRandom.current().nextInt(qualityLoot.getMin(), qualityLoot.getMax() + 1); - QualityRatio qualityRatio = null; - if (fertilizer instanceof YieldIncreasing yieldIncreasing) { - if (Math.random() < yieldIncreasing.getChance()) { - amount += yieldIncreasing.getBonus(); - } - } - else if (fertilizer instanceof QualityCrop qualityCrop) { - if (Math.random() < qualityCrop.getChance()) { - qualityRatio = qualityCrop.getQualityRatio(); - } - } - if (MainConfig.enableSkillBonus && MainConfig.skillInterface != null) { - double bonus_chance = MainConfig.skillInterface.getLevel(player) * MainConfig.bonusPerLevel; - amount *= (bonus_chance + 1); - } - dropQualityLoots(qualityLoot, amount, location.getBlock().getLocation(), qualityRatio); - } - OtherLoot[] otherLoots = crop.getOtherLoots(); - if (otherLoots != null) dropOtherLoots(otherLoots, location.getBlock().getLocation(), player); - } - - public void performActions(ActionInterface[] actions, Player player) { - for (ActionInterface action : actions) { - if (Math.random() <= action.getChance()) { - action.performOn(player); - } - } - } - - public void dropOtherLoots(OtherLoot[] otherLoots, Location location, Player player) { - for (OtherLoot otherLoot : otherLoots) { - if (Math.random() < otherLoot.getChance()) { - int random = ThreadLocalRandom.current().nextInt(otherLoot.getMin(), otherLoot.getMax() + 1); - if (MainConfig.enableSkillBonus && MainConfig.skillInterface != null) { - double bonus_chance = MainConfig.skillInterface.getLevel(player) * MainConfig.bonusPerLevel; - random *= (bonus_chance + 1); - } - ItemStack drop = getLoot(otherLoot.getItemID()); - if (drop == null) continue; - drop.setAmount(random); - location.getWorld().dropItemNaturally(location, drop); - } - } - } - - public void dropQualityLoots(QualityLoot qualityLoot, int amount, Location location, @Nullable QualityRatio qualityRatio) { - if (qualityRatio == null) qualityRatio = MainConfig.qualityRatio; - for (int i = 0; i < amount; i++) { - double random = Math.random(); - World world = location.getWorld(); - if (random < qualityRatio.getQuality_1()) { - ItemStack drop = getLoot(qualityLoot.getQuality_1()); - if (drop == null) continue; - world.dropItemNaturally(location, drop); - } - else if(random > qualityRatio.getQuality_2()){ - ItemStack drop = getLoot(qualityLoot.getQuality_2()); - if (drop == null) continue; - world.dropItemNaturally(location, drop); - } - else { - ItemStack drop = getLoot(qualityLoot.getQuality_3()); - if (drop == null) continue; - world.dropItemNaturally(location, drop); - } - } - } - - @Nullable - private ItemStack getLoot(String id) { - if (id == null) return null; - if (MiscUtils.isVanillaItem(id)) return new ItemStack(Material.valueOf(id)); - else if (id.startsWith("MMOItems:")) return MMOItemsHook.get(id); - else if (id.startsWith("MythicMobs:")) return MythicMobsHook.get(id); - else return customInterface.getItemStack(id); - } - - public boolean crowJudge(Location location, ItemFrame itemFrame) { - if (Math.random() < MainConfig.crowChance && !hasScarecrow(location)) { - for (Player player : location.getNearbyPlayers(48)) { - CrowTask crowTask = new CrowTask(player, location.clone().add(0.4,0,0.4), getArmorStandUtil()); - crowTask.runTaskTimerAsynchronously(CustomCrops.plugin, 1, 1); - } - Bukkit.getScheduler().runTaskLater(CustomCrops.plugin, () -> { - customInterface.removeFurniture(itemFrame); - }, 125); - return true; - } - return false; - } - - public boolean crowJudge(Location location) { - if (Math.random() < MainConfig.crowChance && !hasScarecrow(location)) { - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - CrowAttackEvent crowAttackEvent = new CrowAttackEvent(location); - Bukkit.getPluginManager().callEvent(crowAttackEvent); - for (Player player : location.getNearbyPlayers(48)) { - CrowTask crowTask = new CrowTask(player, location.clone().add(0.4,0,0.4), getArmorStandUtil()); - crowTask.runTaskTimerAsynchronously(CustomCrops.plugin, 1, 1); - } - }); - - Bukkit.getScheduler().runTaskLater(CustomCrops.plugin, () -> { - customInterface.removeBlock(location); - }, 125); - - return true; - } - return false; - } - - public void saveData(World world) { - CustomWorld customWorld = getCustomWorld(world); - if (customWorld == null) return; - customWorld.tryToSaveData(); - } - - public ArmorStandUtil getArmorStandUtil() { - return armorStandUtil; - } - - public HandlerP getHandler() { - return handler; - } - - public boolean wireGrowJudge(Location location, GrowingCrop growingCrop) { - Crop crop = CropConfig.CROPS.get(growingCrop.getType()); - if (crop == null) return true; - - Location potLoc = location.clone().subtract(0,1,0); - Fertilizer fertilizer = getFertilizer(potLoc); - - int current_stage = growingCrop.getStage(); - if (current_stage == crop.getMax_stage()) { - GiganticCrop giganticCrop = crop.getGiganticCrop(); - if (giganticCrop != null) { - double chance = giganticCrop.getChance(); - if (fertilizer instanceof Gigantic gigantic) chance += gigantic.getChance(); - if (Math.random() < chance) { - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - customInterface.removeBlock(location); - if (giganticCrop.isBlock()) customInterface.placeWire(location, giganticCrop.getBlockID()); - else customInterface.placeFurniture(location, giganticCrop.getBlockID()); - }); - } - } - return true; - } - - String blockID = customInterface.getBlockID(location); - if (blockID == null) return true; - - if ((MainConfig.needSkyLight && location.getBlock().getLightFromSky() < MainConfig.skyLightLevel) || isWrongSeason(location, crop.getSeasons())) { - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - customInterface.removeBlock(location); - customInterface.placeWire(location, BasicItemConfig.deadCrop); - }); - return true; - } - - if (MainConfig.enableCrow && crowJudge(location)) { - return true; - } - - String potID = customInterface.getBlockID(potLoc); - if (potID == null) return true; - - boolean certainGrow = potID.equals(BasicItemConfig.wetPot); - if (certainGrow && !hasWater(potLoc.getBlock())) { - if (!(fertilizer instanceof RetainingSoil retainingSoil && Math.random() < retainingSoil.getChance())) { - dry(potLoc); - certainGrow = false; - } - } - - if (MainConfig.dryMakesCropDead && !certainGrow && Math.random() < MainConfig.dryDeadChance) { - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - customInterface.removeBlock(location); - customInterface.placeWire(location, BasicItemConfig.deadCrop); - }); - return true; - } - - String temp = CropConfig.namespace + growingCrop.getType() + "_stage_"; - - if (fertilizer instanceof SpeedGrow speedGrow && Math.random() < speedGrow.getChance() && current_stage+2 <= crop.getMax_stage()) { - customInterface.addWireStage(location, temp + (current_stage+2)); - growingCrop.setStage(current_stage+2); - } - else if (certainGrow || Math.random() < MainConfig.dryGrowChance) { - customInterface.addWireStage(location, temp + (current_stage+1)); - growingCrop.setStage(current_stage+1); - } - return false; - } - - private boolean hasWater(Block block) { - return Optional.ofNullable(customWorlds.get(block.getWorld())) - .map(customWorld -> customWorld.isPotWet(block.getLocation())) - .orElse(false); - } - - public boolean itemFrameGrowJudge(Location location, GrowingCrop growingCrop) { - - Crop crop = CropConfig.CROPS.get(growingCrop.getType()); - if (crop == null) return true; - - if (!location.getChunk().isEntitiesLoaded()) return false; - - Location potLoc = location.clone().subtract(0,1,0); - Fertilizer fertilizer = getFertilizer(potLoc); - - int current_stage = growingCrop.getStage(); - if (current_stage == crop.getMax_stage()) { - GiganticCrop giganticCrop = crop.getGiganticCrop(); - if (giganticCrop != null) { - double chance = giganticCrop.getChance(); - if (fertilizer instanceof Gigantic gigantic) chance += gigantic.getChance(); - if (Math.random() < chance) { - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - ItemFrame itemFrame = FurnitureUtil.getItemFrame(customInterface.getFrameCropLocation(location)); - if (itemFrame != null) { - customInterface.removeFurniture(itemFrame); - if (giganticCrop.isBlock()) customInterface.placeWire(location, giganticCrop.getBlockID()); - else customInterface.placeFurniture(location, giganticCrop.getBlockID()); - } - }); - } - } - return true; - } - - ItemFrame itemFrame = FurnitureUtil.getItemFrame(customInterface.getFrameCropLocation(location)); - if (itemFrame == null) return true; - - if ((MainConfig.needSkyLight && location.getBlock().getLightFromSky() < MainConfig.skyLightLevel) || isWrongSeason(location, crop.getSeasons())) { - itemFrame.setItem(customInterface.getItemStack(BasicItemConfig.deadCrop), false); - return true; - } - - if (MainConfig.enableCrow && crowJudge(location, itemFrame)) return true; - - String potID = customInterface.getBlockID(potLoc); - if (potID == null) return true; - - boolean certainGrow = potID.equals(BasicItemConfig.wetPot); - if (certainGrow && !hasWater(potLoc.getBlock())) { - if (!(fertilizer instanceof RetainingSoil retainingSoil && Math.random() < retainingSoil.getChance())) { - dry(potLoc); - certainGrow = false; - } - } - - if (MainConfig.dryMakesCropDead && !certainGrow && Math.random() < MainConfig.dryDeadChance) { - itemFrame.setItem(customInterface.getItemStack(BasicItemConfig.deadCrop), false); - return true; - } - - String temp = CropConfig.namespace + growingCrop.getType() + "_stage_"; - if (fertilizer instanceof SpeedGrow speedGrow && Math.random() < speedGrow.getChance() && current_stage+2 <= crop.getMax_stage()) { - customInterface.addFrameStage(itemFrame, temp + (current_stage+2), crop.canRotate()); - growingCrop.setStage(current_stage+2); - } - else if (certainGrow || Math.random() < MainConfig.dryGrowChance) { - customInterface.addFrameStage(itemFrame, temp + (current_stage+1), crop.canRotate()); - growingCrop.setStage(current_stage+1); - } - return false; - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/managers/CropModeInterface.java b/src/main/java/net/momirealms/customcrops/managers/CropModeInterface.java deleted file mode 100644 index ccc772b..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/CropModeInterface.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.managers; - -import net.momirealms.customcrops.objects.GrowingCrop; -import org.bukkit.Chunk; -import org.bukkit.Location; - -public interface CropModeInterface { - - boolean growJudge(Location location, GrowingCrop growingCrop); - - default void loadChunk(Location location) { - Chunk chunk = location.getChunk(); - chunk.load(); - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/managers/CustomWorld.java b/src/main/java/net/momirealms/customcrops/managers/CustomWorld.java deleted file mode 100644 index ded0b35..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/CustomWorld.java +++ /dev/null @@ -1,634 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.managers; - -import com.google.gson.*; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.api.event.CustomWorldEvent; -import net.momirealms.customcrops.api.utils.CCSeason; -import net.momirealms.customcrops.api.utils.SeasonUtils; -import net.momirealms.customcrops.config.*; -import net.momirealms.customcrops.objects.GrowingCrop; -import net.momirealms.customcrops.objects.SimpleLocation; -import net.momirealms.customcrops.objects.Sprinkler; -import net.momirealms.customcrops.objects.WorldState; -import net.momirealms.customcrops.objects.fertilizer.Fertilizer; -import net.momirealms.customcrops.objects.fertilizer.RetainingSoil; -import net.momirealms.customcrops.utils.AdventureUtil; -import net.momirealms.customcrops.utils.MiscUtils; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitScheduler; -import org.jetbrains.annotations.Nullable; - -import java.io.*; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ThreadLocalRandom; - -public class CustomWorld { - - private final World world; - private final ConcurrentHashMap sprinklerCache; - private final ConcurrentHashMap fertilizerCache; - private final ConcurrentHashMap> scarecrowCache; - private final ConcurrentHashMap cropData; - private final Set watered; - private HashSet tempWatered; - private final HashSet playerWatered; - private final CropManager cropManager; - private final BukkitScheduler bukkitScheduler; - private final HashSet plantedToday; - private int timer; - - public CustomWorld(World world, CropManager cropManager) { - this.world = world; - this.fertilizerCache = new ConcurrentHashMap<>(2048); - this.sprinklerCache = new ConcurrentHashMap<>(512); - this.scarecrowCache = new ConcurrentHashMap<>(128); - this.cropData = new ConcurrentHashMap<>(2048); - this.cropManager = cropManager; - this.bukkitScheduler = Bukkit.getScheduler(); - this.watered = Collections.synchronizedSet(new HashSet<>()); - this.playerWatered = new HashSet<>(); - this.tempWatered = new HashSet<>(); - this.plantedToday = new HashSet<>(); - this.timer = 0; - - Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> { - loadData(); - loadSeason(); - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - CustomWorldEvent customWorldEvent = new CustomWorldEvent(world, WorldState.LOAD); - Bukkit.getPluginManager().callEvent(customWorldEvent); - }); - }); - } - - public void unload(boolean sync) { - if (sync) { - unloadData(); - unloadSeason(); - backUp(); - } - else { - Bukkit.getScheduler().runTaskAsynchronously(CustomCrops.plugin, () -> { - unloadData(); - unloadSeason(); - backUp(); - Bukkit.getScheduler().runTask(CustomCrops.plugin, () -> { - CustomWorldEvent customWorldEvent = new CustomWorldEvent(world, WorldState.UNLOAD); - Bukkit.getPluginManager().callEvent(customWorldEvent); - }); - }); - } - } - - public void loadData() { - loadCropCache(); - loadSprinklerCache(); - loadFertilizerCache(); - loadPot(); - loadScarecrow(); - } - - public void unloadData() { - unloadCrop(); - unloadSprinkler(); - unloadFertilizer(); - unloadPot(); - unloadScarecrow(); - } - - public void tryToSaveData() { - timer++; - if (timer >= MainConfig.saveInterval) { - timer = 0; - unloadData(); - } - } - - public void backUp() { - if (!MainConfig.autoBackUp) return; - Date date = new Date(); - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); - File file = new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + world.getName() + File.separator + "customcrops_data"); - File[] files = file.listFiles(); - if (files == null) return; - try { - for (File data : files) { - FileUtils.copyFileToDirectory(data, new File(CustomCrops.plugin.getDataFolder(), "backup" + File.separator + world.getName() + "_" + format.format(date))); - } - } - catch (IOException e) { - e.printStackTrace(); - } - } - - public void loadScarecrow() { - if (!MainConfig.enableCrow) return; - try { - JsonParser jsonParser = new JsonParser(); - JsonElement json= jsonParser.parse(new FileReader(new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + world.getName() + File.separator + "customcrops_data" + File.separator + "scarecrow.json"))); - if (json.isJsonObject()) { - JsonObject jsonObject = json.getAsJsonObject(); - for (Map.Entry en : jsonObject.entrySet()) { - JsonArray jsonArray = en.getValue().getAsJsonArray(); - int size = jsonArray.size(); - HashSet simpleLocations = new HashSet<>(); - for (int i = 0; i < size; i++) { - simpleLocations.add(MiscUtils.getSimpleLocation(jsonArray.get(i).getAsString(), world.getName())); - } - scarecrowCache.put(en.getKey(), simpleLocations); - } - } - } - catch (FileNotFoundException ignore) { - } - } - - public void unloadScarecrow() { - if (!MainConfig.enableCrow) return; - JsonObject jsonObject = new JsonObject(); - for (Map.Entry> entry : scarecrowCache.entrySet()) { - HashSet locations = entry.getValue(); - JsonArray jsonArray = new JsonArray(); - for (SimpleLocation simpleLocation : locations) { - String loc = simpleLocation.getX() + "," + simpleLocation.getY() + "," + simpleLocation.getZ(); - jsonArray.add(new JsonPrimitive(loc)); - } - jsonObject.add(entry.getKey(), jsonArray); - } - try (FileWriter fileWriter = new FileWriter(new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + world.getName() + File.separator + "customcrops_data" + File.separator + "scarecrow.json"))){ - fileWriter.write(jsonObject.toString().replace("\\\\", "\\")); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void loadSeason() { - if (!SeasonConfig.enable) return; - try { - JsonParser jsonParser = new JsonParser(); - JsonElement json= jsonParser.parse(new FileReader(new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + world.getName() + File.separator + "customcrops_data" + File.separator + "season.json"))); - if (json.isJsonObject()) { - JsonObject jsonObject = json.getAsJsonObject(); - if (jsonObject.has("season")) { - JsonPrimitive jsonPrimitive = jsonObject.getAsJsonPrimitive("season"); - String season = jsonPrimitive.getAsString(); - if (MainConfig.realisticSeasonHook) return; - SeasonUtils.setSeason(world, CCSeason.valueOf(season)); - } - } - else { - SeasonUtils.setSeason(world, CCSeason.UNKNOWN); - } - } - catch (FileNotFoundException ignore) { - } - } - - public void unloadSeason() { - if (!SeasonConfig.enable) return; - if (MainConfig.realisticSeasonHook) return; - JsonObject jsonObject = new JsonObject(); - JsonPrimitive jsonPrimitive = new JsonPrimitive(SeasonUtils.getSeason(world).name()); - jsonObject.add("season", jsonPrimitive); - try (FileWriter fileWriter = new FileWriter(new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + world.getName() + File.separator + "customcrops_data" + File.separator + "season.json"))){ - fileWriter.write(jsonObject.toString().replace("\\\\", "\\")); - } catch (IOException e) { - e.printStackTrace(); - } - SeasonUtils.unloadSeason(world); - } - - public void loadPot() { - try { - JsonParser jsonParser = new JsonParser(); - JsonElement json= jsonParser.parse(new FileReader(new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + world.getName() + File.separator + "customcrops_data" + File.separator + "pot.json"))); - if (json.isJsonObject()) { - JsonObject jsonObject = json.getAsJsonObject(); - if (jsonObject.has("pot")) { - JsonArray jsonArray = jsonObject.getAsJsonArray("pot"); - String name = world.getName(); - for (JsonElement jsonElement : jsonArray) { - String loc = jsonElement.getAsString(); - String[] locs = StringUtils.split(loc, ","); - watered.add(new SimpleLocation(name, Integer.parseInt(locs[0]), Integer.parseInt(locs[1]), Integer.parseInt(locs[2]))); - } - } - } - } - catch (FileNotFoundException ignore) { - } - } - - public void unloadPot() { - JsonObject jsonObject = new JsonObject(); - JsonArray jsonArray = new JsonArray(); - watered.addAll(playerWatered); - for (SimpleLocation simpleLocation : watered) { - jsonArray.add(simpleLocation.getX() + "," + simpleLocation.getY() + "," + simpleLocation.getZ()); - } - watered.clear(); - jsonObject.add("pot", jsonArray); - try (FileWriter fileWriter = new FileWriter(new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + world.getName() + File.separator + "customcrops_data" + File.separator + "pot.json"))){ - fileWriter.write(jsonObject.toString().replace("\\\\", "\\")); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void loadFertilizerCache() { - YamlConfiguration data = loadData("fertilizers", world.getName()); - for (String key : data.getKeys(false)) { - String[] loc = StringUtils.split(key, ","); - SimpleLocation location = new SimpleLocation(world.getName(), Integer.parseInt(loc[0]), Integer.parseInt(loc[1]), Integer.parseInt(loc[2])); - String fertilizer = data.getString(key + ".type"); - int times = data.getInt(key + ".times"); - Fertilizer fertilizerConfig = FertilizerConfig.FERTILIZERS.get(fertilizer); - if (fertilizerConfig != null) { - fertilizerCache.put(location, fertilizerConfig.getWithTimes(times)); - } - } - } - - public void unloadFertilizer() { - YamlConfiguration data = new YamlConfiguration(); - for (Map.Entry en : fertilizerCache.entrySet()) { - SimpleLocation location = en.getKey(); - String loc = location.getX() + "," + location.getY() + "," + location.getZ(); - data.set(loc + ".times", en.getValue().getTimes()); - data.set(loc + ".type", en.getValue().getKey()); - } - try { - data.save(new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + world.getName() + File.separator + "customcrops_data" + File.separator + "fertilizers.yml")); - } - catch (IOException e) { - e.printStackTrace(); - AdventureUtil.consoleMessage("[CustomCrops] Failed to save pot data for world " + world.getName() + ""); - } - } - - public void loadSprinklerCache() { - YamlConfiguration data = loadData("sprinklers", world.getName()); - for (String key : data.getKeys(false)) { - String[] loc = StringUtils.split(key, ","); - SimpleLocation location = new SimpleLocation(world.getName(), Integer.parseInt(loc[0]), Integer.parseInt(loc[1]), Integer.parseInt(loc[2])); - String sprinkler = data.getString(key + ".type"); - int water = data.getInt(key + ".water"); - Sprinkler sprinklerConfig = SprinklerConfig.SPRINKLERS_CONFIG.get(sprinkler + "CONFIG"); - if (sprinklerConfig != null) { - if (water > sprinklerConfig.getWater()) water = sprinklerConfig.getWater(); - Sprinkler sprinklerInstance = new Sprinkler(sprinklerConfig.getKey(), sprinklerConfig.getRange(), water); - sprinklerCache.put(location, sprinklerInstance); - } - } - } - - public void unloadSprinkler() { - YamlConfiguration data = new YamlConfiguration(); - for (Map.Entry en : sprinklerCache.entrySet()) { - SimpleLocation location = en.getKey(); - String loc = location.getX() + "," + location.getY() + "," + location.getZ(); - data.set(loc + ".water", en.getValue().getWater()); - data.set(loc + ".type", en.getValue().getKey()); - } - try { - data.save(new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + world.getName() + File.separator + "customcrops_data" + File.separator + "sprinklers.yml")); - } - catch (IOException e) { - e.printStackTrace(); - AdventureUtil.consoleMessage("[CustomCrops] Failed to save sprinkler data for world " + world.getName() + ""); - } - } - - public void loadCropCache() { - YamlConfiguration data = loadData("crops", world.getName()); - String worldName = world.getName(); - for (Map.Entry entry : data.getValues(false).entrySet()) { - String crop = (String) entry.getValue(); - GrowingCrop growingCrop; - if (crop.contains("_")) { - String stageStr = crop.substring(crop.indexOf("_stage_") + 7); - int stage = Integer.parseInt(stageStr); - growingCrop = new GrowingCrop(stage, crop.substring(0, crop.indexOf("_stage_"))); - } - else { - growingCrop = new GrowingCrop(1, crop); - } - cropData.put(MiscUtils.getSimpleLocation(entry.getKey(), worldName), growingCrop); - } - } - - public void unloadCrop() { - YamlConfiguration data = new YamlConfiguration(); - for (Map.Entry en : cropData.entrySet()) { - SimpleLocation location = en.getKey(); - String loc = location.getX() + "," + location.getY() + "," + location.getZ(); - data.set(loc, en.getValue().getType() + "_stage_" + en.getValue().getStage()); - } - try { - data.save(new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + world.getName() + File.separator + "customcrops_data" + File.separator + "crops.yml")); - } - catch (IOException e) { - e.printStackTrace(); - AdventureUtil.consoleMessage("[CustomCrops] Failed to save crop data for world " + world.getName() + ""); - } - } - - public void growWire(int cropTime, int sprinklerTime, int dryTime, boolean compensation, boolean force) { - if (cropData == null) return; - Random randomGenerator = ThreadLocalRandom.current(); - if (force) { - for (SimpleLocation location : cropData.keySet()) { - growSingleWire(location, randomGenerator.nextInt(cropTime)); - } - } - else if (!compensation) { - route(sprinklerTime); - - for (SimpleLocation location : cropData.keySet()) { - growSingleWire(location, sprinklerTime + dryTime + randomGenerator.nextInt(cropTime)); - } - - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.plugin, () -> { - potDryJudge(dryTime); - }, sprinklerTime); - } - else { - int delay = (int) (24000 - world.getTime()); - double chance = (double) (24000 - world.getTime()) / 24000; - for (SimpleLocation location : cropData.keySet()) { - if (Math.random() < chance) { - growSingleWire(location, randomGenerator.nextInt(delay)); - } - } - } - } - - private void growSingleWire(SimpleLocation simpleLocation, long delay) { - bukkitScheduler.runTaskLaterAsynchronously(CustomCrops.plugin, () -> { - Location location = MiscUtils.getLocation(simpleLocation); - GrowingCrop growingCrop = cropData.get(simpleLocation); - if (growingCrop == null) return; - if (cropManager.wireGrowJudge(location, growingCrop)) { - cropData.remove(simpleLocation); - } - }, delay); - } - - public void growFrame(int cropTime, int sprinklerTime, int dryTime, boolean compensation, boolean force) { - if (cropData == null) return; - Random randomGenerator = ThreadLocalRandom.current(); - if (force) { - for (SimpleLocation location : cropData.keySet()) { - growSingleFrame(location, randomGenerator.nextInt(cropTime)); - } - } - else if (!compensation) { - route(sprinklerTime); - for (SimpleLocation location : cropData.keySet()) { - growSingleFrame(location, sprinklerTime + dryTime + randomGenerator.nextInt(cropTime)); - } - Bukkit.getScheduler().runTaskLaterAsynchronously(CustomCrops.plugin, () -> { - potDryJudge(dryTime); - }, sprinklerTime); - } - else { - int delay = (int) (24000 - world.getTime()); - double chance = (double) (24000 - world.getTime()) / 24000; - for (SimpleLocation location : cropData.keySet()) { - if (Math.random() < chance) { - growSingleFrame(location, randomGenerator.nextInt(delay)); - } - } - } - } - - private void growSingleFrame(SimpleLocation simpleLocation, long delay) { - bukkitScheduler.runTaskLater(CustomCrops.plugin, () -> { - Location location = MiscUtils.getLocation(simpleLocation); - if (location == null) return; - GrowingCrop growingCrop = cropData.get(simpleLocation); - if (growingCrop == null) return; - location.getChunk().load(); - bukkitScheduler.runTaskLater(CustomCrops.plugin, () -> { - if (cropManager.itemFrameGrowJudge(location, growingCrop)) { - cropData.remove(simpleLocation); - } - }, 5); - }, delay); - } - - private void route(int sprinklerTime) { - //先将湿润的种植盆放入等待判断的种植盆列表中 - tempWatered = new HashSet<>(watered); - //清空湿润的 - watered.clear(); - //玩家浇水 - watered.addAll(playerWatered); - //清除昨日玩家浇水 - playerWatered.clear(); - //清除玩家昨日种植 - plantedToday.clear();; - - //洒水器工作会把种植盆放入watered中 - Random randomGenerator = ThreadLocalRandom.current(); - for (Map.Entry sprinklerEntry : sprinklerCache.entrySet()) { - bukkitScheduler.runTaskLaterAsynchronously(CustomCrops.plugin, () -> sprinklerWork(sprinklerEntry.getKey(), sprinklerEntry.getValue()), randomGenerator.nextInt(sprinklerTime)); - } - - for (Map.Entry fertilizerEntry : fertilizerCache.entrySet()) { - Fertilizer fertilizer = fertilizerEntry.getValue(); - if (fertilizer.getTimes() > 1) fertilizer.setTimes(fertilizer.getTimes() - 1); - else fertilizerCache.remove(fertilizerEntry.getKey()); - } - } - - public YamlConfiguration loadData(String data, String worldName) { - return ConfigUtil.readData(new File(CustomCrops.plugin.getDataFolder().getParentFile().getParentFile(), MainConfig.worldFolder + worldName + File.separator + "customcrops_data" + File.separator + data +".yml")); - } - - public void sprinklerWork(SimpleLocation location, Sprinkler sprinkler) { - if (sprinkler.getWater() < 1) { - sprinklerCache.remove(location); - return; - } - Location sprinklerLoc = MiscUtils.getLocation(location); - if (sprinklerLoc == null) return; - if (MainConfig.enableAnimations) { - new BukkitRunnable() { - @Override - public void run() { - for (Player player : sprinklerLoc.getNearbyPlayers(48)) { - cropManager.getArmorStandUtil().playWaterAnimation(player, sprinklerLoc.clone().add(0.5, MainConfig.animationYOffset, 0.5)); - } - } - }.runTask(CustomCrops.plugin); - } - sprinkler.setWater(sprinkler.getWater() - 1); - int range = sprinkler.getRange(); - for(int i = -range; i <= range; i++){ - for (int j = -range; j <= range; j++){ - Location wetLoc = sprinklerLoc.clone().add(i,-1,j); - cropManager.makePotWet(wetLoc); - setPotWet(wetLoc); - } - } - } - - private void potDryJudge(int dry_time) { - //将待干的种植盆中今日被浇水的种植盆移除 - //剩余的种植盆即为需要变干的 - tempWatered.removeAll(watered); - for (SimpleLocation simpleLocation : tempWatered) { - new BukkitRunnable() { - @Override - public void run() { - Location potLoc = MiscUtils.getLocation(simpleLocation); - if (potLoc == null) return; - Fertilizer fertilizer = getFertilizerCache(potLoc); - if (!(fertilizer instanceof RetainingSoil retainingSoil && Math.random() < retainingSoil.getChance())) { - cropManager.makePotDry(potLoc); - } - } - }.runTaskLaterAsynchronously(CustomCrops.plugin, ThreadLocalRandom.current().nextInt(dry_time)); - } - //用完就抛弃 - tempWatered.clear(); - } - - /** - * - * 肥料缓存 - * - */ - @Nullable - public Fertilizer getFertilizerCache(Location potLoc) { - return fertilizerCache.get(MiscUtils.getSimpleLocation(potLoc)); - } - public void removeFertilizerCache(Location potLoc) { - fertilizerCache.remove(MiscUtils.getSimpleLocation(potLoc)); - } - public void addFertilizerCache(Location potLoc, Fertilizer fertilizer) { - fertilizerCache.put(MiscUtils.getSimpleLocation(potLoc), fertilizer); - } - - - /** - * - * 农作物缓存 - * - */ - public void removeCropCache(Location cropLoc) { - cropData.remove(MiscUtils.getSimpleLocation(cropLoc)); - } - public void addCropCache(Location cropLoc, String crop, int stage) { - SimpleLocation simpleLocation = MiscUtils.getSimpleLocation(cropLoc); - GrowingCrop growingCrop = new GrowingCrop(stage, crop); - cropData.put(simpleLocation, growingCrop); - if (MainConfig.autoGrow && !plantedToday.contains(simpleLocation) && world.getTime() > 1000) { - int delay = (int) (24000 - world.getTime()); - double chance = (double) (24000 - world.getTime()) / 24000; - plantedToday.add(simpleLocation); - if (Math.random() > chance) return; - if (MainConfig.cropMode) growSingleWire(simpleLocation, ThreadLocalRandom.current().nextInt(delay)); - else growSingleFrame(simpleLocation, ThreadLocalRandom.current().nextInt(delay)); - } - } - @Nullable - public GrowingCrop getCropCache(Location cropLoc) { - return cropData.get(MiscUtils.getSimpleLocation(cropLoc)); - } - - - /** - * - * 洒水器缓存 - * - */ - @Nullable - public Sprinkler getSprinklerCache(Location location) { - return sprinklerCache.get(MiscUtils.getSimpleLocation(location)); - } - public void removeSprinklerCache(Location location) { - sprinklerCache.remove(MiscUtils.getSimpleLocation(location)); - } - public void addSprinklerCache(Location location, Sprinkler sprinkler) { - sprinklerCache.put(MiscUtils.getSimpleLocation(location), sprinkler); - } - - - /** - * - * 种植盆状态缓存 - * - */ - public void setPotWet(Location potLoc) { - watered.add(MiscUtils.getSimpleLocation(potLoc)); - } - public boolean isPotWet(Location potLoc) { - return watered.contains(MiscUtils.getSimpleLocation(potLoc)); - } - public void removePotFromWatered(Location potLoc) { - watered.remove(MiscUtils.getSimpleLocation(potLoc)); - } - public void setPlayerWatered(Location potLoc) { - setPotWet(potLoc); - playerWatered.add(MiscUtils.getSimpleLocation(potLoc)); - } - - - /** - * - * 稻草人缓存 - * - */ - public boolean hasScarecrowCache(Location location) { - Chunk chunk = location.getChunk(); - return scarecrowCache.containsKey(chunk.getX() + "," + chunk.getZ()); - } - public void addScarecrowCache(Location location) { - Chunk chunk = location.getChunk(); - HashSet old = scarecrowCache.get(chunk.getX() + "," + chunk.getZ()); - if (old == null) { - HashSet young = new HashSet<>(4); - young.add(new SimpleLocation(world.getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ())); - scarecrowCache.put(chunk.getX() + "," + chunk.getZ(), young); - } - else { - old.add(new SimpleLocation(world.getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ())); - } - } - public void removeScarecrowCache(Location location) { - Chunk chunk = location.getChunk(); - HashSet old = scarecrowCache.get(chunk.getX() + "," + chunk.getZ()); - if (old == null) return; - old.remove(new SimpleLocation(world.getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ())); - if (old.size() == 0) scarecrowCache.remove(chunk.getX() + "," + chunk.getZ()); - } -} diff --git a/src/main/java/net/momirealms/customcrops/managers/listener/ContainerListener.java b/src/main/java/net/momirealms/customcrops/managers/listener/ContainerListener.java deleted file mode 100644 index 1b197c8..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/listener/ContainerListener.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.momirealms.customcrops.managers.listener; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.ListenerPriority; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTItem; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.config.WaterCanConfig; -import net.momirealms.customcrops.managers.CropManager; -import net.momirealms.customcrops.objects.WaterCan; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.List; - -public class ContainerListener extends PacketAdapter { - - private final CropManager cropManager; - - public ContainerListener(CropManager cropManager) { - super(CustomCrops.plugin, ListenerPriority.HIGHEST, PacketType.Play.Server.WINDOW_ITEMS); - this.cropManager = cropManager; - } - - public void onPacketSending(PacketEvent event) { - PacketContainer packet = event.getPacket(); - if (event.getPlayer().getGameMode() == GameMode.CREATIVE) { - return; - } - List itemStacks = packet.getItemListModifier().read(0); - List itemStacksClone = new ArrayList<>(); - for (ItemStack itemStack : itemStacks) { - ItemStack fake = itemStack.clone(); - itemStacksClone.add(fake); - if (fake.getType() == Material.AIR) continue; - String id = cropManager.getCustomInterface().getItemID(fake); - WaterCan config = WaterCanConfig.CANS.get(id); - if (config == null) continue; - NBTItem nbtItem = new NBTItem(fake); - int water = nbtItem.getInteger("WaterAmount"); - NBTCompound display = nbtItem.getCompound("display"); - if (display == null) continue; - List lore = display.getStringList("Lore"); - if (MainConfig.topOrBottom) lore.addAll(0, getLore(config.getMax(), water)); - else lore.addAll(getLore(config.getMax(), water)); - fake.setItemMeta(nbtItem.getItem().getItemMeta()); - } - packet.getItemListModifier().write(0, itemStacksClone); - } - - private List getLore(int max, int water) { - List lore = new ArrayList<>(); - for (String text : MainConfig.waterCanLore) { - lore.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize( - text.replace("{water_bar}", - MainConfig.waterBarLeft + - MainConfig.waterBarFull.repeat(water) + - MainConfig.waterBarEmpty.repeat(max - water) + - MainConfig.waterBarRight - ) - .replace("{water}", String.valueOf(water)) - .replace("{max_water}", String.valueOf(max)) - ))); - } - return lore; - } -} diff --git a/src/main/java/net/momirealms/customcrops/managers/listener/InteractListener.java b/src/main/java/net/momirealms/customcrops/managers/listener/InteractListener.java deleted file mode 100644 index 6bc230a..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/listener/InteractListener.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.managers.listener; - -import net.momirealms.customcrops.integrations.customplugin.HandlerP; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerQuitEvent; - -public class InteractListener implements Listener { - - private final HandlerP handlerP; - - public InteractListener(HandlerP handlerP) { - this.handlerP = handlerP; - } - - @EventHandler - public void onPlayerInteract(PlayerInteractEvent event) { - handlerP.onPlayerInteract(event); - } - - @EventHandler - public void onQuit(PlayerQuitEvent event) { - handlerP.onQuit(event.getPlayer()); - } -} diff --git a/src/main/java/net/momirealms/customcrops/managers/listener/ItemSpawnListener.java b/src/main/java/net/momirealms/customcrops/managers/listener/ItemSpawnListener.java deleted file mode 100644 index fa578e6..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/listener/ItemSpawnListener.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.managers.listener; - -import net.momirealms.customcrops.managers.CropManager; -import org.bukkit.entity.Item; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntitySpawnEvent; - -public class ItemSpawnListener implements Listener { - - private final CropManager cropManager; - - public ItemSpawnListener(CropManager cropManager) { - this.cropManager = cropManager; - } - - @EventHandler - public void onItemSpawn(EntitySpawnEvent event) { - if (event.isCancelled()) return; - if (event.getEntity() instanceof Item item) { - cropManager.onItemSpawn(item); - } - } -} diff --git a/src/main/java/net/momirealms/customcrops/managers/listener/PlayerModeListener.java b/src/main/java/net/momirealms/customcrops/managers/listener/PlayerModeListener.java deleted file mode 100644 index c9bc4ef..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/listener/PlayerModeListener.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.momirealms.customcrops.managers.listener; - -import net.momirealms.customcrops.CustomCrops; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerGameModeChangeEvent; - -public class PlayerModeListener implements Listener { - - @EventHandler - public void onModeChange(PlayerGameModeChangeEvent event) { - if (event.isCancelled()) return; - Bukkit.getScheduler().runTaskLater(CustomCrops.plugin, () -> { - event.getPlayer().updateInventory(); - }, 1); - } -} diff --git a/src/main/java/net/momirealms/customcrops/managers/listener/VanillaCropHarvestListener.java b/src/main/java/net/momirealms/customcrops/managers/listener/VanillaCropHarvestListener.java deleted file mode 100644 index daeead0..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/listener/VanillaCropHarvestListener.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.momirealms.customcrops.managers.listener; - -import net.momirealms.customcrops.config.MainConfig; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.data.Ageable; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.PlayerInventory; - -public class VanillaCropHarvestListener implements Listener { - - @EventHandler - public void onInteractRipeCrop(PlayerInteractEvent event) { - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - Block block = event.getClickedBlock(); - if (block == null) return; - Material material = block.getType(); - if (material == Material.COCOA) return; - if (block.getBlockData() instanceof Ageable ageable) { - if (ageable.getMaximumAge() == ageable.getAge()) { - final Player player = event.getPlayer(); - if (MainConfig.emptyHand) { - final PlayerInventory inventory = player.getInventory(); - if (!(inventory.getItemInMainHand().getType() != Material.AIR || inventory.getItemInOffHand().getType() != Material.AIR)) { - if (player.breakBlock(block)) { - block.setType(material); - } - } - } - else if (player.breakBlock(block)) { - block.setType(material); - } - } - } - } -} diff --git a/src/main/java/net/momirealms/customcrops/managers/listener/VanillaCropPlaceListener.java b/src/main/java/net/momirealms/customcrops/managers/listener/VanillaCropPlaceListener.java deleted file mode 100644 index 0a5eed8..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/listener/VanillaCropPlaceListener.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.momirealms.customcrops.managers.listener; - -import net.momirealms.customcrops.config.MainConfig; -import org.bukkit.Material; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockPlaceEvent; - -public class VanillaCropPlaceListener implements Listener { - - @EventHandler - public void onPlant(BlockPlaceEvent event) { - if (event.isCancelled()) return; - Material type = event.getBlockPlaced().getType(); - for (Material vanillaCrop : MainConfig.preventPlantVanillaArray) { - if (type == vanillaCrop) { - event.setCancelled(true); - return; - } - } - } -} diff --git a/src/main/java/net/momirealms/customcrops/managers/listener/WorldListener.java b/src/main/java/net/momirealms/customcrops/managers/listener/WorldListener.java deleted file mode 100644 index aaa30aa..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/listener/WorldListener.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.managers.listener; - -import net.momirealms.customcrops.managers.CropManager; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.world.WorldLoadEvent; -import org.bukkit.event.world.WorldUnloadEvent; - -public record WorldListener(CropManager cropManager) implements Listener { - - @EventHandler - public void onWorldLoad(WorldLoadEvent event) { - cropManager.onWorldLoad(event.getWorld()); - } - - @EventHandler - public void onWorldUnload(WorldUnloadEvent event) { - cropManager.onWorldUnload(event.getWorld(), false); - } -} diff --git a/src/main/java/net/momirealms/customcrops/managers/timer/TimerTask.java b/src/main/java/net/momirealms/customcrops/managers/timer/TimerTask.java deleted file mode 100644 index 7e79722..0000000 --- a/src/main/java/net/momirealms/customcrops/managers/timer/TimerTask.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.managers.timer; - -import net.momirealms.customcrops.config.MainConfig; -import net.momirealms.customcrops.managers.CropManager; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.scheduler.BukkitRunnable; - -public class TimerTask extends BukkitRunnable { - - private final CropManager cropManager; - - public TimerTask(CropManager cropManager) { - this.cropManager = cropManager; - } - - @Override - public void run() { - if (!MainConfig.autoGrow) return; - for (String worldName : MainConfig.getWorldNameList()) { - World world = Bukkit.getWorld(worldName); - if (world != null) { - long time = world.getTime(); - if (time > 900 && time < 1001) { - cropManager.grow(world, MainConfig.timeToGrow, MainConfig.timeToWork, MainConfig.timeToDry, false, false); - } - if (time > 0 && time < 101) { - cropManager.saveData(world); - } - } - } - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/CCCrop.java b/src/main/java/net/momirealms/customcrops/objects/CCCrop.java deleted file mode 100644 index 15f85f2..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/CCCrop.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects; - -import net.momirealms.customcrops.api.crop.Crop; -import net.momirealms.customcrops.api.utils.CCSeason; -import net.momirealms.customcrops.objects.actions.ActionInterface; -import net.momirealms.customcrops.objects.requirements.RequirementInterface; - -public class CCCrop implements Crop { - - private CCSeason[] seasons; - private RequirementInterface[] plantRequirements; - private RequirementInterface[] harvestRequirements; - private String returnStage; - private QualityLoot qualityLoot; - private GiganticCrop giganticCrop; - private OtherLoot[] otherLoots; - private ActionInterface[] actions; - private final String key; - private boolean rotation; - private final int max_stage; - - public CCCrop(String key, int max_stage) { - this.key = key; - this.max_stage = max_stage; - } - - public QualityLoot getQualityLoot() { - return qualityLoot; - } - - public void setQualityLoot(QualityLoot qualityLoot) { - this.qualityLoot = qualityLoot; - } - - public String getKey() { - return key; - } - - public CCSeason[] getSeasons() { - return seasons; - } - - public RequirementInterface[] getPlantRequirements() { - return plantRequirements; - } - - public String getReturnStage() { - return returnStage; - } - - public GiganticCrop getGiganticCrop() { - return giganticCrop; - } - - public OtherLoot[] getOtherLoots() { - return otherLoots; - } - - public ActionInterface[] getActions() { - return actions; - } - - public void setSeasons(CCSeason[] seasons) { - this.seasons = seasons; - } - - public void setPlantRequirements(RequirementInterface[] requirementInterfaces) { - this.plantRequirements = requirementInterfaces; - } - - public void setReturnStage(String returnStage) { - this.returnStage = returnStage; - } - - public void setGiganticCrop(GiganticCrop giganticCrop) { - this.giganticCrop = giganticCrop; - } - - public void setOtherLoots(OtherLoot[] otherLoots) { - this.otherLoots = otherLoots; - } - - public void setActions(ActionInterface[] actions) { - this.actions = actions; - } - - public boolean canRotate() { - return rotation; - } - - public void setCanRotate(boolean rotation) { - this.rotation = rotation; - } - - public int getMax_stage() { - return max_stage; - } - - public RequirementInterface[] getHarvestRequirements() { - return harvestRequirements; - } - - public void setHarvestRequirements(RequirementInterface[] harvestRequirements) { - this.harvestRequirements = harvestRequirements; - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/GiganticCrop.java b/src/main/java/net/momirealms/customcrops/objects/GiganticCrop.java deleted file mode 100644 index aae4cc2..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/GiganticCrop.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects; - -public class GiganticCrop { - - private final double chance; - private final boolean isBlock; - private final String blockID; - - public GiganticCrop(double chance, boolean isBlock, String blockID) { - this.chance = chance; - this.isBlock = isBlock; - this.blockID = blockID; - } - - public double getChance() { - return chance; - } - - public boolean isBlock() { - return isBlock; - } - - public String getBlockID() { - return blockID; - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/GrowingCrop.java b/src/main/java/net/momirealms/customcrops/objects/GrowingCrop.java deleted file mode 100644 index 2f50f24..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/GrowingCrop.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.momirealms.customcrops.objects; - -public class GrowingCrop { - - private int stage; - - private final String type; - - public GrowingCrop(int stage, String type) { - this.stage = stage; - this.type = type; - } - - public int getStage() { - return stage; - } - - public String getType() { - return type; - } - - public void setStage(int stage) { - this.stage = stage; - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/OtherLoot.java b/src/main/java/net/momirealms/customcrops/objects/OtherLoot.java deleted file mode 100644 index 9fcfbbb..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/OtherLoot.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects; - -public class OtherLoot { - - private final int min; - private final int max; - private final String itemID; - private final double chance; - - public OtherLoot(int min, int max, String itemID, double chance) { - this.min = min; - this.max = max; - this.itemID = itemID; - this.chance = chance; - } - - public int getMin() { - return min; - } - - public int getMax() { - return max; - } - - public String getItemID() { - return itemID; - } - - public double getChance() { - return chance; - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/objects/QualityLoot.java b/src/main/java/net/momirealms/customcrops/objects/QualityLoot.java deleted file mode 100644 index c6dcce1..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/QualityLoot.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects; - -public class QualityLoot { - - private final int min; - private final int max; - - private final String quality_1; - private final String quality_2; - private final String quality_3; - - public QualityLoot(int min, int max, String quality_1, String quality_2, String quality_3) { - this.quality_1 = quality_1; - this.quality_2 = quality_2; - this.quality_3 = quality_3; - this.max = max; - this.min = min; - } - - public String getQuality_1() { - return quality_1; - } - - public String getQuality_2() { - return quality_2; - } - - public String getQuality_3() { - return quality_3; - } - - public int getMin() { - return min; - } - - public int getMax() { - return max; - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/Sprinkler.java b/src/main/java/net/momirealms/customcrops/objects/Sprinkler.java deleted file mode 100644 index ffec5f2..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/Sprinkler.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects; - -import org.jetbrains.annotations.Nullable; - -public class Sprinkler { - - private int range; - private int water; - private final String key; - private String twoD; - private String threeD; - - public Sprinkler(String key, int range, int water) { - this.range = range; - this.water = water; - this.key = key; - } - - public int getRange() { - return range; - } - - public void setRange(int range) { - this.range = range; - } - - public int getWater() { - return water; - } - - public void setWater(int water) { - this.water = water; - } - - public String getKey() { - return key; - } - - @Nullable - public String getTwoD() { - return twoD; - } - - public void setTwoD(String twoD) { - this.twoD = twoD; - } - - @Nullable - public String getThreeD() { - return threeD; - } - - public void setThreeD(String threeD) { - this.threeD = threeD; - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/WaterCan.java b/src/main/java/net/momirealms/customcrops/objects/WaterCan.java deleted file mode 100644 index f84bd55..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/WaterCan.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects; - -public record WaterCan(int max, int width, int length) { - - public int getMax() { - return max; - } - - public int getLength() { - return length; - } - - public int getWidth() { - return width; - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/objects/actions/ActionJobXP.java b/src/main/java/net/momirealms/customcrops/objects/actions/ActionJobXP.java deleted file mode 100644 index 8daceaf..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/actions/ActionJobXP.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.momirealms.customcrops.objects.actions; - -import net.momirealms.customcrops.config.MainConfig; -import org.bukkit.entity.Player; - -public class ActionJobXP implements ActionInterface { - - private final double xp; - private final double chance; - - public ActionJobXP(double xp, double chance) { - this.xp = xp; - this.chance = chance; - } - - @Override - public void performOn(Player player) { - if (MainConfig.jobInterface != null) { - MainConfig.jobInterface.addXp(player, xp); - } - } - - @Override - public double getChance() { - return chance; - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/actions/ActionMessage.java b/src/main/java/net/momirealms/customcrops/objects/actions/ActionMessage.java deleted file mode 100644 index a26e56b..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/actions/ActionMessage.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.actions; - -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.entity.Player; - -public class ActionMessage implements ActionInterface{ - - private final String[] messages; - private final double chance; - - public ActionMessage(String[] messages, double chance) { - this.messages = messages; - this.chance = chance; - } - - @Override - public void performOn(Player player) { - for (String message : messages) { - AdventureUtil.playerMessage(player, message.replace("{player}", player.getName())); - } - } - - @Override - public double getChance() { - return chance; - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/fertilizer/Fertilizer.java b/src/main/java/net/momirealms/customcrops/objects/fertilizer/Fertilizer.java deleted file mode 100644 index bb4df38..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/fertilizer/Fertilizer.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.fertilizer; - -import org.bukkit.Particle; - -public abstract class Fertilizer { - - String key; - int times; - boolean before; - String name; - Particle particle; - double chance; - - protected Fertilizer(String key, int times, double chance, boolean before, String name) { - this.key = key; - this.times = times; - this.chance = chance; - this.before = before; - this.name = name; - } - - public String getKey() { - return key; - } - - public int getTimes() { - return times; - } - - public void setTimes(int times) { - this.times = times; - } - - public boolean isBefore() { - return before; - } - - public String getName() { - return name; - } - - public Particle getParticle() { - return particle; - } - - public void setParticle(Particle particle) { - this.particle = particle; - } - - public Fertilizer getWithTimes(int times) { - return null; - } - - public double getChance() { - return chance; - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/fertilizer/QualityCrop.java b/src/main/java/net/momirealms/customcrops/objects/fertilizer/QualityCrop.java deleted file mode 100644 index f6273f4..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/fertilizer/QualityCrop.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.fertilizer; - - -import net.momirealms.customcrops.objects.QualityRatio; - -public class QualityCrop extends Fertilizer { - - private final QualityRatio qualityRatio; - - public QualityCrop(String key, int times, double chance, QualityRatio qualityRatio, boolean before, String name) { - super(key, times, chance, before, name); - this.qualityRatio = qualityRatio; - } - - public QualityRatio getQualityRatio() { - return qualityRatio; - } - - @Override - public Fertilizer getWithTimes(int times) { - return new QualityCrop(this.key, times, this.chance, this.qualityRatio, this.before, this.name); - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/fertilizer/RetainingSoil.java b/src/main/java/net/momirealms/customcrops/objects/fertilizer/RetainingSoil.java deleted file mode 100644 index 65bb1e9..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/fertilizer/RetainingSoil.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.fertilizer; - -public class RetainingSoil extends Fertilizer { - - public RetainingSoil(String key, int times, double chance, boolean before, String name){ - super(key, times, chance, before, name); - } - - @Override - public Fertilizer getWithTimes(int times) { - return new RetainingSoil(this.key, times, this.chance, this.before, this.name); - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/fertilizer/SpeedGrow.java b/src/main/java/net/momirealms/customcrops/objects/fertilizer/SpeedGrow.java deleted file mode 100644 index 53736f7..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/fertilizer/SpeedGrow.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.fertilizer; - -public class SpeedGrow extends Fertilizer { - - public SpeedGrow(String key, int times, double chance, boolean before, String name){ - super(key, times, chance, before, name); - } - - @Override - public Fertilizer getWithTimes(int times) { - return new SpeedGrow(this.key, times, this.chance, this.before, this.name); - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/fertilizer/YieldIncreasing.java b/src/main/java/net/momirealms/customcrops/objects/fertilizer/YieldIncreasing.java deleted file mode 100644 index 015c74b..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/fertilizer/YieldIncreasing.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.fertilizer; - -public class YieldIncreasing extends Fertilizer { - - private final int bonus; - - public YieldIncreasing(String key, int times, double chance ,int bonus, boolean before, String name) { - super(key, times, chance, before, name); - this.bonus = bonus; - } - - public int getBonus() { - return bonus; - } - - @Override - public Fertilizer getWithTimes(int times) { - return new YieldIncreasing(this.key, times, this.chance, this.bonus, this.before, this.name); - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/CustomPapi.java b/src/main/java/net/momirealms/customcrops/objects/requirements/CustomPapi.java deleted file mode 100644 index 4386ddc..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/CustomPapi.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.requirements; - -import net.momirealms.customcrops.objects.requirements.papi.*; -import net.momirealms.customcrops.utils.AdventureUtil; -import org.bukkit.configuration.MemorySection; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -public class CustomPapi implements RequirementInterface { - - public static HashSet allPapi = new HashSet<>(); - - private PapiRequirement papiRequirement; - private final String msg; - - public CustomPapi(Map expressions, String msg){ - this.msg = msg; - expressions.keySet().forEach(key -> { - if (key.startsWith("&&")){ - List papiRequirements = new ArrayList<>(); - if (expressions.get(key) instanceof MemorySection map2){ - addAndRequirements(papiRequirements, map2.getValues(false)); - } - papiRequirement = new ExpressionAnd(papiRequirements); - } - else if (key.startsWith("||")){ - List papiRequirements = new ArrayList<>(); - if (expressions.get(key) instanceof MemorySection map2){ - addOrRequirements(papiRequirements, map2.getValues(false)); - } - papiRequirement = new ExpressionOr(papiRequirements); - } - else { - if (expressions.get(key) instanceof MemorySection map){ - String type = map.getString("type"); - if (type == null) return; - String papi = map.getString("papi"); - if (papi == null) return; - String value = map.getString("value"); - if (value == null) return; - allPapi.add(papi); - switch (type){ - case "==" -> papiRequirement = new PapiEquals(papi, value); - case "!=" -> papiRequirement = new PapiNotEquals(papi, value); - case ">=" -> papiRequirement = new PapiNoLess(papi, value); - case "<=" -> papiRequirement = new PapiNoLarger(papi, value); - case "<" -> papiRequirement = new PapiSmaller(papi, value); - case ">" -> papiRequirement = new PapiGreater(papi, value); - } - } - } - }); - } - - @Override - public boolean isConditionMet(PlayerCondition playerCondition) { - if (!papiRequirement.isMet(playerCondition.getPapiMap(), playerCondition.getPlayer())) { - if (msg != null) AdventureUtil.playerMessage(playerCondition.getPlayer(), msg); - return false; - } - return true; - } - - private void addAndRequirements(List requirements, Map map){ - requirements.add(new ExpressionAnd(getRequirements(map))); - } - - private void addOrRequirements(List requirements, Map map){ - requirements.add(new ExpressionOr(getRequirements(map))); - } - - private List getRequirements(Map map) { - List papiRequirements = new ArrayList<>(); - map.keySet().forEach(key -> { - if (key.startsWith("&&")){ - if (map.get(key) instanceof MemorySection map2){ - addAndRequirements(papiRequirements, map2.getValues(false)); - } - }else if (key.startsWith("||")){ - if (map.get(key) instanceof MemorySection map2){ - addOrRequirements(papiRequirements, map2.getValues(false)); - } - }else { - if (map.get(key) instanceof MemorySection map2){ - String type = map2.getString("type"); - if (type == null) return; - String papi = map2.getString("papi"); - if (papi == null) return; - String value = map2.getString("value"); - if (value == null) return; - allPapi.add(papi); - switch (type){ - case "==" -> papiRequirements.add(new PapiEquals(papi, value)); - case "!=" -> papiRequirements.add(new PapiNotEquals(papi, value)); - case ">=" -> papiRequirements.add(new PapiNoLess(papi, value)); - case "<=" -> papiRequirements.add(new PapiNoLarger(papi, value)); - case "<" -> papiRequirements.add(new PapiSmaller(papi, value)); - case ">" -> papiRequirements.add(new PapiGreater(papi, value)); - } - } - } - }); - return papiRequirements; - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/PlayerCondition.java b/src/main/java/net/momirealms/customcrops/objects/requirements/PlayerCondition.java deleted file mode 100644 index 74ed6a4..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/PlayerCondition.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.requirements; - -import net.momirealms.customcrops.CustomCrops; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; - -public class PlayerCondition { - - private final Location location; - private final Player player; - private HashMap papiMap; - - public PlayerCondition(Location location, Player player) { - this.location = location; - this.player = player; - if (CustomCrops.plugin.hasPapi()){ - this.papiMap = new HashMap<>(); - CustomPapi.allPapi.forEach(papi -> this.papiMap.put(papi, CustomCrops.plugin.getPlaceholderManager().parse(player, papi))); - } - } - - @Nullable - public HashMap getPapiMap() { - return papiMap; - } - - @NotNull - public Location getLocation() { - return location; - } - - @NotNull - public Player getPlayer() { - return player; - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementBiome.java b/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementBiome.java deleted file mode 100644 index 1131b22..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementBiome.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.requirements; - -import net.momirealms.biomeapi.BiomeAPI; - -public class RequirementBiome extends Requirement implements RequirementInterface { - - public RequirementBiome(String[] values, boolean mode, String msg) { - super(values, mode, msg); - } - - @Override - public boolean isConditionMet(PlayerCondition playerCondition) { - String currentBiome = BiomeAPI.getBiome(playerCondition.getLocation()); - if (mode) { - for (String value : values) { - if (!(currentBiome.equalsIgnoreCase(value))) { - notMetMessage(playerCondition.getPlayer()); - return false; - } - } - return true; - } - else { - for (String value : values) { - if (currentBiome.equalsIgnoreCase(value)) { - return true; - } - } - notMetMessage(playerCondition.getPlayer()); - return false; - } - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementInterface.java b/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementInterface.java deleted file mode 100644 index 4783f8d..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementInterface.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.requirements; - -public interface RequirementInterface { - boolean isConditionMet(PlayerCondition playerCondition); -} diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementPermission.java b/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementPermission.java deleted file mode 100644 index e8df939..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementPermission.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.requirements; - -public class RequirementPermission extends Requirement implements RequirementInterface { - - public RequirementPermission(String[] values, boolean mode, String msg) { - super(values, mode, msg); - } - - @Override - public boolean isConditionMet(PlayerCondition playerCondition) { - if (mode) { - for (String value : values) { - if (!(playerCondition.getPlayer().hasPermission(value))) { - notMetMessage(playerCondition.getPlayer()); - return false; - } - } - return true; - } - else { - for (String value : values) { - if (playerCondition.getPlayer().hasPermission(value)) { - return true; - } - } - notMetMessage(playerCondition.getPlayer()); - return false; - } - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementTime.java b/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementTime.java deleted file mode 100644 index 050c87e..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementTime.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.requirements; - -import org.apache.commons.lang.StringUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class RequirementTime extends Requirement implements RequirementInterface { - - public RequirementTime(@NotNull String[] values, boolean mode, @Nullable String msg) { - super(values, mode, msg); - } - - @Override - public boolean isConditionMet(PlayerCondition playerCondition) { - long time = playerCondition.getLocation().getWorld().getTime(); - if (mode) { - for (String value : values) { - String[] timeMinMax = StringUtils.split(value, "~"); - if (!(time > Long.parseLong(timeMinMax[0]) && time < Long.parseLong(timeMinMax[1]))) { - notMetMessage(playerCondition.getPlayer()); - return false; - } - } - return true; - } - else { - for (String value : values) { - String[] timeMinMax = StringUtils.split(value, "~"); - if (time > Long.parseLong(timeMinMax[0]) && time < Long.parseLong(timeMinMax[1])) { - return true; - } - } - notMetMessage(playerCondition.getPlayer()); - return false; - } - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementWeather.java b/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementWeather.java deleted file mode 100644 index 434a2d9..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementWeather.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.requirements; - -import org.bukkit.World; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class RequirementWeather extends Requirement implements RequirementInterface { - - public RequirementWeather(@NotNull String[] values, boolean mode, @Nullable String msg) { - super(values, mode, msg); - } - - @Override - public boolean isConditionMet(PlayerCondition playerCondition) { - World world = playerCondition.getLocation().getWorld(); - String weather; - if (world.isThundering()) weather = "thunder"; - else if (world.isClearWeather()) weather = "clear"; - else weather = "rain"; - if (mode) { - for (String value : values) { - if (!value.equalsIgnoreCase(weather)) { - notMetMessage(playerCondition.getPlayer()); - return false; - } - } - return true; - } - else { - for (String value : values) { - if (value.equalsIgnoreCase(weather)) { - return true; - } - } - notMetMessage(playerCondition.getPlayer()); - return false; - } - } -} diff --git a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementYPos.java b/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementYPos.java deleted file mode 100644 index 09417df..0000000 --- a/src/main/java/net/momirealms/customcrops/objects/requirements/RequirementYPos.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.objects.requirements; - -import org.apache.commons.lang.StringUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class RequirementYPos extends Requirement implements RequirementInterface { - - public RequirementYPos(@NotNull String[] values, boolean mode, @Nullable String msg) { - super(values, mode, msg); - } - - @Override - public boolean isConditionMet(PlayerCondition playerCondition) { - int y = playerCondition.getLocation().getBlockY(); - if (mode) { - for (String value : values) { - String[] yMinMax = StringUtils.split(value, "~"); - if (!(y > Long.parseLong(yMinMax[0]) && y < Long.parseLong(yMinMax[1]))) { - notMetMessage(playerCondition.getPlayer()); - return false; - } - } - return true; - } - else { - for (String value : values) { - String[] yMinMax = StringUtils.split(value, "~"); - if (y > Long.parseLong(yMinMax[0]) && y < Long.parseLong(yMinMax[1])) { - return true; - } - } - notMetMessage(playerCondition.getPlayer()); - return false; - } - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/utils/AdventureUtil.java b/src/main/java/net/momirealms/customcrops/utils/AdventureUtil.java deleted file mode 100644 index 5f6b1e4..0000000 --- a/src/main/java/net/momirealms/customcrops/utils/AdventureUtil.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.utils; - -import net.kyori.adventure.audience.Audience; -import net.kyori.adventure.key.Key; -import net.kyori.adventure.sound.Sound; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.title.Title; -import net.momirealms.customcrops.CustomCrops; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.time.Duration; - -public class AdventureUtil { - - public static void sendMessage(CommandSender sender, String s) { - if (sender instanceof Player player) playerMessage(player, s); - else consoleMessage(s); - } - - public static void consoleMessage(String s) { - Audience au = CustomCrops.adventure.sender(Bukkit.getConsoleSender()); - MiniMessage mm = MiniMessage.miniMessage(); - Component parsed = mm.deserialize(s); - au.sendMessage(parsed); - } - - public static void playerMessage(Player player, String s) { - Audience au = CustomCrops.adventure.player(player); - MiniMessage mm = MiniMessage.miniMessage(); - Component parsed = mm.deserialize(s); - au.sendMessage(parsed); - } - - public static void playerTitle(Player player, String s1, String s2, int in, int duration, int out) { - Audience au = CustomCrops.adventure.player(player); - MiniMessage mm = MiniMessage.miniMessage(); - Title.Times times = Title.Times.times(Duration.ofMillis(in), Duration.ofMillis(duration), Duration.ofMillis(out)); - Title title = Title.title(mm.deserialize(s1), mm.deserialize(s2), times); - au.showTitle(title); - } - - public static void playerActionbar(Player player, String s) { - Audience au = CustomCrops.adventure.player(player); - MiniMessage mm = MiniMessage.miniMessage(); - au.sendActionBar(mm.deserialize(s)); - } - - public static void playerSound(Player player, Sound.Source source, Key key, float volume, float pitch) { - Sound sound = Sound.sound(key, source, volume, pitch); - Audience au = CustomCrops.adventure.player(player); - au.playSound(sound); - } -} diff --git a/src/main/java/net/momirealms/customcrops/utils/FurnitureUtil.java b/src/main/java/net/momirealms/customcrops/utils/FurnitureUtil.java deleted file mode 100644 index bc939ae..0000000 --- a/src/main/java/net/momirealms/customcrops/utils/FurnitureUtil.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.utils; - -import org.bukkit.Location; -import org.bukkit.Rotation; -import org.bukkit.entity.Entity; -import org.bukkit.entity.ItemFrame; - -import java.util.Random; - -public class FurnitureUtil { - - private static final Rotation[] rotations4 = {Rotation.NONE, Rotation.FLIPPED, Rotation.CLOCKWISE, Rotation.COUNTER_CLOCKWISE}; - - public static ItemFrame getItemFrame(Location location) { - for(Entity entity : location.getWorld().getNearbyEntities(location,0,0,0)){ - if (entity instanceof ItemFrame itemFrame) { - return itemFrame; - } - } - return null; - } - - public static boolean hasFurniture(Location location) { - return getItemFrame(location) != null; - } - - public static Rotation getRandomRotation() { - return rotations4[new Random().nextInt(rotations4.length-1)]; - } -} diff --git a/src/main/java/net/momirealms/customcrops/utils/HologramUtil.java b/src/main/java/net/momirealms/customcrops/utils/HologramUtil.java deleted file mode 100644 index 643104d..0000000 --- a/src/main/java/net/momirealms/customcrops/utils/HologramUtil.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.utils; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedChatComponent; -import com.comphenix.protocol.wrappers.WrappedDataValue; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.google.common.collect.Lists; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.momirealms.customcrops.CustomCrops; -import net.momirealms.customcrops.objects.SimpleLocation; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; - -import java.util.*; - -public class HologramUtil { - - public static HashMap cache = new HashMap<>(); - - public static void showHolo(String text, Player player, Location location, int duration){ - - Integer entityID = cache.remove(MiscUtils.getSimpleLocation(location)); - if (entityID != null) { - removeHolo(player, entityID); - } - PacketContainer spawnPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY); - int id = new Random().nextInt(1000000000); - cache.put(MiscUtils.getSimpleLocation(location), id); - spawnPacket.getModifier().write(0, id); - spawnPacket.getModifier().write(1, UUID.randomUUID()); - spawnPacket.getEntityTypeModifier().write(0, EntityType.ARMOR_STAND); - spawnPacket.getDoubles().write(0, location.getX()); - spawnPacket.getDoubles().write(1, location.getY()); - spawnPacket.getDoubles().write(2, location.getZ()); - PacketContainer metaPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); - Component component = MiniMessage.miniMessage().deserialize(text); - WrappedDataWatcher wrappedDataWatcher = new WrappedDataWatcher(); - WrappedDataWatcher.Serializer serializer1 = WrappedDataWatcher.Registry.get(Boolean.class); - WrappedDataWatcher.Serializer serializer2 = WrappedDataWatcher.Registry.get(Byte.class); - wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true)), Optional.of(WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(component)).getHandle())); - wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, serializer1), true); - wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(5, serializer1), true); - byte mask1 = 0x20; - byte mask2 = 0x01; - wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(0, serializer2), mask1); - wrappedDataWatcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, serializer2), mask2); - metaPacket.getModifier().write(0,id); - - if (CustomCrops.plugin.getVersionHelper().isVersionNewerThan1_19_R2()) { - List wrappedDataValueList = Lists.newArrayList(); - wrappedDataWatcher.getWatchableObjects().stream().filter(Objects::nonNull).forEach(entry -> { - final WrappedDataWatcher.WrappedDataWatcherObject dataWatcherObject = entry.getWatcherObject(); - wrappedDataValueList.add(new WrappedDataValue(dataWatcherObject.getIndex(), dataWatcherObject.getSerializer(), entry.getRawValue())); - }); - metaPacket.getDataValueCollectionModifier().write(0, wrappedDataValueList); - } else { - metaPacket.getWatchableCollectionModifier().write(0, wrappedDataWatcher.getWatchableObjects()); - } - - try { - CustomCrops.protocolManager.sendServerPacket(player, spawnPacket); - CustomCrops.protocolManager.sendServerPacket(player, metaPacket); - } - catch (Exception e) { - AdventureUtil.consoleMessage("[CustomCrops] Failed to display hologram for " + player.getName() + " !"); - e.printStackTrace(); - } - Bukkit.getScheduler().runTaskLater(CustomCrops.plugin, ()->{ - removeHolo(player, id); - cache.remove(MiscUtils.getSimpleLocation(location)); - }, duration * 20L); - } - - public static void removeHolo(Player player, int entityId){ - PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY); - packet.getIntLists().write(0, List.of(entityId)); - try { - CustomCrops.protocolManager.sendServerPacket(player, packet); - } - catch (Exception e) { - AdventureUtil.consoleMessage("[CustomCrops] Failed to remove hologram for " + player.getName() + " !"); - e.printStackTrace(); - } - } -} diff --git a/src/main/java/net/momirealms/customcrops/utils/LimitationUtil.java b/src/main/java/net/momirealms/customcrops/utils/LimitationUtil.java deleted file mode 100644 index 982f981..0000000 --- a/src/main/java/net/momirealms/customcrops/utils/LimitationUtil.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.utils; - -import net.momirealms.customcrops.config.MainConfig; -import org.bukkit.Location; -import org.bukkit.Material; - -public class LimitationUtil { - - public static boolean reachWireLimit(Location location) { - int minHeight = location.getWorld().getMinHeight(); - int maxHeight = location.getWorld().getMaxHeight(); - Location chunkLocation = new Location(location.getWorld(), location.getChunk().getX() * 16, minHeight, location.getChunk().getZ() * 16); - int n = 1; - for (int i = 0; i < 16; ++i){ - for (int j = 0; j < 16; ++j) { - Location square = chunkLocation.clone().add(i, 0, j); - for (int k = minHeight; k <= maxHeight; ++k) { - square.add(0.0, 1.0, 0.0); - if (square.getBlock().getType() == Material.TRIPWIRE && ++n > MainConfig.wireAmount) { - return true; - } - } - } - } - return false; - } - - public static boolean reachFrameLimit(Location location) { - int minHeight = location.getWorld().getMinHeight(); - int maxHeight = location.getWorld().getMaxHeight(); - Location chunkLocation = new Location(location.getWorld(), location.getChunk().getX() * 16, minHeight, location.getChunk().getZ() * 16); - int n = 1; - for (int i = 0; i < 16; ++i) { - for (int j = 0; j < 16; ++j) { - Location square; - if (MainConfig.OraxenHook) square = chunkLocation.clone().add(i + 0.5, 0.03125, j + 0.5); - else square = chunkLocation.clone().add(i + 0.5, 0.5, j + 0.5); - for (int k = minHeight; k <= maxHeight; ++k) { - square.add(0.0, 1.0, 0.0); - if (FurnitureUtil.hasFurniture(square) && ++n > MainConfig.frameAmount) { - return true; - } - } - } - } - return false; - } -} \ No newline at end of file diff --git a/src/main/java/net/momirealms/customcrops/utils/MiscUtils.java b/src/main/java/net/momirealms/customcrops/utils/MiscUtils.java deleted file mode 100644 index c30f415..0000000 --- a/src/main/java/net/momirealms/customcrops/utils/MiscUtils.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customcrops.utils; - -import net.momirealms.customcrops.objects.SimpleLocation; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.jetbrains.annotations.Nullable; - -public class MiscUtils { - - public static SimpleLocation getSimpleLocation(Location location) { - return new SimpleLocation(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } - - public static Location getItemFrameBlockLocation(Location frameLoc) { - return new Location(frameLoc.getWorld(), frameLoc.getBlockX(), frameLoc.getBlockY(), frameLoc.getBlockZ()); - } - - @Nullable - public static Location getLocation(SimpleLocation location) { - World world = Bukkit.getWorld(location.getWorldName()); - if (world == null) return null; - return new Location(world, location.getX(), location.getY(), location.getZ()); - } - - public static SimpleLocation getSimpleLocation(String location, String world) { - String[] loc = StringUtils.split(location, ","); - return new SimpleLocation(world, Integer.parseInt(loc[0]), Integer.parseInt(loc[1]), Integer.parseInt(loc[2])); - } - - public static Location getLocation(String location, World world) { - String[] loc = StringUtils.split(location, ","); - return new Location(world, Integer.parseInt(loc[0]), Integer.parseInt(loc[1]), Integer.parseInt(loc[2])); - } - - public static String getStringLocation(Location location) { - return location.getBlockX() + "," + location.getBlockY() + "," + location.getBlockZ(); - } - - public static boolean isVanillaItem(String item) { - char[] chars = item.toCharArray(); - for (char character : chars) { - if ((character < 65 || character > 90) && character != 95) { - return false; - } - } - return true; - } -} diff --git a/src/main/resources/basic_itemsadder.yml b/src/main/resources/basic_itemsadder.yml deleted file mode 100644 index ea62ebc..0000000 --- a/src/main/resources/basic_itemsadder.yml +++ /dev/null @@ -1,9 +0,0 @@ -dry-pot: customcrops:pot -wet-pot: customcrops:watered_pot -greenhouse-glass: customcrops:greenhouse_glass -dead-crop: customcrops:crop_stage_death -soil-surveyor: customcrops:soil_surveyor -crow-fly: customcrops:crow_fly -crow-land: customcrops:crow_land -scarecrow: customcrops:scarecrow -water-effect: customcrops:water_effect \ No newline at end of file diff --git a/src/main/resources/basic_oraxen.yml b/src/main/resources/basic_oraxen.yml deleted file mode 100644 index 06cbff9..0000000 --- a/src/main/resources/basic_oraxen.yml +++ /dev/null @@ -1,9 +0,0 @@ -dry-pot: pot -wet-pot: watered_pot -greenhouse-glass: greenhouse_glass -dead-crop: crop_stage_death -soil-surveyor: soil_surveyor -crow-fly: crow_fly -crow-land: crow_land -scarecrow: scarecrow -water-effect: water_effect \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 6fef651..c5e7fbc 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,12 +1,13 @@ # Don't change -# 请不要修改 -config-version: '24' +config-version: '25' +# BStats metrics: true -# lang: english / spanish / chinese +# Language: english / spanish / chinese / turkish lang: english - -integration: - # AntiGrief +# Set up mode +set-up-mode: true +# AntiGrief +integrations: Residence: false WorldGuard: false Kingdoms: false @@ -17,27 +18,14 @@ integration: GriefPrevention: false CrashClaim: false BentoBox: false - IridiumSkyblock: false + IridiumSkyBlock: false SuperiorSkyBlock: false - # Skill Xp - # Don't forget to config skill-xp for each crop if you enabled skill xp integration - AureliumSkills: false - mcMMO: false - MMOCore: false - EcoSkills: false - # Job xp - # Don't forget to config job-xp for each crop if you enabled job xp integration - JobsReborn: false - EcoJobs: false - # Season - # Synchronize season with other plugins - RealisticSeasons: false worlds: # This is designed for servers that using a separate folder for worlds # The default folder is your server's root folder # 如果你的服务器使用独立文件夹存储世界,请在此填入根目录下的文件地址 - worlds-folder: '' + folder: '' # Mode: whitelist/blacklist # Requires a restart when changing mode or editing world list for the safety of data # 模式:白名单/黑名单 @@ -46,6 +34,21 @@ worlds: list: - world +schedule-system: + enable: true + # The average interval for a crop to gain one point (measured in seconds) + # 平均每个农作物获得一生长点的时间间隔(秒) + point-gain-interval: 10 + # Thread pool settings + # 线程池设置 + thread-pool-settings: + # 核心线程池大小 + corePoolSize: 2 + # 最大线程池大小 + maximumPoolSize: 4 + # seconds (秒) + keepAliveTime: 10 + optimization: # Recommend enabling this to prevent large quantities of crops/item frames from lagging the server # When you are using both item_frame mode and ItemsAdder, you should set "max-furniture-vehicles-per-chunk" in ItemsAdder's config.yml to a higher value @@ -55,274 +58,42 @@ optimization: enable: true # max amount per chunk # 每个区块的限制数量 - tripwire-amount: 64 - itemframe-amount: 64 - - # Disable the water particles when using watering-cans - # 关闭水粒子效果 - disable-water-particles: false - # Auto back up the data when a world is unloaded - # 自动备份 - auto-back-up: true + valid-crop-amount: 64 mechanics: - # Mode: tripwire/item_frame - # 模式:拌线/展示框 - crops-mode: tripwire + # 17/2/1 = 85%/10%/5% + # 2/2/1 = 40%/40%/20% + default-quality-ratio: 17/2/1 - # If enabled, crops would start growing at about 7am(at most 5 seconds inaccuracy) and finish growing in the rest of the day - # Note: All the crops can only start growing when a world's time is around 7am, so when a world is loaded and its time is 8am, - # crops would not grow in this day. You can enable time compensation to make the crops grow when starting the server. - # 如果启用自动生长,农作物将在上午7点左右完成当日生长任务安排并且在接下来的时间里完成生长 - # 请注意:农作物只有在生长点前种植才能在当日生长,否则需要等待下一个生长点,你可以开启下方的生长补偿功能 - auto-grow: - enable: true - # For example, the time to start growing is at 1000ticks(7am), - # sprinklers would finish their work in a random time between 1000~1300ticks, - # Pot would start drying in a random time between 1300~1500ticks - # and crops would grow in a random time between 1500~21500ticks - # 洒水器工作时间/种植盆干湿判断时间/农作物生长时间 不建议修改 - sprinkler-work-time: 300 - pot-dry-time: 200 - crops-grow-time: 20000 - # Crops would start growing instantly when the world is loaded instead of waiting for the second day's 7am - # 生长补偿:当你种下农作物或刚加载世界且恰好错过生长点时候,进行补偿计算分配生长任务 - time-compensation: true - # If the pot is wet, crop would 100% grow a stage per day - # Otherwise they would have a lower chance to grow. - # Recommend setting it to a value higher than 0 to make sure every crop can be ripe even if - # players don't take care of them, this is good for server's performance because crop data would - # be removed from data file as soon as the crop is ripe to avoid affecting server performance in the long term - # 如果种植盆是干燥的,每天生长一个阶段的概率是多少 - # 建议设置高于0的数值,这样每个农作物都能得到生长,最后从数据中移除 - # 长远来看,这样不会造成数据堆积,对服务器性能友好 - dry-pot-grow-chance: 0.5 - # Should the crop go to dead stage if the pot is dry - # 农作物是否会在干燥的种植盆上枯萎 - dry-pot-makes-crop-dead: - enable: false - chance: 0.6 - # Can player harvest crops with right click? - # if set "false" crops can't be harvested repeatedly - # 玩家是否能右键收获农作物,禁用此项则重复收获机制也无法使用 - right-click-harvest: - enable: true - # 是否需要空手 - require-empty-hand: true - # Should player be prevented from planting if wrong season - # 是否阻止玩家在错误季节种植 - prevent-plant-if-wrong-season: true - # Should player be notified of the wrong season? - # 是否提示玩家错误的季节 - should-notify-if-wrong-season: true - # Should crops drop loot only in whitelist worlds or in all the worlds - # 农作物是否只在白名单世界掉落农产品 - drop-loots-in-all-worlds: false - - # Water splash animation when sprinkler works - sprinkler-animation: - enable: true - y-offset: 0.4 - - fill: - watering-can-to-sprinkler: 1 - water-bucket-to-sprinkler: 3 - waterblock-to-watering-can: 1 - - # Will bone meal accelerate the growth of crop - # 骨粉是否能加快农作物生长 - bone-meal: - enable: true - chance: 0.5 - success-particle: VILLAGER_HAPPY # Season mechanic - # Crops would go to death stage if growing in wrong seasons - # Season would not affect ripe crops(for better performance and friendly player's experience) - # 生长中的农作物会在错误的季节死去,但是不会影响已成熟的农作物 + # 季节机制 season: enable: true # If you want all the worlds to share the same season # 是否全世界同步季节 - sync-seasons: + sync-season: enable: false - world: world - + reference: world + # 自动季节交替 auto-season-change: - # If enabled, season would be automatically calculated according to game time when reloading - # 自动切换季节,如果启用则setseason指令仅对当天有效 enable: true # duration of each season (Minecraft days) # 每个季节的时长 duration: 28 greenhouse: enable: true + block: customcrops:greenhouse_glass # effective range (Y axis) + # Y轴有效范围 range: 5 - # During the crop growing progress, crops have a little chance to be eaten by a crow - # Place a scarecrow would protect the crops in this chunk - # 在生长过程中,农作物有小概率被乌鸦袭击,在当前区块放置稻草人可以驱赶乌鸦 - crow: - enable: true - chance: 0.005 - - # 17/2/1 means 85%/10%/5% - # 2/2/1 means 40%/40%/20% - default-quality-ratio: 17/2/1 - - # A crop would go to dead stage if the sky-light level is lower than a certain value. - # 在自然光照不足时,农作物是否会死亡 - dead-if-no-sky-light: - enable: true - level: 10 - - vanilla-crops: - # Can vanilla crops be harvested with right clicks - # 是否可以右键重复收获原版农作物 - right-click-harvest: false - # Prevent player from planting these vanilla crops in farmland - # 阻止玩家种植原版农作物 - prevent-plant: - enable: false - list: - - WHEAT - - CARROTS - - POTATOES - - BEETROOTS - # Convert vanilla items into CustomCrops crops - # You need to make extra CustomCrops/IA/Oraxen configs & models for these crops - # This makes it possible to make vanilla crops have a better mechanic - # 将原版物品转换为customcrops插件农作物 - # 你需要为此制作额外的模型和配置 - convert-to-customcrops: - enable: true - list: - APPLE: apple - #WHEAT_SEEDS: wheat - #CARROT: carrot - #POTATO: potato - #BEETROOT_SEEDS: beetroot +other-settings: # This option requires a skill-plugin hook # Which would increase the amount of crops player get # 这需要一个技能插件才能生效,可以根据玩家种植技能等级提供增益 skill-bonus: enable: false - bonus-per-level: 0.001 - -sounds: - water-pot: - enable: true - sound: minecraft:block.water.ambient - type: player - add-water-to-can: - enable: true - sound: minecraft:item.bucket.fill - type: player - add-water-to-sprinkler: - enable: true - sound: minecraft:item.bucket.fill - type: player - place-sprinkler: - enable: true - sound: minecraft:block.bone_block.place - type: player - plant-seed: - enable: true - sound: minecraft:item.hoe.till - type: player - use-fertilizer: - enable: true - sound: minecraft:item.hoe.till - type: player - harvest-crops: - enable: true - sound: minecraft:block.crop.break - type: player - bonemeal: - enable: true - sound: minecraft:item.hoe.till - type: player - surveyor: - enable: true - sound: minecraft:block.note_block.pling - type: player - - -# Hologram information -hologram: - # Fertilizer infomation - fertilizer-info: - enable: true - y-offset: 0.8 - duration: 1 - text: '{fertilizer} {times}/{max_times}' - # Sprinkler infomation - sprinkler-info: - enable: true - y-offset: 0.8 - duration: 1 - # available variables {water} {max_water} - left: '뀂' - full: '뀁뀃' - empty: '뀁뀄' - right: '뀁뀅' - -actionbar: - # Should actionbar be sent when using watering-can - enable: true - # Available variables {water} {max_water} - left: '뀂' - full: '뀁뀃' - empty: '뀁뀄' - right: '뀁뀅' - - -season-broadcast: - enable: true - spring: - - '<#3CB371>Spring is coming!' - summer: - - '<#FFFFE0>Summer is coming!' - autumn: - - '<#FF8C00>Autumn is coming!' - winter: - - '<#87CEFA>Winter is coming!' - -season-change-command: - enable: false - spring: - - 'say spring is coming!' - - -watering-can-lore: - # Should watering-can has dynamic lore according to the water amount - # 水壶是否有根据水量变化的动态lore - enable: true - # Only packets can remain the former lore, otherwise the lore would be replaced - # 只有发包描述才能保持原有的物品描述,否则会被强制替换 - packets: - # Should watering-can's lore be sent by packets - # Wouldn't work in creative mode for safety - # 是否启用发包模式 - # 安全起见,创造模式下这不会生效 - enable: false - # true: top / false: bottom - # 发包描述位于描述的顶部还是底部 - top-or-bottom: true - # Lore format - # Available variables: {water_bar} - # {water}current water {max_water}max storage - lore: - - '{water_bar}' - - 'Right click water to add water to the can.' - water-bar: - left: '뀂' - full: '뀁뀃' - empty: '뀁뀄' - right: '뀁뀅' - - -other-settings: - # 3 days = 1 hour - # Save the cache to file - data-save-interval: 3 \ No newline at end of file + formula: '{base} + {level} * 0.01' + # MMOCore profession name + # MMOCore职业名 + MMOCore-profession-name: 'farmer' \ No newline at end of file diff --git a/src/main/resources/contents/crops/tomato.yml b/src/main/resources/contents/crops/tomato.yml new file mode 100644 index 0000000..4b63daf --- /dev/null +++ b/src/main/resources/contents/crops/tomato.yml @@ -0,0 +1,280 @@ +tomato: + # TripWire / Item_Frame / Item_Display + crop-mode: TripWire + + # The crop can only be planted on certain pots + pot-whitelist: + - default + + # Seed + seed: customcrops:tomato_seeds + + # break/plant requirements + requirements: + break: + requirement_1: + type: permission + value: tomato.break + message: "You don't have permission to harvest the tomato" + plant: + requirement_1: + type: permission + value: tomato.plant + message: "You don't have permission to plant the tomato" + requirement_2: + type: season + value: + - Spring + - Autumn + message: "It's not a good season to plant tomato" + + # plant actions + plant-actions: + action_1: + type: sound + value: + source: player + key: minecraft:item.hoe.till + volume: 1 + pitch: 1 + + # This decides when the crop data would be removed from cache + max-points: 6 + points: + 0: + model: customcrops:tomato_stage_1 + events: + break: + action_1: + type: drop-items + value: + other-items: + loot_1: + item: customcrops:tomato_seeds + min: 1 + max: 1 + chance: 0.3 + action_2: + type: sound + value: + source: player + key: minecraft:block.crop.break + volume: 1 + pitch: 1 + 1: + model: customcrops:tomato_stage_2 + events: + break: + action_1: + type: drop-items + value: + other-items: + loot_1: + item: customcrops:tomato_seeds + min: 1 + max: 1 + chance: 0.5 + action_2: + type: sound + value: + source: player + key: minecraft:block.crop.break + volume: 1 + pitch: 1 + 3: + model: customcrops:tomato_stage_3 + events: + break: + action_1: + type: drop-items + value: + other-items: + loot_1: + item: customcrops:tomato_seeds + min: 1 + max: 1 + chance: 0.8 + action_2: + type: sound + value: + source: player + key: minecraft:block.crop.break + volume: 1 + pitch: 1 + 5: + model: customcrops:tomato_stage_4 + events: + break: + action_1: + type: command + value: + - 'say Hello, {player}!' + chance: 0.5 + action_2: + type: sound + value: + source: player + key: minecraft:block.crop.break + volume: 1 + pitch: 1 + action_3: + type: drop-items + value: + quality-crops: + min: 1 + max: 4 + items: + # Other plugin item compatibility(Can also be used in other-items) + # MMOItems:TYPE:ID + # MythicMobs:id + 1: customcrops:tomato + 2: customcrops:tomato_silver_star + 3: customcrops:tomato_golden_star + other-items: + loot_1: + item: customcrops:tomato_seeds + min: 1 + max: 1 + chance: 1 + grow: + action_1: + type: variation + value: + golden: + model: tomato_stage_golden + type: TripWire + chance: 0.01 + interact-by-hand: + action_1: + type: break + action_2: + type: replant + value: + point: 0 + crop: tomato # Replant the crop + model: customcrops:tomato_stage_1 + interact-with-item: + interact_1: + item: customcrops:hoe + reduce-amount: false + actions: + action_1: + type: break + action_2: + type: replant + value: + point: 0 + crop: tomato # Replant the crop + model: customcrops:tomato_stage_1 + interact_2: + item: customcrops:i_want_overgrown_tomato_right_now + reduce-amount: true + return: customcrops:returned_item + actions: + action_1: + type: variation + value: + gigantic: + item: customcrops:gigantic_tomato + type: CHORUS + chance: 1 + 6: + events: + grow: + action_1: + type: variation + value: + gigantic: + item: customcrops:gigantic_tomato + type: CHORUS + chance: 0.02 + + # The crop would actually not gain so many points + 999: + model: customcrops:tomato_stage_golden + events: + break: + action_1: + type: drop-items + value: + other-items: + loot_1: + item: customcrops:golden_tomato + min: 1 + max: 1 + chance: 1 + loot_2: + item: customcrops:golden_tomato + min: 1 + max: 2 + chance: 0.5 + loot_3: + item: customcrops:golden_tomato + min: 1 + max: 2 + chance: 0.3 + interact-by-hand: + action_1: + type: break + action_2: + type: replant + value: + point: 0 + crop: tomato # Replant the crop + model: customcrops:tomato_stage_1 + + # grow conditions + grow-conditions: + condition_1: + type: suitable_season + value: + - Spring + - Autumn + condition_2: + type: water_more_than + value: 3 + + # death conditions + death-conditions: + no_water: + model: customcrops:crop_stage_death + conditions: + '&&': + condition_1: + type: water_less_than + value: 1 + condition_2: + type: random + value: 0.7 # 70% chance to die if the pot is not wet + unsuitable_season: + model: customcrops:crop_stage_death + conditions: + condition_1: + type: unsuitable_season + value: + - Winter + crow_attack: + # crop would be removed if dead-model is not set + conditions: + condition_1: + type: crow_attack + value: + chance: 0.001 + fly-model: customcrops:crow_fly + stand-model: customcrops:crow_stand + + # custom bone meal + custom-bone-meal: + bone_meal_1: + item: BONE_MEAL + particle: VILLAGER_HAPPY + sound: minecraft:item.bone_meal.use + chance: + 2: 0.2 + 1: 0.6 + bone_meal_2: + item: customcrops:custom_bone_meal + return: customcrops:custom_bone_meal_used + chance: + 2: 0.4 + 1: 1 \ No newline at end of file diff --git a/src/main/resources/contents/fertilizers/quality.yml b/src/main/resources/contents/fertilizers/quality.yml new file mode 100644 index 0000000..e380f85 --- /dev/null +++ b/src/main/resources/contents/fertilizers/quality.yml @@ -0,0 +1,36 @@ +quality_1: + type: QUALITY + name: '뀆' + chance: 1 + times: 28 + ratio: 7/2/1 + item: customcrops:quality_1 + before-plant: true + particle: SCRAPE + sound: minecraft:item.hoe.till + pot-whitelist: + - default +quality_2: + type: QUALITY + name: '뀇' + chance: 1 + times: 28 + ratio: 11/6/3 + item: customcrops:quality_2 + before-plant: true + particle: SCRAPE + sound: minecraft:item.hoe.till + pot-whitelist: + - default +quality_3: + type: QUALITY + name: '뀈' + chance: 1 + times: 28 + ratio: 2/2/1 + item: customcrops:quality_3 + before-plant: true + particle: SCRAPE + sound: minecraft:item.hoe.till + pot-whitelist: + - default \ No newline at end of file diff --git a/src/main/resources/contents/fertilizers/soil-retain.yml b/src/main/resources/contents/fertilizers/soil-retain.yml new file mode 100644 index 0000000..fb62127 --- /dev/null +++ b/src/main/resources/contents/fertilizers/soil-retain.yml @@ -0,0 +1,33 @@ +soil_retain_1: + type: SOIL_RETAIN + name: '뀉' + chance: 0.1 + times: 28 + item: customcrops:soil_retain_1 + before-plant: false + particle: SPELL + sound: minecraft:item.hoe.till + pot-whitelist: + - default +soil_retain_2: + type: SOIL_RETAIN + name: '뀊' + chance: 0.2 + times: 28 + item: customcrops:soil_retain_2 + before-plant: false + particle: SPELL + sound: minecraft:item.hoe.till + pot-whitelist: + - default +soil_retain_3: + type: SOIL_RETAIN + name: '뀋' + chance: 0.3 + times: 28 + item: customcrops:soil_retain_3 + before-plant: false + particle: SPELL + sound: minecraft:item.hoe.till + pot-whitelist: + - default \ No newline at end of file diff --git a/src/main/resources/contents/fertilizers/speed-grow.yml b/src/main/resources/contents/fertilizers/speed-grow.yml new file mode 100644 index 0000000..641c8db --- /dev/null +++ b/src/main/resources/contents/fertilizers/speed-grow.yml @@ -0,0 +1,45 @@ +speed_grow_1: + type: SPEED_GROW + # Fertilizer Hologram display name + name: '뀌' + # How many days can this fertilizer stay in pot + times: 14 + # ItemsAdder item namespacedID + item: customcrops:speed_grow_1 + # Should this fertilizer be used before planting + before-plant: true + # The particle to be displayed when using fertilizer + # https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Particle.html + particle: SPELL_WITCH + sound: minecraft:item.hoe.till + pot-whitelist: + - default + chance: + 1: 0.5 +speed_grow_2: + type: SPEED_GROW + name: '뀍' + times: 14 + item: customcrops:speed_grow_2 + before-plant: true + particle: SPELL_WITCH + sound: minecraft:item.hoe.till + pot-whitelist: + - default + chance: + 1: 0.9 +speed_grow_3: + type: SPEED_GROW + name: '뀎' + times: 14 + item: customcrops:speed_grow_3 + before-plant: true + particle: SPELL_WITCH + sound: minecraft:item.hoe.till + pot-whitelist: + - default + # 40% chance to gain another 2 points + # 100% chance to gain another 1 point + chance: + 2: 0.4 + 1: 1 \ No newline at end of file diff --git a/src/main/resources/contents/fertilizers/variation.yml b/src/main/resources/contents/fertilizers/variation.yml new file mode 100644 index 0000000..50c37ea --- /dev/null +++ b/src/main/resources/contents/fertilizers/variation.yml @@ -0,0 +1,34 @@ +variation_1: + type: VARIATION + name: '뀒' + times: 14 + # If a crop's default variation chance is 0.01, now it's 0.03 + chance: 0.02 + item: customcrops:variation_1 + before-plant: true + particle: SOUL + sound: minecraft:item.hoe.till + pot-whitelist: + - default +variation_2: + type: VARIATION + name: '뀓' + times: 14 + chance: 0.04 + item: customcrops:variation_2 + before-plant: true + particle: SOUL + sound: minecraft:item.hoe.till + pot-whitelist: + - default +variation_3: + type: VARIATION + name: '뀔' + times: 14 + chance: 0.08 + item: customcrops:variation_3 + before-plant: true + particle: SOUL + sound: minecraft:item.hoe.till + pot-whitelist: + - default \ No newline at end of file diff --git a/src/main/resources/contents/fertilizers/yield-increase.yml b/src/main/resources/contents/fertilizers/yield-increase.yml new file mode 100644 index 0000000..2d8e22a --- /dev/null +++ b/src/main/resources/contents/fertilizers/yield-increase.yml @@ -0,0 +1,41 @@ +yield_increase_1: + type: YIELD_INCREASE + name: '뀏' + times: 14 + item: customcrops:yield_increase_1 + before-plant: true + particle: TOTEM + sound: minecraft:item.hoe.till + pot-whitelist: + - default + chance: + 3: 0.1 + 2: 0.4 + 1: 0.8 +yield_increase_2: + type: YIELD_INCREASE + name: '뀐' + times: 14 + item: customcrops:yield_increase_2 + before-plant: true + particle: TOTEM + sound: minecraft:item.hoe.till + pot-whitelist: + - default + chance: + 3: 0.2 + 2: 0.6 + 1: 1 +yield_increase_3: + type: YIELD_INCREASE + name: '뀑' + times: 14 + item: customcrops:yield_increase_3 + before-plant: true + particle: TOTEM + sound: minecraft:item.hoe.till + pot-whitelist: + - default + chance: + 3: 0.4 + 2: 1 \ No newline at end of file diff --git a/src/main/resources/contents/pots/default.yml b/src/main/resources/contents/pots/default.yml new file mode 100644 index 0000000..43bd698 --- /dev/null +++ b/src/main/resources/contents/pots/default.yml @@ -0,0 +1,48 @@ +default: + max-water-storage: 10 + base: + # basic models + dry: customcrops:dry_pot + wet: customcrops:wet_pot + # If you want fertilized pots to have different looks + # Don't forget to set more bottom-block types in crop's config + fertilized-pots: + enable: false + quality: + dry: customcrops:dry_pot + wet: customcrops:wet_pot + yield-increase: + dry: customcrops:dry_pot + wet: customcrops:wet_pot + variation: + dry: customcrops:dry_pot + wet: customcrops:wet_pot + soil-retain: + dry: customcrops:dry_pot + wet: customcrops:wet_pot + speed-grow: + dry: customcrops:dry_pot + wet: customcrops:wet_pot + fill-method: + method_1: + item: WATER_BUCKET + return: BUCKET + amount: 3 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + method_2: + item: WATER + return: GLASS_BOTTLE + amount: 1 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + method_3: + item: SNOWBALL + amount: 1 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + method_4: + item: customcrops:magic_water + amount: 10 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient \ No newline at end of file diff --git a/src/main/resources/contents/sprinklers/default.yml b/src/main/resources/contents/sprinklers/default.yml new file mode 100644 index 0000000..0b967e9 --- /dev/null +++ b/src/main/resources/contents/sprinklers/default.yml @@ -0,0 +1,116 @@ +sprinkler_1: + # This decides the work range + # (1+1x2)²=9 + range: 1 + storage: 5 + 3D-item: customcrops:sprinkler_1 + 2D-item: customcrops:sprinkler_1_item + # Item_Frame / Item_Display / Tripwire + type: Item_Frame + place-sound: minecraft:block.bone_block.place + hologram: + enable: true + y-offset: 0.8 + duration: 1 + # Available variables: + # {current} current water + # {storage} max storage + left: '뀂' + full: '뀁뀃' + empty: '뀁뀄' + right: '뀁뀅' + # Water splash animation when sprinkler works + sprinkler-animation: + enable: true + y-offset: 0.4 + item: customcrops:water_animation + # ARMOR_STAND / ITEM_DISPLAY + type: ARMOR_STAND + pot-whitelist: + - default + fill-method: + method_1: + item: WATER_BUCKET + return: BUCKET + amount: 3 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + method_2: + item: WATER + return: GLASS_BOTTLE + amount: 1 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + +sprinkler_2: + # (1+2x2)²=25 + range: 2 + storage: 5 + 3D-item: customcrops:sprinkler_2 + 2D-item: customcrops:sprinkler_2_item + type: Item_Frame + place-sound: minecraft:block.bone_block.place + hologram: + enable: true + y-offset: 0.8 + duration: 1 + left: '뀂' + full: '뀁뀃' + empty: '뀁뀄' + right: '뀁뀅' + sprinkler-animation: + enable: true + y-offset: 0.4 + item: customcrops:water_animation + type: ARMOR_STAND + pot-whitelist: + - default + fill-method: + method_1: + item: WATER_BUCKET + return: BUCKET + amount: 3 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + method_2: + item: WATER + return: GLASS_BOTTLE + amount: 1 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + +sprinkler_3: + range: 2 + storage: 7 + 3D-item: customcrops:sprinkler_3 + 2D-item: customcrops:sprinkler_3_item + type: Item_Frame + place-sound: minecraft:block.bone_block.place + hologram: + enable: true + y-offset: 0.8 + duration: 1 + left: '뀂' + full: '뀁뀃' + empty: '뀁뀄' + right: '뀁뀅' + sprinkler-animation: + enable: true + y-offset: 0.4 + item: customcrops:water_animation + type: ARMOR_STAND + pot-whitelist: + - default + fill-method: + method_1: + item: WATER_BUCKET + return: BUCKET + amount: 3 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + method_2: + item: WATER + return: GLASS_BOTTLE + amount: 1 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient \ No newline at end of file diff --git a/src/main/resources/contents/watering-cans/default.yml b/src/main/resources/contents/watering-cans/default.yml new file mode 100644 index 0000000..e7ed36d --- /dev/null +++ b/src/main/resources/contents/watering-cans/default.yml @@ -0,0 +1,146 @@ +watering_can_1: + item: customcrops:watering_can_1 + capacity: 3 + # Effective Range + effective-range: + width: 1 + length: 1 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + fill-method: + method_1: + target: WATER + type: block + amount: 1 + particle: WATER_SPLASH + sound: minecraft:item.bucket.fill + pot-whitelist: + - default + # allows you to add water to sprinkler by clicking with a watering can + sprinkler-whitelist: + - sprinkler_1 + - sprinkler_2 + - sprinkler_3 + dynamic-lore: + # Should watering-can has dynamic lore according to the water amount + # 水壶是否有根据水量变化的动态lore + enable: true + # Available variables: + # {water_bar} water bar image + # {current} current water + # {storage} max storage + lore: + - '{water_bar}' + - 'Right click water to add water to the can.' + actionbar: + # Should actionbar be sent when using watering-can + enable: true + # Available variables {current} {storage} {water_bar} + content: '{water_bar}' + water-bar: + left: '뀂' + full: '뀁뀃' + empty: '뀁뀄' + right: '뀁뀅' + +watering_can_2: + item: customcrops:watering_can_2 + capacity: 4 + effective-range: + width: 1 + length: 2 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + fill-method: + method_1: + target: WATER + type: block + amount: 1 + particle: WATER_SPLASH + pot-whitelist: + - default + sprinkler-whitelist: + - sprinkler_1 + - sprinkler_2 + - sprinkler_3 + dynamic-lore: + enable: true + lore: + - '{water_bar}' + - 'Right click water to add water to the can.' + actionbar: + enable: true + content: '{water_bar}' + water-bar: + left: '뀂' + full: '뀁뀃' + empty: '뀁뀄' + right: '뀁뀅' + +watering_can_3: + item: customcrops:watering_can_3 + capacity: 5 + effective-range: + width: 1 + length: 3 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + fill-method: + method_1: + target: WATER + type: block + amount: 1 + particle: WATER_SPLASH + pot-whitelist: + - default + sprinkler-whitelist: + - sprinkler_1 + - sprinkler_2 + - sprinkler_3 + dynamic-lore: + enable: true + lore: + - '{water_bar}' + - 'Right click water to add water to the can.' + actionbar: + enable: true + content: '{water_bar}' + water-bar: + left: '뀂' + full: '뀁뀃' + empty: '뀁뀄' + right: '뀁뀅' + +watering_can_4: + item: customcrops:watering_can_4 + capacity: 3 + effective-range: + width: 3 + length: 3 + particle: WATER_SPLASH + sound: minecraft:block.water.ambient + fill-method: + method_1: + target: WATER + type: block + amount: 1 + particle: WATER_SPLASH + pot-whitelist: + - default + sprinkler-whitelist: + - sprinkler_1 + - sprinkler_2 + - sprinkler_3 + dynamic-lore: + enable: true + lore: + - '{water_bar}' + - 'Right click water to add water to the can.' + actionbar: + enable: true + content: '{water_bar}' + water-bar: + left: '뀂' + full: '뀁뀃' + empty: '뀁뀄' + right: '뀁뀅' diff --git a/src/main/resources/crops_itemsadder.yml b/src/main/resources/crops_itemsadder.yml deleted file mode 100644 index 8ed6844..0000000 --- a/src/main/resources/crops_itemsadder.yml +++ /dev/null @@ -1,241 +0,0 @@ -# Crop's namespace in ItemsAdder -namespace: customcrops - -# Crop's key name -tomato: - # Crop's max stage - max-stage: 4 - - quality-loots: - amount: 1~4 - quality: - # Other plugin item compatibility(Can also be used in other-loots) - # MMOItems:TYPE:ID - # MythicMobs:id - 1: customcrops:tomato - 2: customcrops:tomato_silver_star - 3: customcrops:tomato_golden_star - - other-loots: - loot_1: - item: customcrops:tomato_seeds - min_amount: 1 - max_amount: 2 - chance: 0.8 - loot_2: - item: customcrops:tomato - min_amount: 1 - max_amount: 2 - chance: 0.8 - - gigantic-crop: - block: customcrops:gigantic_tomato - # furniture: customcrops:gigantic_tomato (If you want gigantic crop to be a furniture) - chance: 0.01 - - harvest-actions: - # Text format: https://docs.adventure.kyori.net/minimessage/format.html - messages: - - 'Hello, {player}! Click here to read the CustomCrops wiki' - # The chance of triggering this type of action, if not set, the action would be definitely triggered (commands-chance, xp-chance...) - messages-chance: 0.5 - - commands: - - 'say {player} harvested a tomato! lol' - xp: 10 - # skill-xp: 100 (You need to enable any skill plugin compatibility in config.yml) - # job-xp: 10 (You need to enable any job plugin compatibility in config.yml) - - # When you harvest with a single right click, the crop would return to a certain stage. If not set, crops would be removed when harvesting - return: customcrops:tomato_stage_1 - - # Suitable seasons for growing - season: - - Spring - - plant-requirements: - condition_1: - # Read the wiki for more condition types - type: permission - # Mode: && / || - mode: '&&' - value: - - crops.plant.tomato - # The message to be shown when not meeting the requirements - message: 'You don''t have permission to plant this seed!' - harvest-requirements: - condition_1: - type: permission - mode: '&&' - value: - - crops.harvest.tomato - message: 'You don''t have permission to harvest tomato!' - - -grape: - max-stage: 6 - quality-loots: - amount: 3~4 - quality: - 1: customcrops:grape - 2: customcrops:grape_silver_star - 3: customcrops:grape_golden_star - return: customcrops:grape_stage_4 - season: - - Spring - - Summer - - Autumn - -garlic: - max-stage: 4 - quality-loots: - amount: 1~4 - quality: - 1: customcrops:garlic - 2: customcrops:garlic_silver_star - 3: customcrops:garlic_golden_star - season: - - Autumn - - Winter - -redpacket: - max-stage: 6 - other-loots: - loot_1: - item: customcrops:redpacket - min_amount: 1 - max_amount: 2 - chance: 1 - loot_2: - item: customcrops:redpacket - min_amount: 1 - max_amount: 4 - chance: 0.8 - loot_3: - item: customcrops:redpacket - min_amount: 1 - max_amount: 2 - chance: 0.4 - -cabbage: - max-stage: 4 - quality-loots: - amount: 1~1 - quality: - 1: customcrops:cabbage - 2: customcrops:cabbage_silver_star - 3: customcrops:cabbage_golden_star - season: - - Spring - - Summer - gigantic-crop: - block: customcrops:gigantic_cabbage - chance: 0.02 - -pepper: - max-stage: 5 - quality-loots: - amount: 3~6 - quality: - 1: customcrops:pepper - 2: customcrops:pepper_silver_star - 3: customcrops:pepper_golden_star - return: customcrops:pepper_stage_3 - season: - - Spring - - Autumn - -corn: - max-stage: 4 - quality-loots: - amount: 1~3 - quality: - 1: customcrops:corn - 2: customcrops:corn_silver_star - 3: customcrops:corn_golden_star - season: - - Summer - - Autumn - - -apple: - max-stage: 6 - other-loots: - loot_1: - item: APPLE - min_amount: 1 - max_amount: 2 - chance: 0.8 - loot_2: - item: APPLE - min_amount: 1 - max_amount: 2 - chance: 1 - return: customcrops:apple_stage_4 - - -pineapple: - max-stage: 4 - quality-loots: - amount: 1~1 - quality: - 1: customcrops:pineapple - 2: customcrops:pineapple_silver_star - 3: customcrops:pineapple_golden_star - gigantic-crop: - block: customcrops:gigantic_pineapple - chance: 0.01 - season: - - Summer - - -pitaya: - max-stage: 6 - quality-loots: - amount: 2~5 - quality: - 1: customcrops:pitaya - 2: customcrops:pitaya_silver_star - 3: customcrops:pitaya_golden_star - return: customcrops:pitaya_stage_4 - - -eggplant: - max-stage: 4 - quality-loots: - amount: 3~7 - quality: - 1: customcrops:eggplant - 2: customcrops:eggplant_silver_star - 3: customcrops:eggplant_golden_star - season: - - Summer - - -chinesecabbage: - max-stage: 4 - quality-loots: - amount: 1~1 - quality: - 1: customcrops:chinese_cabbage - 2: customcrops:chinese_cabbage_silver_star - 3: customcrops:chinese_cabbage_golden_star - season: - - Autumn - - Winter - - -hop: - max-stage: 4 - # Only works in item_frame mode - # To prevent rotation - rotation: false - quality-loots: - amount: 2~5 - quality: - 1: customcrops:hop - 2: customcrops:hop_silver_star - 3: customcrops:hop_golden_star - return: customcrops:hop_stage_1 - season: - - Summer \ No newline at end of file diff --git a/src/main/resources/crops_oraxen.yml b/src/main/resources/crops_oraxen.yml deleted file mode 100644 index 0bfa870..0000000 --- a/src/main/resources/crops_oraxen.yml +++ /dev/null @@ -1,233 +0,0 @@ -# Crop's key name -tomato: - # Crop's max stage - max-stage: 4 - - quality-loots: - amount: 1~4 - quality: - # Other plugin item compatibility(Can also be used in other-loots) - # MMOItems:TYPE:ID - # MythicMobs:id - 1: tomato - 2: tomato_silver_star - 3: tomato_golden_star - - other-loots: - loot_1: - item: tomato_seeds - min_amount: 1 - max_amount: 2 - chance: 0.8 - loot_2: - item: tomato - min_amount: 1 - max_amount: 2 - chance: 0.8 - - gigantic-crop: - block: gigantic_tomato - # furniture: gigantic_tomato (If you want gigantic crop to be a furniture) - chance: 0.01 - - harvest-actions: - # Text format: https://docs.adventure.kyori.net/minimessage/format.html - messages: - - 'Hello, {player}! Click here to read the CustomCrops wiki' - # The chance of triggering this type of action, if not set, the action would be definitely triggered (commands-chance, xp-chance...) - messages-chance: 0.5 - - commands: - - 'say {player} harvested a tomato! lol' - xp: 10 - # skill-xp: 100 (You need to enable any skill plugin compatibility in config.yml) - - # When you harvest with a single right click, the crop would return to a certain stage. If not set, crops would be removed when harvesting - return: tomato_stage_1 - - # Suitable seasons for growing - season: - - Spring - - plant-requirements: - condition_1: - # Read the wiki for more condition types - type: permission - # Mode: && / || - mode: '&&' - value: - - crops.plant.tomato - # The message to be shown when not meeting the requirements - message: 'You don''t have permission to plant this seed!' - harvest-requirements: - condition_1: - type: permission - mode: '&&' - value: - - crops.harvest.tomato - message: 'You don''t have permission to harvest tomato!' - -grape: - max-stage: 6 - quality-loots: - amount: 3~4 - quality: - 1: grape - 2: grape_silver_star - 3: grape_golden_star - return: grape_stage_4 - season: - - Spring - - Summer - - Autumn - -garlic: - max-stage: 4 - quality-loots: - amount: 1~4 - quality: - 1: garlic - 2: garlic_silver_star - 3: garlic_golden_star - season: - - Autumn - - Winter - -redpacket: - max-stage: 6 - other-loots: - loot_1: - item: redpacket - min_amount: 1 - max_amount: 2 - chance: 1 - loot_2: - item: redpacket - min_amount: 1 - max_amount: 4 - chance: 0.8 - loot_3: - item: redpacket - min_amount: 1 - max_amount: 2 - chance: 0.4 - -cabbage: - max-stage: 4 - quality-loots: - amount: 1~1 - quality: - 1: cabbage - 2: cabbage_silver_star - 3: cabbage_golden_star - season: - - Spring - - Summer - gigantic-crop: - block: gigantic_cabbage - chance: 0.02 - -pepper: - max-stage: 5 - quality-loots: - amount: 3~6 - quality: - 1: pepper - 2: pepper_silver_star - 3: pepper_golden_star - return: pepper_stage_3 - season: - - Spring - - Autumn - -corn: - max-stage: 4 - quality-loots: - amount: 1~3 - quality: - 1: corn - 2: corn_silver_star - 3: corn_golden_star - season: - - Summer - - Autumn - - -apple: - max-stage: 6 - other-loots: - loot_1: - item: APPLE - min_amount: 1 - max_amount: 2 - chance: 0.8 - loot_2: - item: APPLE - min_amount: 1 - max_amount: 2 - chance: 1 - return: apple_stage_4 - - -pineapple: - max-stage: 4 - quality-loots: - amount: 1~1 - quality: - 1: pineapple - 2: pineapple_silver_star - 3: pineapple_golden_star - gigantic-crop: - block: gigantic_pineapple - chance: 0.01 - season: - - Summer - - -pitaya: - max-stage: 6 - quality-loots: - amount: 2~5 - quality: - 1: pitaya - 2: pitaya_silver_star - 3: pitaya_golden_star - return: pitaya_stage_4 - - -eggplant: - max-stage: 4 - quality-loots: - amount: 3~7 - quality: - 1: eggplant - 2: eggplant_silver_star - 3: eggplant_golden_star - season: - - Summer - - -chinesecabbage: - max-stage: 4 - quality-loots: - amount: 1~1 - quality: - 1: chinese_cabbage - 2: chinese_cabbage_silver_star - 3: chinese_cabbage_golden_star - season: - - Autumn - - Winter - - -hop: - max-stage: 4 - quality-loots: - amount: 2~5 - quality: - 1: hop - 2: hop_silver_star - 3: hop_golden_star - return: hop_stage_1 - season: - - Summer \ No newline at end of file diff --git a/src/main/resources/fertilizers_itemsadder.yml b/src/main/resources/fertilizers_itemsadder.yml deleted file mode 100644 index 4cf4a3b..0000000 --- a/src/main/resources/fertilizers_itemsadder.yml +++ /dev/null @@ -1,137 +0,0 @@ -#C rops have a small chance to grow two stages at a time -speed: - speed_1: - # Fertilizer Hologram display name - name: '뀌' - # The chance of this fertilizer taking effect - chance: 0.1 - # How many days can this fertilizer stay in pot - times: 14 - # ItemsAdder item namespacedID - item: customcrops:speed_1 - # Should this fertilizer be used before planting - before-plant: true - # The particle to be displayed when using fertilizer - # https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Particle.html - particle: SPELL_WITCH - speed_2: - name: '뀍' - chance: 0.2 - times: 14 - item: customcrops:speed_2 - before-plant: true - particle: SPELL_WITCH - speed_3: - name: '뀎' - chance: 0.3 - times: 14 - item: customcrops:speed_3 - before-plant: true - particle: SPELL_WITCH - - -# Pot have a small chance to retain its water after crops grow -retaining: - retaining_1: - name: '뀉' - chance: 0.1 - times: 28 - item: customcrops:retaining_1 - before-plant: false - particle: SPELL - retaining_2: - name: '뀊' - chance: 0.2 - times: 28 - item: customcrops:retaining_2 - before-plant: false - particle: SPELL - retaining_3: - name: '뀋' - chance: 0.3 - times: 28 - item: customcrops:retaining_3 - before-plant: false - particle: SPELL - - -# When haveresting, players have a higher chance to get high quality crops. -quality: - quality_1: - name: '뀆' - chance: 1 - times: 28 - ratio: 7/2/1 - item: customcrops:quality_1 - before-plant: true - particle: SCRAPE - quality_2: - name: '뀇' - chance: 1 - times: 28 - ratio: 11/6/3 - item: customcrops:quality_2 - before-plant: true - particle: SCRAPE - quality_3: - name: '뀈' - chance: 1 - times: 28 - ratio: 2/2/1 - item: customcrops:quality_3 - before-plant: true - particle: SCRAPE - - -# When haveresting, players have a higher chance to get more crops. -quantity: - quantity_1: - name: '뀏' - times: 14 - chance: 0.5 - bonus: 1 - item: customcrops:quantity_1 - before-plant: true - particle: TOTEM - quantity_2: - name: '뀐' - times: 14 - chance: 0.5 - bonus: 2 - item: customcrops:quantity_2 - before-plant: true - particle: TOTEM - quantity_3: - name: '뀑' - times: 14 - chance: 0.8 - bonus: 2 - item: customcrops:quantity_3 - before-plant: true - particle: TOTEM - - -# Crops have a higher chance to be gigantic -gigantic: - gigantic_1: - name: '뀒' - times: 14 - # If a crop's default gigantic chance is 0.01, now it's 0.03 - chance: 0.02 - item: customcrops:gigantic_1 - before-plant: true - particle: SOUL - gigantic_2: - name: '뀓' - times: 14 - chance: 0.04 - item: customcrops:gigantic_2 - before-plant: true - particle: SOUL - gigantic_3: - name: '뀔' - times: 14 - chance: 0.08 - item: customcrops:gigantic_3 - before-plant: true - particle: SOUL \ No newline at end of file diff --git a/src/main/resources/fertilizers_oraxen.yml b/src/main/resources/fertilizers_oraxen.yml deleted file mode 100644 index 057d5d0..0000000 --- a/src/main/resources/fertilizers_oraxen.yml +++ /dev/null @@ -1,137 +0,0 @@ -# Crops have a small chance to grow two stages at a time -speed: - speed_1: - # Fertilizer Hologram display name - name: '뀌' - # The chance of this fertilizer taking effect - chance: 0.1 - # How many days can this fertilizer stay in pot - times: 14 - # Oraxen Item id - item: speed_1 - # Should this fertilizer be used before planting - before-plant: true - # The particle to be displayed when using fertilizer - # https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Particle.html - particle: SPELL_WITCH - speed_2: - name: '뀍' - chance: 0.2 - times: 14 - item: speed_2 - before-plant: true - particle: SPELL_WITCH - speed_3: - name: '뀎' - chance: 0.3 - times: 14 - item: speed_3 - before-plant: true - particle: SPELL_WITCH - - -# Pot have a small chance to retain its water after crops grow -retaining: - retaining_1: - name: '뀉' - chance: 0.1 - times: 28 - item: retaining_1 - before-plant: false - particle: SPELL - retaining_2: - name: '뀊' - chance: 0.2 - times: 28 - item: retaining_2 - before-plant: false - particle: SPELL - retaining_3: - name: '뀋' - chance: 0.3 - times: 28 - item: retaining_3 - before-plant: false - particle: SPELL - - -# When haveresting, players have a higher chance to get high quality crops. -quality: - quality_1: - name: '뀆' - times: 28 - chance: 1 - ratio: 7/2/1 - item: quality_1 - before-plant: true - particle: SCRAPE - quality_2: - name: '뀇' - times: 28 - chance: 1 - ratio: 11/6/3 - item: quality_2 - before-plant: true - particle: SCRAPE - quality_3: - name: '뀈' - times: 28 - chance: 1 - ratio: 2/2/1 - item: quality_3 - before-plant: true - particle: SCRAPE - - -# When haveresting, players have a higher chance to get more crops. -quantity: - quantity_1: - name: '뀏' - times: 14 - chance: 0.5 - bonus: 1 - item: quantity_1 - before-plant: true - particle: TOTEM - quantity_2: - name: '뀐' - times: 14 - chance: 0.5 - bonus: 2 - item: quantity_2 - before-plant: true - particle: TOTEM - quantity_3: - name: '뀑' - times: 14 - chance: 0.8 - bonus: 2 - item: quantity_3 - before-plant: true - particle: TOTEM - - -# Crops have a higher chance to be gigantic -gigantic: - gigantic_1: - name: '뀒' - times: 14 - # If a crop's default gigantic chance is 0.01, now it's 0.03 - chance: 0.02 - item: gigantic_1 - before-plant: true - particle: SOUL - gigantic_2: - name: '뀓' - times: 14 - chance: 0.04 - item: gigantic_2 - before-plant: true - particle: SOUL - gigantic_3: - name: '뀔' - times: 14 - chance: 0.08 - item: gigantic_3 - before-plant: true - particle: SOUL \ No newline at end of file diff --git a/src/main/resources/messages/messages_chinese.yml b/src/main/resources/messages/messages_chinese.yml index 2445d87..e69de29 100644 --- a/src/main/resources/messages/messages_chinese.yml +++ b/src/main/resources/messages/messages_chinese.yml @@ -1,26 +0,0 @@ -# Text Format -# https://docs.adventure.kyori.net/minimessage/format.html -messages: - prefix: '[CustomCrops] ' - reload: '重载成功! 耗时 {time}ms' - no-perm: '权限不足!' - lack-args: '参数不足!' - wrong-args: '参数错误!' - none-args: '非空参数!' - invalid-args: '无效参数!' - spring: '春' - summer: '夏' - autumn: '秋' - winter: '冬' - limitation-tripwire: '此区块的拌线数量已到达上限 {max}' - limitation-itemframe: '此区块的展示框数量已到达上限 {max}' - grow-simulation: '已开始模拟生长' - back-up: '已完成数据备份!' - set-season: '成功切换世界 {world} 的季节为 {season}!' - before-plant: '这种肥料必须在种植前使用!' - wrong-season: '当前季节不适合这个农作物生长. 当前季节{season}' - no-season: '此世界没有季节' - season-disabled: '季节系统已被禁用' - auto-season-disabled: '自动季节切换已被禁用,无法计算此变量' - world-not-exist: '世界 {world} 不存在' - season-not-exist: '季节 {season} 不存在' \ No newline at end of file diff --git a/src/main/resources/messages/messages_english.yml b/src/main/resources/messages/messages_english.yml index 4b9c124..518f036 100644 --- a/src/main/resources/messages/messages_english.yml +++ b/src/main/resources/messages/messages_english.yml @@ -1,25 +1,20 @@ -# Text Format -# https://docs.adventure.kyori.net/minimessage/format.html -messages: - prefix: '[CustomCrops] ' - reload: 'Reloaded! Took {time}ms' - no-perm: 'No Permission!' - lack-args: 'Arguments are insufficient!' - wrong-args: 'Wrong arguments!' - none-args: 'None arguments!' - invalid-args: 'Invalid arguments!' - spring: 'Spring' - summer: 'Summer' - autumn: 'Autumn' - winter: 'Winter' - limitation-tripwire: 'Tripwires in this chunk have reached limitation {max}' - limitation-itemframe: 'Item frames in this chunk have reached limitation {max}' - grow-simulation: 'Growing simulation has started' - set-season: 'Successfully set {world}''s season to {season}!' - before-plant: 'This fertilizer must be used before planting!' - wrong-season: 'Current season is not suitable for planting this seed. Current season: {season} Suitable seasons: {suitable}' - no-season: 'No season' - season-disabled: 'Season is disabled' - auto-season-disabled: 'Failed to count' - world-not-exist: 'World {world} does not exist' - season-not-exist: 'Season {season} does not exist' \ No newline at end of file +prefix: '[CustomCrops] ' +reload: 'Reloaded! Took {time}ms.' +invalid-args: 'Invalid arguments.' +no-console: 'This command can only be executed by a player.' +not-online: 'Player {player} is not online.' +lack-args: 'Arguments are insufficient.' +not-none-args: 'Not a none argument command.' +before-plant: 'This fertilizer must be used before planting!' +unsuitable-pot: "You can't plant the seed in this pot." +reach-crop-limit: 'The number of crops has reached the limitation.' +no-perm: "You don't have permission to do that." +spring: 'Spring' +summer: 'Summer' +autumn: 'Autumn' +winter: 'Winter' +no-season: 'SEASON DISABLED IN THIS WORLD' +set-season: "Successfully set {world}'s season to {season}." +set-date: "Successfully set {world}'s date to {date}." +world-not-exist: 'World {world} does not exist.' +season-not-exist: 'Season {season} does not exist.' \ No newline at end of file diff --git a/src/main/resources/messages/messages_spanish.yml b/src/main/resources/messages/messages_spanish.yml index 322fe0e..e69de29 100644 --- a/src/main/resources/messages/messages_spanish.yml +++ b/src/main/resources/messages/messages_spanish.yml @@ -1,25 +0,0 @@ -# Text Format -# https://docs.adventure.kyori.net/minimessage/format.html -messages: - prefix: '[CustomCrops] ' - reload: '¡Recargado! Tomó {time}ms' - no-perm: 'No tienes permisos!' - lack-args: 'Los argumentos son insuficientes' - wrong-args: 'Argumentos equivocados' - none-args: '¡Ningún argumento!' - invalid-args: 'Argumentos no válidos' - spring: 'Primavera' - summer: 'Verano' - autumn: 'Otoño' - winter: 'Invierno' - limitation-tripwire: 'Los Tripwires en este trozo han alcanzado la limitación {max}' - limitation-itemframe: 'Los ItemFrames de este trozo han alcanzado el límite {max}' - grow-simulation: 'La simulación de crecimiento ha comenzado' - set-season: 'Fijado con éxito {world}''s temporada a {season}!' - before-plant: 'Este abono debe utilizarse antes de la siembra' - wrong-season: 'La temporada actual no es adecuada para plantar esta semilla' - no-season: 'Sin temporada' - season-disabled: 'La temporada está desactivada' - auto-season-disabled: 'No se ha podido contar' - world-not-exist: 'World {world} no existe' - season-not-exist: 'Temporada {season} no existe' \ No newline at end of file diff --git a/src/main/resources/messages/messages_turkish.yml b/src/main/resources/messages/messages_turkish.yml new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/sprinklers_itemsadder.yml b/src/main/resources/sprinklers_itemsadder.yml deleted file mode 100644 index ad76512..0000000 --- a/src/main/resources/sprinklers_itemsadder.yml +++ /dev/null @@ -1,15 +0,0 @@ -sprinkler_1: - range: 1 - max-water-storage: 5 - 3Ditem: customcrops:sprinkler_1 - 2Ditem: customcrops:sprinkler_1_item -sprinkler_2: - range: 2 - max-water-storage: 6 - 3Ditem: customcrops:sprinkler_2 - 2Ditem: customcrops:sprinkler_2_item -sprinkler_3: - range: 3 - max-water-storage: 7 - 3Ditem: customcrops:sprinkler_3 - 2Ditem: customcrops:sprinkler_3_item \ No newline at end of file diff --git a/src/main/resources/sprinklers_oraxen.yml b/src/main/resources/sprinklers_oraxen.yml deleted file mode 100644 index 247d1d9..0000000 --- a/src/main/resources/sprinklers_oraxen.yml +++ /dev/null @@ -1,15 +0,0 @@ -sprinkler_1: - range: 1 - max-water-storage: 5 - 3Ditem: sprinkler_1 - 2Ditem: sprinkler_1_item -sprinkler_2: - range: 2 - max-water-storage: 6 - 3Ditem: sprinkler_2 - 2Ditem: sprinkler_2_item -sprinkler_3: - range: 3 - max-water-storage: 7 - 3Ditem: sprinkler_3 - 2Ditem: sprinkler_3_item \ No newline at end of file diff --git a/src/main/resources/watercans_itemsadder.yml b/src/main/resources/watercans_itemsadder.yml deleted file mode 100644 index 8e8cc66..0000000 --- a/src/main/resources/watercans_itemsadder.yml +++ /dev/null @@ -1,21 +0,0 @@ -watering_can_1: - item: customcrops:watering_can_1 - max-water-storage: 3 - #Effective Range - width: 1 - length: 1 -watering_can_2: - item: customcrops:watering_can_2 - max-water-storage: 4 - width: 1 - length: 3 -watering_can_3: - item: customcrops:watering_can_3 - max-water-storage: 5 - width: 3 - length: 3 -watering_can_4: - item: customcrops:watering_can_4 - max-water-storage: 6 - width: 3 - length: 5 \ No newline at end of file diff --git a/src/main/resources/watercans_oraxen.yml b/src/main/resources/watercans_oraxen.yml deleted file mode 100644 index d32e095..0000000 --- a/src/main/resources/watercans_oraxen.yml +++ /dev/null @@ -1,21 +0,0 @@ -watering_can_1: - item: watering_can_1 - max-water-storage: 3 - #Effective Range - width: 1 - length: 1 -watering_can_2: - item: watering_can_2 - max-water-storage: 4 - width: 1 - length: 3 -watering_can_3: - item: watering_can_3 - max-water-storage: 5 - width: 3 - length: 3 -watering_can_4: - item: watering_can_4 - max-water-storage: 6 - width: 3 - length: 5 \ No newline at end of file