9
0
mirror of https://github.com/Xiao-MoMi/Custom-Fishing.git synced 2025-12-19 15:09:24 +00:00

1.2半成品

This commit is contained in:
Xiao-MoMi
2022-10-17 01:55:10 +08:00
parent cbb929c7ad
commit 3a4d91be99
180 changed files with 5390 additions and 5675 deletions

View File

@@ -4,7 +4,7 @@ plugins {
}
group = 'net.momirealms'
version = '1.1.4.3'
version = '1.2.0-SNAPSHOT'
repositories {
mavenCentral()
@@ -46,6 +46,7 @@ dependencies {
compileOnly fileTree(dir:'libs',includes:['*.jar'])
compileOnly('io.papermc.paper:paper-api:1.17.1-R0.1-SNAPSHOT')
compileOnly('com.github.Archy-X:AureliumSkills:Beta1.3.6')
compileOnly('com.comphenix.protocol:ProtocolLib:4.8.0')
compileOnly('redis.clients:jedis:4.2.3')
compileOnly('me.clip:placeholderapi:2.11.1')
compileOnly('com.sk89q.worldguard:worldguard-bukkit:7.0.7')
@@ -60,6 +61,7 @@ dependencies {
implementation('net.kyori:adventure-text-minimessage:4.11.0')
implementation('net.kyori:adventure-text-serializer-legacy:4.11.0')
implementation('de.tr7zw:item-nbt-api:2.10.0')
implementation("org.bstats:bstats-bukkit:3.0.0")
}
def targetJavaVersion = 16
@@ -92,6 +94,7 @@ tasks.withType(JavaCompile) {
}
shadowJar {
relocate 'de.tr7zw', 'net.momirealms.customfishing.libs'
relocate 'net.kyori', 'net.momirealms.customfishing.libs'
relocate 'de.tr7zw', 'net.momirealms.customfishing.libs.de.tr7zw'
relocate 'net.kyori', 'net.momirealms.customfishing.libs.net.kyori'
relocate 'org.bstats', 'net.momirealms.customfishing.libs.org.bstats'
}

2
gradlew vendored
View File

@@ -86,7 +86,7 @@ APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
DEFAULT_JVM_OPTS='"-Xmx128m" "-Xms128m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum

File diff suppressed because it is too large Load Diff

View File

@@ -17,34 +17,54 @@
package net.momirealms.customfishing;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.momirealms.customfishing.command.Execute;
import net.momirealms.customfishing.command.TabComplete;
import net.momirealms.customfishing.commands.PluginCommand;
import net.momirealms.customfishing.competition.CompetitionSchedule;
import net.momirealms.customfishing.competition.bossbar.BossBarManager;
import net.momirealms.customfishing.helper.LibraryLoader;
import net.momirealms.customfishing.hook.Placeholders;
import net.momirealms.customfishing.hook.skill.JobsReborn;
import net.momirealms.customfishing.listener.*;
import net.momirealms.customfishing.utils.AdventureUtil;
import net.momirealms.customfishing.utils.ConfigUtil;
import net.momirealms.customfishing.manager.FishingManager;
import net.momirealms.customfishing.manager.IntegrationManager;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ConfigUtil;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Objects;
public final class CustomFishing extends JavaPlugin {
public static JavaPlugin instance;
public static CustomFishing plugin;
public static BukkitAudiences adventure;
public static MiniMessage miniMessage;
public static ProtocolManager protocolManager;
private IntegrationManager integrationManager;
private FishingManager fishingManager;
private CompetitionSchedule competitionSchedule;
public static Placeholders placeholders;
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// .' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||_ \
// | | \\\ - /'| | |
// | \_| `\`---'// |_/ |
// \ .-\__ `-. -'__/-. /
// ___`. .' /--.--\ `. .'___
// ."" '< `.___\_<|>_/___.' _> \"".
// | | : `- \`. ;`. _/; .'/ / .' ; |
// \ \ `-. \_\_`. _.'_/_/ -' _.' /
// ================-.`___`-.__\ \___ /__.-'_.'_.-'================
// `=--=-'
// 佛祖保佑 永无BUG 永不卡服
@Override
public void onLoad() {
instance = this;
plugin = this;
LibraryLoader.load("redis.clients","jedis","4.2.3","https://repo.maven.apache.org/maven2/");
LibraryLoader.load("org.apache.commons","commons-pool2","2.11.1","https://repo.maven.apache.org/maven2/");
LibraryLoader.load("dev.dejvokep","boosted-yaml","1.3","https://repo.maven.apache.org/maven2/");
@@ -52,60 +72,37 @@ public final class CustomFishing extends JavaPlugin {
@Override
public void onEnable() {
adventure = BukkitAudiences.create(this);
miniMessage = MiniMessage.miniMessage();
Objects.requireNonNull(Bukkit.getPluginCommand("customfishing")).setExecutor(new Execute());
Objects.requireNonNull(Bukkit.getPluginCommand("customfishing")).setTabCompleter(new TabComplete());
Bukkit.getPluginManager().registerEvents(new FishListener(),this);
protocolManager = ProtocolLibrary.getProtocolManager();
this.fishingManager = new FishingManager();
this.integrationManager = new IntegrationManager();
this.competitionSchedule = new CompetitionSchedule();
ConfigUtil.reload();
AdventureUtil.consoleMessage("[CustomFishing] Running on <white>" + Bukkit.getVersion());
Bukkit.getScheduler().runTaskAsynchronously(this, ()-> {
ConfigReader.Reload();
if (ConfigReader.Config.competition){
competitionSchedule = new CompetitionSchedule();
competitionSchedule.checkTime();
Bukkit.getScheduler().runTask(this, () -> Bukkit.getPluginManager().registerEvents(new BossBarManager(), this));
}
if (ConfigReader.Config.papi){
placeholders = new Placeholders();
Bukkit.getScheduler().runTask(this, () -> {
placeholders.register();
Bukkit.getPluginManager().registerEvents(new PapiUnregister(), this);
});
}
if (ConfigReader.Config.preventPick)
Bukkit.getScheduler().runTask(this, () -> Bukkit.getPluginManager().registerEvents(new PickUpListener(),this));
if (!Objects.equals(ConfigReader.Config.version, "8"))
ConfigUtil.update();
if (ConfigReader.Config.convertMMOItems)
Bukkit.getScheduler().runTask(this, () -> Bukkit.getPluginManager().registerEvents(new MMOItemsListener(), this));
if (ConfigReader.Config.disableJobXp)
Bukkit.getScheduler().runTask(this, () -> Bukkit.getPluginManager().registerEvents(new JobsListener(), this));
ConfigReader.tryEnableJedis();
AdventureUtil.consoleMessage("<gradient:#0070B3:#A0EACF>[CustomFishing] </gradient><color:#E1FFFF>Plugin Enabled!");
});
PluginCommand pluginCommand = new PluginCommand();
Bukkit.getPluginCommand("customfishing").setExecutor(pluginCommand);
Bukkit.getPluginCommand("customfishing").setTabCompleter(pluginCommand);
AdventureUtil.consoleMessage("[CustomFishing] Plugin Enabled!");
new Metrics(this, 16648);
}
@Override
public void onDisable() {
if (competitionSchedule != null){
competitionSchedule.stopCheck();
competitionSchedule = null;
}
if (adventure != null) {
adventure.close();
adventure = null;
}
if (instance != null){
instance = null;
}
}
public IntegrationManager getIntegrationManager() {
return integrationManager;
}
public FishingManager getFishingManager() {
return fishingManager;
}
public CompetitionSchedule getCompetitionSchedule() {
return competitionSchedule;
}
}

View File

@@ -0,0 +1,22 @@
package net.momirealms.customfishing;
import org.bukkit.entity.Player;
public class Function {
public void load() {
//empty
}
public void unload() {
//empty
}
public void onQuit(Player player) {
}
public void onJoin(Player player) {
}
}

View File

@@ -1,13 +1,7 @@
package net.momirealms.customfishing.api;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.object.loot.Loot;
import org.jetbrains.annotations.Nullable;
public class CustomFishingAPI {
@Nullable
public static Loot getLoot(String key){
return ConfigReader.LOOT.get(key);
}
}

View File

@@ -0,0 +1,43 @@
package net.momirealms.customfishing.api.event;
import net.momirealms.customfishing.object.loot.Loot;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class FishFinderEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlerList = new HandlerList();
private boolean cancelled;
private final List<Loot> loots;
public FishFinderEvent(@NotNull Player who, List<Loot> loots) {
super(who);
this.cancelled = false;
this.loots = loots;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancel) {
cancelled = cancel;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
public List<Loot> getLoots() {
return loots;
}
}

View File

@@ -0,0 +1,40 @@
package net.momirealms.customfishing.api.event;
import net.momirealms.customfishing.object.Difficulty;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import org.jetbrains.annotations.NotNull;
public class FishHookEvent extends PlayerEvent implements Cancellable {
private boolean cancelled;
private final Difficulty difficulty;
private static final HandlerList handlerList = new HandlerList();
public FishHookEvent(@NotNull Player who, Difficulty difficulty) {
super(who);
this.cancelled = false;
this.difficulty = difficulty;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancel) {
cancelled = cancel;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
public Difficulty getDifficulty() {
return difficulty;
}
}

View File

@@ -0,0 +1,61 @@
package net.momirealms.customfishing.api.event;
import net.momirealms.customfishing.object.Difficulty;
import net.momirealms.customfishing.object.FishResult;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FishResultEvent extends PlayerEvent implements Cancellable {
private boolean cancelled;
private boolean isDouble;
private final FishResult result;
private final ItemStack loot;
private static final HandlerList handlerList = new HandlerList();
public FishResultEvent(@NotNull Player who, FishResult result, boolean isDouble, ItemStack loot) {
super(who);
this.cancelled = false;
this.result = result;
this.isDouble = isDouble;
this.loot = loot;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancel) {
cancelled = cancel;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
public boolean isDouble() {
return isDouble;
}
@NotNull
public FishResult getResult() {
return result;
}
@Nullable
public ItemStack getLoot() {
return loot;
}
public void setDouble(boolean willDouble) {
isDouble = willDouble;
}
}

View File

@@ -0,0 +1,40 @@
package net.momirealms.customfishing.api.event;
import net.momirealms.customfishing.object.Bonus;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import org.jetbrains.annotations.NotNull;
public class RodCastEvent extends PlayerEvent implements Cancellable {
private final Bonus bonus;
private boolean isCancelled;
private static final HandlerList handlerList = new HandlerList();
public RodCastEvent(@NotNull Player who, @NotNull Bonus bonus) {
super(who);
this.isCancelled = false;
this.bonus = bonus;
}
@Override
public boolean isCancelled() {
return this.isCancelled;
}
@Override
public void setCancelled(boolean cancel) {
this.isCancelled = cancel;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
public Bonus getBonus() {
return bonus;
}
}

View File

@@ -0,0 +1,4 @@
package net.momirealms.customfishing.api.event;
public class TotemActivationEvent {
}

View File

@@ -1,428 +0,0 @@
package net.momirealms.customfishing.command;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.competition.CompetitionSchedule;
import net.momirealms.customfishing.utils.AdventureUtil;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.utils.ItemUtil;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import javax.print.DocFlavor;
public class Execute implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (!(sender.hasPermission("customfishing.admin") || sender.isOp())) {
AdventureUtil.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.noPerm);
return true;
}
if (args.length < 1){
lackArgs(sender);
return true;
}
if (args[0].equalsIgnoreCase("reload")) {
Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.instance, ()-> {
ConfigReader.Reload();
if (sender instanceof Player){
AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.reload);
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.reload);
}
});
return true;
}
if (args[0].equalsIgnoreCase("import")) {
if (args.length < 2){
lackArgs(sender);
return true;
}
if (sender instanceof Player player){
ItemUtil.saveToFile(player.getInventory().getItemInMainHand(), args[1]);
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + "Done! File is saved to /CustomFishing/loots/" + args[1] + ".yml");
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.noConsole);
}
return true;
}
if (args[0].equalsIgnoreCase("competition")) {
//检验参数长度 [0]competition [1]start/end [2]key
if (args.length < 2){
lackArgs(sender);
return true;
}
if (args[1].equalsIgnoreCase("start")){
if (args.length < 3){
lackArgs(sender);
return true;
}
if (CompetitionSchedule.startCompetition(args[2])){
forceSuccess(sender);
}else {
forceFailure(sender);
}
}else if (args[1].equalsIgnoreCase("end")){
CompetitionSchedule.endCompetition();
forceEnd(sender);
}else if (args[1].equalsIgnoreCase("cancel")){
CompetitionSchedule.cancelCompetition();
forceCancel(sender);
}
return true;
}
if (args[0].equalsIgnoreCase("items")) {
if (args.length < 4){
lackArgs(sender);
return true;
}
if (args[1].equalsIgnoreCase("loot")) {
if (args[2].equalsIgnoreCase("get")) {
//检验参数长度 [0]items [1]loot [2]get [3]xxx [4](amount)
if (sender instanceof Player player){
//是否存在于缓存中
if (ConfigReader.LootItem.containsKey(args[3])){
if (args.length == 4){
ItemUtil.givePlayerLoot(player, args[3], 1);
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", "1").replace("{Item}",args[3]));
}else {
if (Integer.parseInt(args[4]) < 1){
wrongAmount(sender);
return true;
}
ItemUtil.givePlayerLoot(player, args[3], Integer.parseInt(args[4]));
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3]));
}
}else if (ConfigReader.OTHERS.containsKey(args[3])){
if (args.length == 4){
player.getInventory().addItem(ItemUtil.getItemStackFromOtherPlugins(args[3]));
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", "1").replace("{Item}",args[3]));
}else {
if (Integer.parseInt(args[4]) < 1){
wrongAmount(sender);
return true;
}
ItemStack itemStack = ItemUtil.getItemStackFromOtherPlugins(args[3]);
itemStack.setAmount(Integer.parseInt(args[4]));
player.getInventory().addItem(itemStack);
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3]));
}
}else {
noItem(sender);
return true;
}
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.noConsole);
}
return true;
}
if (args[2].equalsIgnoreCase("give")) {
//检验参数长度 [0]items [1]loot [2]give [3]player [4]xxx [5](amount)
if (args.length < 5){
lackArgs(sender);
return true;
}
Player player = Bukkit.getPlayer(args[3]);
//玩家是否在线
if (player == null){
notOnline(sender);
return true;
}
//是否存在于缓存中
if (ConfigReader.LootItem.containsKey(args[4])){
if (args.length == 5){
ItemUtil.givePlayerLoot(player, args[4], 1);
giveItem(sender, args[3], args[4], 1);
return true;
}
else {
if (Integer.parseInt(args[5]) < 1){
wrongAmount(sender);
return true;
}
ItemUtil.givePlayerLoot(player, args[4], Integer.parseInt(args[5]));
giveItem(sender, args[3], args[4], Integer.parseInt(args[5]));
}
}else if (ConfigReader.OTHERS.containsKey(args[4])){
if (args.length == 5){
player.getInventory().addItem(ItemUtil.getItemStackFromOtherPlugins(args[4]));
giveItem(sender, args[3], args[4], 1);
return true;
}
else {
if (Integer.parseInt(args[5]) < 1) {
wrongAmount(sender);
return true;
}
ItemStack itemStack = ItemUtil.getItemStackFromOtherPlugins(args[4]);
itemStack.setAmount(Integer.parseInt(args[5]));
player.getInventory().addItem(itemStack);
giveItem(sender, args[3], args[4], Integer.parseInt(args[5]));
}
}else {
noItem(sender);
return true;
}
return true;
}
}
/*
给予实用物品
*/
else if(args[1].equalsIgnoreCase("util")){
if (args[2].equalsIgnoreCase("get")) {
//检验参数长度 [0]items [1]util [2]get [3]xxx [4](amount)
if (sender instanceof Player player){
//是否存在于缓存中
if (!ConfigReader.UtilItem.containsKey(args[3])){
noItem(sender);
return true;
}
if (args.length == 4){
ItemUtil.givePlayerUtil(player, args[3], 1);
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", "1").replace("{Item}",args[3]));
}else {
if (Integer.parseInt(args[4]) < 1){
wrongAmount(sender);
return true;
}
ItemUtil.givePlayerUtil(player, args[3], Integer.parseInt(args[4]));
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3]));
}
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.noConsole);
}
return true;
}
if (args[2].equalsIgnoreCase("give")) {
//检验参数长度 [0]items [1]util [2]give [3]player [4]xxx [5](amount)
if (args.length < 5){
lackArgs(sender);
return true;
}
Player player = Bukkit.getPlayer(args[3]);
//玩家是否在线
if (player == null){
notOnline(sender);
return true;
}
//是否存在于缓存中
if (!ConfigReader.UtilItem.containsKey(args[4])){
noItem(sender);
return true;
}
if (args.length == 5){
ItemUtil.givePlayerUtil(player, args[4], 1);
giveItem(sender, args[3], args[4], 1);
}else {
if (Integer.parseInt(args[5]) < 1){
wrongAmount(sender);
return true;
}
ItemUtil.givePlayerUtil(player, args[4], Integer.parseInt(args[5]));
giveItem(sender, args[3], args[4], Integer.parseInt(args[5]));
}
return true;
}
}
else if (args[1].equalsIgnoreCase("rod")){
if (args[2].equalsIgnoreCase("get")) {
//检验参数长度 [0]items [1]rod [2]get [3]xxx [4](amount)
if (sender instanceof Player player){
//是否存在于缓存中
if (!ConfigReader.RodItem.containsKey(args[3])){
noItem(sender);
return true;
}
if (args.length == 4){
ItemUtil.givePlayerRod(player, args[3], 1);
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", "1").replace("{Item}",args[3]));
}else {
if (Integer.parseInt(args[4]) < 1){
wrongAmount(sender);
return true;
}
ItemUtil.givePlayerRod(player, args[3], Integer.parseInt(args[4]));
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3]));
}
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.noConsole);
}
return true;
}
if (args[2].equalsIgnoreCase("give")) {
//检验参数长度 [0]items [1]rod [2]give [3]player [4]xxx [5](amount)
if (args.length < 5){
lackArgs(sender);
return true;
}
Player player = Bukkit.getPlayer(args[3]);
//玩家是否在线
if (player == null){
notOnline(sender);
return true;
}
//是否存在于缓存中
if (!ConfigReader.RodItem.containsKey(args[4])){
noItem(sender);
return true;
}
if (args.length == 5){
ItemUtil.givePlayerRod(player, args[4], 1);
giveItem(sender, args[3], args[4], 1);
}else {
if (Integer.parseInt(args[5]) < 1){
wrongAmount(sender);
return true;
}
ItemUtil.givePlayerRod(player, args[4], Integer.parseInt(args[5]));
giveItem(sender, args[3], args[4], Integer.parseInt(args[5]));
}
return true;
}
}
else if (args[1].equalsIgnoreCase("bait")){
if (args[2].equalsIgnoreCase("get")) {
//检验参数长度 [0]items [1]bait [2]get [3]xxx [4](amount)
if (sender instanceof Player player){
//是否存在于缓存中
if (!ConfigReader.BaitItem.containsKey(args[3])){
noItem(sender);
return true;
}
if (args.length == 4){
ItemUtil.givePlayerBait(player, args[3], 1);
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", "1").replace("{Item}",args[3]));
}else {
if (Integer.parseInt(args[4]) < 1){
wrongAmount(sender);
return true;
}
ItemUtil.givePlayerBait(player, args[3], Integer.parseInt(args[4]));
AdventureUtil.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3]));
}
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.noConsole);
}
return true;
}
if (args[2].equalsIgnoreCase("give")) {
//检验参数长度 [0]items [1]bait [2]give [3]player [4]xxx [5](amount)
if (args.length < 5){
lackArgs(sender);
return true;
}
Player player = Bukkit.getPlayer(args[3]);
//玩家是否在线
if (player == null){
notOnline(sender);
return true;
}
//是否存在于缓存中
if (!ConfigReader.BaitItem.containsKey(args[4])){
noItem(sender);
return true;
}
if (args.length == 5){
ItemUtil.givePlayerBait(player, args[4], 1);
giveItem(sender, args[3], args[4], 1);
}else {
if (Integer.parseInt(args[5]) < 1){
wrongAmount(sender);
return true;
}
ItemUtil.givePlayerBait(player, args[4], Integer.parseInt(args[5]));
giveItem(sender, args[3], args[4], Integer.parseInt(args[5]));
}
return true;
}
}
}
return true;
}
private void lackArgs(CommandSender sender){
if (sender instanceof Player){
AdventureUtil.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.lackArgs);
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.lackArgs);
}
}
private void notOnline(CommandSender sender){
if (sender instanceof Player){
AdventureUtil.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.notOnline);
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.notOnline);
}
}
private void noItem(CommandSender sender){
if (sender instanceof Player){
AdventureUtil.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.notExist);
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.notExist);
}
}
private void giveItem(CommandSender sender, String name, String item, int amount){
String string = ConfigReader.Message.prefix + ConfigReader.Message.giveItem.replace("{Amount}", String.valueOf(amount)).replace("{Player}",name).replace("{Item}",item);
if (sender instanceof Player){
AdventureUtil.playerMessage((Player) sender, string);
}else {
AdventureUtil.consoleMessage(string);
}
}
private void wrongAmount(CommandSender sender){
if (sender instanceof Player){
AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.wrongAmount);
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.wrongAmount);
}
}
private void forceSuccess(CommandSender sender){
if (sender instanceof Player){
AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.forceSuccess);
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.forceSuccess);
}
}
private void forceFailure(CommandSender sender){
if (sender instanceof Player){
AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.forceFailure);
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.forceFailure);
}
}
private void forceEnd(CommandSender sender){
if (sender instanceof Player){
AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.forceEnd);
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.forceEnd);
}
}
private void forceCancel(CommandSender sender){
if (sender instanceof Player){
AdventureUtil.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.forceCancel);
}else {
AdventureUtil.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.forceCancel);
}
}
}

View File

@@ -1,252 +0,0 @@
package net.momirealms.customfishing.command;
import net.momirealms.customfishing.ConfigReader;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TabComplete implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) {
if (!(sender.hasPermission("customfishing.admin") || sender.isOp())) {
return null;
}
if (args.length == 1){
List<String> arrayList = new ArrayList<>();
for (String cmd : Arrays.asList("competition","reload", "items","import")) {
if (cmd.startsWith(args[0]))
arrayList.add(cmd);
}
return arrayList;
}
if (args.length == 2){
if (args[0].equalsIgnoreCase("items")){
List<String> arrayList = new ArrayList<>();
for (String cmd : Arrays.asList("loot","bait","rod","util")) {
if (cmd.startsWith(args[1]))
arrayList.add(cmd);
}
return arrayList;
}
if (args[0].equalsIgnoreCase("import")){
return List.of("FileName");
}
if (args[0].equalsIgnoreCase("competition")){
List<String> arrayList = new ArrayList<>();
for (String cmd : List.of("start","end","cancel")) {
if (cmd.startsWith(args[1]))
arrayList.add(cmd);
}
return arrayList;
}
}
if (args.length == 3){
if (args[0].equalsIgnoreCase("items")){
if (args[1].equalsIgnoreCase("loot") || args[1].equalsIgnoreCase("util") || args[1].equalsIgnoreCase("rod") || args[1].equalsIgnoreCase("bait")){
List<String> arrayList = new ArrayList<>();
for (String cmd : Arrays.asList("get","give")) {
if (cmd.startsWith(args[2]))
arrayList.add(cmd);
}
return arrayList;
}
}
if (args[0].equalsIgnoreCase("competition")){
if (args[1].equalsIgnoreCase("start")){
List<String> arrayList = new ArrayList<>();
for (String cmd : competitions()) {
if (cmd.startsWith(args[2]))
arrayList.add(cmd);
}
return arrayList;
}
}
}
if (args.length == 4){
if (args[0].equalsIgnoreCase("items")){
if (args[1].equalsIgnoreCase("loot")){
if (args[2].equalsIgnoreCase("give")){
List<String> arrayList = new ArrayList<>();
for (String cmd : online_players()) {
if (cmd.startsWith(args[3]))
arrayList.add(cmd);
}
return arrayList;
}
if (args[2].equalsIgnoreCase("get")){
List<String> arrayList = new ArrayList<>();
for (String cmd : loots()) {
if (cmd.startsWith(args[3]))
arrayList.add(cmd);
}
return arrayList;
}
}else if (args[1].equalsIgnoreCase("util")){
if (args[2].equalsIgnoreCase("give")){
List<String> arrayList = new ArrayList<>();
for (String cmd : online_players()) {
if (cmd.startsWith(args[3]))
arrayList.add(cmd);
}
return arrayList;
}
if (args[2].equalsIgnoreCase("get")){
List<String> arrayList = new ArrayList<>();
for (String cmd : utils()) {
if (cmd.startsWith(args[3]))
arrayList.add(cmd);
}
return arrayList;
}
}else if (args[1].equalsIgnoreCase("rod")){
if (args[2].equalsIgnoreCase("give")){
List<String> arrayList = new ArrayList<>();
for (String cmd : online_players()) {
if (cmd.startsWith(args[3]))
arrayList.add(cmd);
}
return arrayList;
}
if (args[2].equalsIgnoreCase("get")){
List<String> arrayList = new ArrayList<>();
for (String cmd : rods()) {
if (cmd.startsWith(args[3]))
arrayList.add(cmd);
}
return arrayList;
}
}else if (args[1].equalsIgnoreCase("bait")){
if (args[2].equalsIgnoreCase("give")){
List<String> arrayList = new ArrayList<>();
for (String cmd : online_players()) {
if (cmd.startsWith(args[3]))
arrayList.add(cmd);
}
return arrayList;
}
if (args[2].equalsIgnoreCase("get")){
List<String> arrayList = new ArrayList<>();
for (String cmd : baits()) {
if (cmd.startsWith(args[3]))
arrayList.add(cmd);
}
return arrayList;
}
}
}
}
if (args.length == 5){
if (args[0].equalsIgnoreCase("items")){
if (args[1].equalsIgnoreCase("loot")){
if (args[2].equalsIgnoreCase("give")){
List<String> arrayList = new ArrayList<>();
for (String cmd : loots()) {
if (cmd.startsWith(args[4]))
arrayList.add(cmd);
}
return arrayList;
}
if (args[2].equalsIgnoreCase("get")){
return Arrays.asList("1","16","64");
}
}else if (args[1].equalsIgnoreCase("util")){
if (args[2].equalsIgnoreCase("give")){
List<String> arrayList = new ArrayList<>();
for (String cmd : utils()) {
if (cmd.startsWith(args[4]))
arrayList.add(cmd);
}
return arrayList;
}
if (args[2].equalsIgnoreCase("get")){
return Arrays.asList("1","16","64");
}
}else if (args[1].equalsIgnoreCase("rod")){
if (args[2].equalsIgnoreCase("give")){
List<String> arrayList = new ArrayList<>();
for (String cmd : rods()) {
if (cmd.startsWith(args[4]))
arrayList.add(cmd);
}
return arrayList;
}
if (args[2].equalsIgnoreCase("get")){
return Arrays.asList("1","16","64");
}
}
else if (args[1].equalsIgnoreCase("bait")){
if (args[2].equalsIgnoreCase("give")){
List<String> arrayList = new ArrayList<>();
for (String cmd : baits()) {
if (cmd.startsWith(args[4]))
arrayList.add(cmd);
}
return arrayList;
}
if (args[2].equalsIgnoreCase("get")){
return Arrays.asList("1","16","64");
}
}
}
}
if (args.length == 6){
if (args[0].equalsIgnoreCase("items")){
if (args[1].equalsIgnoreCase("loot")){
if (args[2].equalsIgnoreCase("give")){
return Arrays.asList("1","16","64");
}
}else if (args[1].equalsIgnoreCase("util")){
if (args[2].equalsIgnoreCase("give")){
return Arrays.asList("1","16","64");
}
}else if (args[1].equalsIgnoreCase("rod")){
if (args[2].equalsIgnoreCase("give")){
return List.of("1");
}
}
else if (args[1].equalsIgnoreCase("bait")){
if (args[2].equalsIgnoreCase("give")){
return Arrays.asList("1","16","64");
}
}
}
}
return null;
}
private List<String> online_players(){
List<String> online = new ArrayList<>();
Bukkit.getOnlinePlayers().forEach((player -> online.add(player.getName())));
return online;
}
private List<String> loots(){
ArrayList<String> loots = new ArrayList<>();
loots.addAll(ConfigReader.LootItem.keySet());
loots.addAll(ConfigReader.OTHERS.keySet());
return loots;
}
private List<String> utils(){
return new ArrayList<>(ConfigReader.UtilItem.keySet());
}
private List<String> rods() {
return new ArrayList<>(ConfigReader.RodItem.keySet());
}
private List<String> baits() {
return new ArrayList<>(ConfigReader.BaitItem.keySet());
}
private List<String> competitions() {
return new ArrayList<>(ConfigReader.CompetitionsC.keySet());
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.commands;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.util.AdventureUtil;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public abstract class AbstractSubCommand implements SubCommand {
private final String command;
private Map<String, SubCommand> subCommandMap;
public AbstractSubCommand(String command, Map<String, SubCommand> subCommandMap) {
this.command = command;
this.subCommandMap = subCommandMap;
}
@Override
public boolean onCommand(CommandSender sender, List<String> args) {
if (subCommandMap == null || args.size() < 1) {
return true;
}
SubCommand subCommand = subCommandMap.get(args.get(0));
if (subCommand == null) {
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.unavailableArgs);
} else {
subCommand.onCommand(sender, args.subList(1, args.size()));
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, List<String> args) {
if (subCommandMap == null)
return Collections.singletonList("");
if (args.size() <= 1) {
List<String> returnList = new ArrayList<>(subCommandMap.keySet());
returnList.removeIf(str -> !str.startsWith(args.get(0)));
return returnList;
}
SubCommand subCmd = subCommandMap.get(args.get(0));
if (subCmd != null)
return subCommandMap.get(args.get(0)).onTabComplete(sender, args.subList(1, args.size()));
return Collections.singletonList("");
}
@Override
public String getSubCommand() {
return command;
}
@Override
public Map<String, SubCommand> getSubCommands() {
return Collections.unmodifiableMap(subCommandMap);
}
@Override
public void regSubCommand(SubCommand command) {
if (subCommandMap == null) {
subCommandMap = new ConcurrentHashMap<>();
}
subCommandMap.put(command.getSubCommand(), command);
}
public void setSubCommandMap(Map<String, SubCommand> subCommandMap) {
this.subCommandMap = subCommandMap;
}
protected void giveItem(CommandSender sender, String name, String item, int amount){
String string = MessageManager.prefix + MessageManager.giveItem.replace("{Amount}", String.valueOf(amount)).replace("{Player}",name).replace("{Item}",item);
AdventureUtil.sendMessage(sender, string);
}
protected List<String> online_players() {
List<String> online = new ArrayList<>();
Bukkit.getOnlinePlayers().forEach((player -> online.add(player.getName())));
return online;
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.commands;
import net.momirealms.customfishing.commands.subcmd.CompetitionCommand;
import net.momirealms.customfishing.commands.subcmd.ImportCommand;
import net.momirealms.customfishing.commands.subcmd.ItemsCommand;
import net.momirealms.customfishing.commands.subcmd.ReloadCommand;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.util.AdventureUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class PluginCommand implements TabExecutor {
private final Map<String, SubCommand> subCommandMap;
public PluginCommand() {
subCommandMap = new ConcurrentHashMap<>();
regDefaultSubCommands();
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
List<String> argList = Arrays.asList(args);
if (argList.size() < 1) {
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.nonArgs);
return true;
}
SubCommand subCommand = subCommandMap.get(argList.get(0));
if (subCommand != null)
return subCommand.onCommand(sender, argList.subList(1, argList.size()));
else {
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.unavailableArgs);
return true;
}
}
private void regDefaultSubCommands() {
regSubCommand(ReloadCommand.INSTANCE);
regSubCommand(ItemsCommand.INSTANCE);
regSubCommand(CompetitionCommand.INSTANCE);
regSubCommand(ImportCommand.INSTANCE);
}
public void regSubCommand(SubCommand executor) {
subCommandMap.put(executor.getSubCommand(), executor);
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
List<String> argList = Arrays.asList(args);
if (argList.size() <= 1) {
List<String> returnList = new ArrayList<>(subCommandMap.keySet());
returnList.removeIf(str -> !str.startsWith(args[0]));
return returnList;
}
SubCommand subCommand = subCommandMap.get(argList.get(0));
if (subCommand != null)
return subCommand.onTabComplete(sender, argList.subList(1, argList.size()));
else
return Collections.singletonList("");
}
public Map<String, SubCommand> getSubCommandMap() {
return subCommandMap;
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.commands;
import org.bukkit.command.CommandSender;
import java.util.List;
import java.util.Map;
public interface SubCommand {
boolean onCommand(CommandSender sender, List<String> args);
List<String> onTabComplete(CommandSender sender, List<String> args);
String getSubCommand();
Map<String, SubCommand> getSubCommands();
void regSubCommand(SubCommand subCommand);
}

View File

@@ -0,0 +1,126 @@
package net.momirealms.customfishing.commands.subcmd;
import net.momirealms.customfishing.commands.AbstractSubCommand;
import net.momirealms.customfishing.commands.SubCommand;
import net.momirealms.customfishing.manager.BonusManager;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ItemStackUtil;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class BaitCommand extends AbstractSubCommand {
public static final SubCommand INSTANCE = new BaitCommand();
public BaitCommand() {
super("bait", null);
}
@Override
public boolean onCommand(CommandSender sender, List<String> args) {
if (args.size() < 2) {
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
}
else if (args.get(0).equalsIgnoreCase("get")) {
if (sender instanceof Player player){
if (!BonusManager.BAITITEMS.containsKey(args.get(1))){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist);
return true;
}
if (args.size() == 2){
ItemStackUtil.givePlayerBait(player, args.get(1), 1);
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", "1").replace("{Item}", args.get(1)));
} else {
if (Integer.parseInt(args.get(2)) < 1){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount);
return true;
}
ItemStackUtil.givePlayerBait(player, args.get(1), Integer.parseInt(args.get(2)));
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", args.get(2)).replace("{Item}", args.get(1)));
}
} else {
AdventureUtil.consoleMessage(MessageManager.prefix + MessageManager.noConsole);
}
}
else if (args.get(0).equalsIgnoreCase("give")) {
if (args.size() < 3){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
return true;
}
Player player = Bukkit.getPlayer(args.get(1));
if (player == null){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1)));
return true;
}
if (!BonusManager.BAITITEMS.containsKey(args.get(2))){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist);
return true;
}
if (args.size() == 3){
ItemStackUtil.givePlayerBait(player, args.get(2), 1);
super.giveItem(sender, args.get(1), args.get(2), 1);
} else {
if (Integer.parseInt(args.get(3)) < 1){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount);
return true;
}
ItemStackUtil.givePlayerBait(player, args.get(2), Integer.parseInt(args.get(3)));
super.giveItem(sender, args.get(1), args.get(2), Integer.parseInt(args.get(3)));
}
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, List<String> args) {
if (args.size() == 1) {
return List.of("get", "give");
}
if (args.size() == 2) {
if (args.get(0).equals("get")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : baits()) {
if (cmd.startsWith(args.get(1)))
arrayList.add(cmd);
}
return arrayList;
}
if (args.get(0).equals("give")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : online_players()) {
if (cmd.startsWith(args.get(1)))
arrayList.add(cmd);
}
return arrayList;
}
}
if (args.size() == 3) {
if (args.get(0).equals("get")) {
return List.of("1","2","4","8","16","32","64");
}
if (args.get(0).equals("give")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : baits()) {
if (cmd.startsWith(args.get(2)))
arrayList.add(cmd);
}
return arrayList;
}
}
if (args.size() == 4) {
if (args.get(0).equals("give")) {
return List.of("1","2","4","8","16","32","64");
}
}
return super.onTabComplete(sender, args);
}
private List<String> baits() {
return new ArrayList<>(BonusManager.BAITITEMS.keySet());
}
}

View File

@@ -0,0 +1,63 @@
package net.momirealms.customfishing.commands.subcmd;
import net.momirealms.customfishing.commands.AbstractSubCommand;
import net.momirealms.customfishing.commands.SubCommand;
import net.momirealms.customfishing.competition.CompetitionSchedule;
import net.momirealms.customfishing.manager.CompetitionManager;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.util.AdventureUtil;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class CompetitionCommand extends AbstractSubCommand {
public static final SubCommand INSTANCE = new CompetitionCommand();
public CompetitionCommand() {
super("competition", null);
}
@Override
public boolean onCommand(CommandSender sender, List<String> args) {
if (args.size() < 1){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
return true;
}
if (args.get(0).equals("start")){
if (args.size() < 2){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
return true;
}
if (CompetitionSchedule.startCompetition(args.get(1))){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceSuccess);
} else {
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceFailure);
}
} else if (args.get(0).equals("end")) {
CompetitionSchedule.endCompetition();
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceEnd);
} else if (args.get(0).equals("cancel")) {
CompetitionSchedule.cancelCompetition();
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.forceEnd);
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, List<String> args) {
if (args.size() == 1) {
return List.of("start","end","cancel");
}
if (args.size() == 2 && args.get(0).equals("start")) {
return competitions();
}
return super.onTabComplete(sender, args);
}
private List<String> competitions() {
return new ArrayList<>(CompetitionManager.competitionsC.keySet());
}
}

View File

@@ -0,0 +1,44 @@
package net.momirealms.customfishing.commands.subcmd;
import net.momirealms.customfishing.commands.AbstractSubCommand;
import net.momirealms.customfishing.commands.SubCommand;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ItemStackUtil;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
public class ImportCommand extends AbstractSubCommand {
public static final SubCommand INSTANCE = new ImportCommand();
public ImportCommand() {
super("import", null);
}
@Override
public boolean onCommand(CommandSender sender, List<String> args) {
if (args.size() < 1){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
return true;
} else if (sender instanceof Player player) {
if (ItemStackUtil.saveToFile(player.getInventory().getItemInMainHand(), args.get(0))) {
AdventureUtil.playerMessage(player, MessageManager.prefix + "Done! File is saved to /CustomFishing/loots/" + args.get(0) + ".yml");
}
} else {
AdventureUtil.consoleMessage(MessageManager.prefix + MessageManager.noConsole);
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, List<String> args) {
if (args.size() == 1) {
return Collections.singletonList("file_name");
}
return super.onTabComplete(sender, args);
}
}

View File

@@ -0,0 +1,30 @@
package net.momirealms.customfishing.commands.subcmd;
import net.momirealms.customfishing.commands.AbstractSubCommand;
import net.momirealms.customfishing.commands.SubCommand;
import org.bukkit.command.CommandSender;
import java.util.List;
public class ItemsCommand extends AbstractSubCommand {
public static final SubCommand INSTANCE = new ItemsCommand();
public ItemsCommand() {
super("items", null);
regSubCommand(UtilCommand.INSTANCE);
regSubCommand(RodCommand.INSTANCE);
regSubCommand(BaitCommand.INSTANCE);
regSubCommand(LootCommand.INSTANCE);
}
@Override
public boolean onCommand(CommandSender sender, List<String> args) {
return super.onCommand(sender, args);
}
@Override
public List<String> onTabComplete(CommandSender sender, List<String> args) {
return super.onTabComplete(sender, args);
}
}

View File

@@ -0,0 +1,141 @@
package net.momirealms.customfishing.commands.subcmd;
import net.momirealms.customfishing.commands.AbstractSubCommand;
import net.momirealms.customfishing.commands.SubCommand;
import net.momirealms.customfishing.manager.BonusManager;
import net.momirealms.customfishing.manager.LootManager;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.object.loot.DroppedItem;
import net.momirealms.customfishing.object.loot.Loot;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ItemStackUtil;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class LootCommand extends AbstractSubCommand {
public static final SubCommand INSTANCE = new LootCommand();
public LootCommand() {
super("loot", null);
}
@Override
public boolean onCommand(CommandSender sender, List<String> args) {
if (args.size() < 2) {
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
}
else if (args.get(0).equalsIgnoreCase("get")) {
if (sender instanceof Player player){
if (!loots().contains(args.get(1))){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist);
return true;
}
if (args.size() == 2){
ItemStackUtil.givePlayerLoot(player, args.get(1), 1);
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", "1").replace("{Item}", args.get(1)));
} else {
if (Integer.parseInt(args.get(2)) < 1){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount);
return true;
}
ItemStackUtil.givePlayerLoot(player, args.get(1), Integer.parseInt(args.get(2)));
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", args.get(2)).replace("{Item}", args.get(1)));
}
} else {
AdventureUtil.consoleMessage(MessageManager.prefix + MessageManager.noConsole);
}
}
else if (args.get(0).equalsIgnoreCase("give")) {
if (args.size() < 3){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
return true;
}
Player player = Bukkit.getPlayer(args.get(1));
if (player == null){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1)));
return true;
}
if (!loots().contains(args.get(2))){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist);
return true;
}
if (args.size() == 3){
ItemStackUtil.givePlayerLoot(player, args.get(2), 1);
super.giveItem(sender, args.get(1), args.get(2), 1);
} else {
if (Integer.parseInt(args.get(3)) < 1){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount);
return true;
}
ItemStackUtil.givePlayerLoot(player, args.get(2), Integer.parseInt(args.get(3)));
super.giveItem(sender, args.get(1), args.get(2), Integer.parseInt(args.get(3)));
}
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, List<String> args) {
if (args.size() == 1) {
return List.of("get", "give");
}
if (args.size() == 2) {
if (args.get(0).equals("get")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : loots()) {
if (cmd.startsWith(args.get(1)))
arrayList.add(cmd);
}
return arrayList;
}
if (args.get(0).equals("give")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : online_players()) {
if (cmd.startsWith(args.get(1)))
arrayList.add(cmd);
}
return arrayList;
}
}
if (args.size() == 3) {
if (args.get(0).equals("get")) {
return List.of("1","2","4","8","16","32","64");
}
if (args.get(0).equals("give")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : loots()) {
if (cmd.startsWith(args.get(2)))
arrayList.add(cmd);
}
return arrayList;
}
}
if (args.size() == 4) {
if (args.get(0).equals("give")) {
return List.of("1","2","4","8","16","32","64");
}
}
return super.onTabComplete(sender, args);
}
private List<String> loots() {
List<String> loots = new ArrayList<>();
for (Map.Entry<String, Loot> en : LootManager.WATERLOOTS.entrySet()) {
if (en.getValue() instanceof DroppedItem) {
loots.add(en.getKey());
}
}
for (Map.Entry<String, Loot> en : LootManager.LAVALOOTS.entrySet()) {
if (en.getValue() instanceof DroppedItem) {
loots.add(en.getKey());
}
}
return loots;
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.commands.subcmd;
import net.momirealms.customfishing.commands.AbstractSubCommand;
import net.momirealms.customfishing.commands.SubCommand;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ConfigUtil;
import org.bukkit.command.CommandSender;
import java.util.List;
public final class ReloadCommand extends AbstractSubCommand {
public static final SubCommand INSTANCE = new ReloadCommand();
private ReloadCommand() {
super("reload", null);
}
@Override
public boolean onCommand(CommandSender sender, List<String> args) {
if (args.size() < 1) {
long time1 = System.currentTimeMillis();
ConfigUtil.reload();
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.reload.replace("{time}", String.valueOf(System.currentTimeMillis() - time1)));
return true;
}
return super.onCommand(sender, args);
}
}

View File

@@ -0,0 +1,126 @@
package net.momirealms.customfishing.commands.subcmd;
import net.momirealms.customfishing.commands.AbstractSubCommand;
import net.momirealms.customfishing.commands.SubCommand;
import net.momirealms.customfishing.manager.BonusManager;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ItemStackUtil;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class RodCommand extends AbstractSubCommand {
public static final SubCommand INSTANCE = new RodCommand();
public RodCommand() {
super("rod", null);
}
@Override
public boolean onCommand(CommandSender sender, List<String> args) {
if (args.size() < 2) {
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
}
else if (args.get(0).equalsIgnoreCase("get")) {
if (sender instanceof Player player){
if (!BonusManager.RODITEMS.containsKey(args.get(1))){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist);
return true;
}
if (args.size() == 2){
ItemStackUtil.givePlayerRod(player, args.get(1), 1);
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", "1").replace("{Item}", args.get(1)));
} else {
if (Integer.parseInt(args.get(2)) < 1){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount);
return true;
}
ItemStackUtil.givePlayerRod(player, args.get(1), Integer.parseInt(args.get(2)));
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", args.get(2)).replace("{Item}", args.get(1)));
}
} else {
AdventureUtil.consoleMessage(MessageManager.prefix + MessageManager.noConsole);
}
}
else if (args.get(0).equalsIgnoreCase("give")) {
if (args.size() < 3){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
return true;
}
Player player = Bukkit.getPlayer(args.get(1));
if (player == null){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1)));
return true;
}
if (!BonusManager.RODITEMS.containsKey(args.get(2))){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist);
return true;
}
if (args.size() == 3){
ItemStackUtil.givePlayerRod(player, args.get(2), 1);
super.giveItem(sender, args.get(1), args.get(2), 1);
} else {
if (Integer.parseInt(args.get(3)) < 1){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount);
return true;
}
ItemStackUtil.givePlayerRod(player, args.get(2), Integer.parseInt(args.get(3)));
super.giveItem(sender, args.get(1), args.get(2), Integer.parseInt(args.get(3)));
}
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, List<String> args) {
if (args.size() == 1) {
return List.of("get", "give");
}
if (args.size() == 2) {
if (args.get(0).equals("get")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : rods()) {
if (cmd.startsWith(args.get(1)))
arrayList.add(cmd);
}
return arrayList;
}
if (args.get(0).equals("give")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : online_players()) {
if (cmd.startsWith(args.get(1)))
arrayList.add(cmd);
}
return arrayList;
}
}
if (args.size() == 3) {
if (args.get(0).equals("get")) {
return List.of("1","2","4","8","16","32","64");
}
if (args.get(0).equals("give")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : rods()) {
if (cmd.startsWith(args.get(2)))
arrayList.add(cmd);
}
return arrayList;
}
}
if (args.size() == 4) {
if (args.get(0).equals("give")) {
return List.of("1","2","4","8","16","32","64");
}
}
return super.onTabComplete(sender, args);
}
private List<String> rods() {
return new ArrayList<>(BonusManager.RODITEMS.keySet());
}
}

View File

@@ -0,0 +1,126 @@
package net.momirealms.customfishing.commands.subcmd;
import net.momirealms.customfishing.commands.AbstractSubCommand;
import net.momirealms.customfishing.commands.SubCommand;
import net.momirealms.customfishing.manager.BonusManager;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ItemStackUtil;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class UtilCommand extends AbstractSubCommand {
public static final SubCommand INSTANCE = new UtilCommand();
public UtilCommand() {
super("util", null);
}
@Override
public boolean onCommand(CommandSender sender, List<String> args) {
if (args.size() < 2) {
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
}
else if (args.get(0).equalsIgnoreCase("get")) {
if (sender instanceof Player player){
if (!BonusManager.UTILITEMS.containsKey(args.get(1))){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist);
return true;
}
if (args.size() == 2){
ItemStackUtil.givePlayerUtil(player, args.get(1), 1);
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", "1").replace("{Item}", args.get(1)));
} else {
if (Integer.parseInt(args.get(2)) < 1){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount);
return true;
}
ItemStackUtil.givePlayerUtil(player, args.get(1), Integer.parseInt(args.get(2)));
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.getItem.replace("{Amount}", args.get(2)).replace("{Item}", args.get(1)));
}
} else {
AdventureUtil.consoleMessage(MessageManager.prefix + MessageManager.noConsole);
}
}
else if (args.get(0).equalsIgnoreCase("give")) {
if (args.size() < 3){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.lackArgs);
return true;
}
Player player = Bukkit.getPlayer(args.get(1));
if (player == null){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notOnline.replace("{Player}", args.get(1)));
return true;
}
if (!BonusManager.UTILITEMS.containsKey(args.get(2))){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.notExist);
return true;
}
if (args.size() == 3){
ItemStackUtil.givePlayerUtil(player, args.get(2), 1);
super.giveItem(sender, args.get(1), args.get(2), 1);
} else {
if (Integer.parseInt(args.get(3)) < 1){
AdventureUtil.sendMessage(sender, MessageManager.prefix + MessageManager.wrongAmount);
return true;
}
ItemStackUtil.givePlayerUtil(player, args.get(2), Integer.parseInt(args.get(3)));
super.giveItem(sender, args.get(1), args.get(2), Integer.parseInt(args.get(3)));
}
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, List<String> args) {
if (args.size() == 1) {
return List.of("get", "give");
}
if (args.size() == 2) {
if (args.get(0).equals("get")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : utils()) {
if (cmd.startsWith(args.get(1)))
arrayList.add(cmd);
}
return arrayList;
}
if (args.get(0).equals("give")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : online_players()) {
if (cmd.startsWith(args.get(1)))
arrayList.add(cmd);
}
return arrayList;
}
}
if (args.size() == 3) {
if (args.get(0).equals("get")) {
return List.of("1","2","4","8","16","32","64");
}
if (args.get(0).equals("give")) {
List<String> arrayList = new ArrayList<>();
for (String cmd : utils()) {
if (cmd.startsWith(args.get(2)))
arrayList.add(cmd);
}
return arrayList;
}
}
if (args.size() == 4) {
if (args.get(0).equals("give")) {
return List.of("1","2","4","8","16","32","64");
}
}
return super.onTabComplete(sender, args);
}
private List<String> utils() {
return new ArrayList<>(BonusManager.UTILITEMS.keySet());
}
}

View File

@@ -1,106 +1,77 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.competition.bossbar.BossBarConfig;
import net.momirealms.customfishing.competition.bossbar.BossBarManager;
import net.momirealms.customfishing.competition.ranking.Ranking;
import net.momirealms.customfishing.competition.ranking.RankingImpl;
import net.momirealms.customfishing.competition.ranking.LocalRankingImpl;
import net.momirealms.customfishing.competition.ranking.RankingInterface;
import net.momirealms.customfishing.competition.ranking.RedisRankingImpl;
import net.momirealms.customfishing.object.action.ActionB;
import net.momirealms.customfishing.utils.AdventureUtil;
import net.momirealms.customfishing.manager.CompetitionManager;
import net.momirealms.customfishing.manager.ConfigManager;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.object.action.ActionInterface;
import net.momirealms.customfishing.util.AdventureUtil;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import java.time.Instant;
import java.time.LocalTime;
import java.util.*;
public class Competition {
private Goal goal;
private final long duration;
private long startTime;
private final int minPlayers;
private boolean status;
private BukkitTask timerTask;
private Ranking ranking;
private final BossBarConfig bossBarConfig;
private final List<String> startMessage;
private final List<String> endMessage;
private final List<String> endCommand;
private final List<String> startCommand;
private final List<String> joinCommand;
private final HashMap<String, List<ActionB>> rewardsMap;
public static Competition currentCompetition;
public static long remainingTime;
public static float progress;
public static CompetitionPlayer emptyPlayer = new CompetitionPlayer("XiaoMoMi",0);
private final CompetitionConfig competitionConfig;
private CompetitionGoal goal;
private BukkitTask timerTask;
private RankingInterface ranking;
private long startTime;
private long remainingTime;
private float progress;
private BossBarManager bossBarManager;
public Competition(CompetitionConfig competitionConfig) {
this.duration = competitionConfig.getDuration();
this.goal = competitionConfig.getGoal();
this.minPlayers = competitionConfig.getMinPlayers();
this.bossBarConfig = competitionConfig.getBossBarConfig();
this.startMessage = competitionConfig.getStartMessage();
this.endMessage = competitionConfig.getEndMessage();
this.rewardsMap = competitionConfig.getRewards();
this.startCommand = competitionConfig.getStartCommand();
this.endCommand = competitionConfig.getEndCommand();
this.joinCommand = competitionConfig.getJoinCommand();
this.competitionConfig = competitionConfig;
}
public void begin(boolean forceStart) {
if (goal == Goal.RANDOM) {
goal = getRandomGoal();
if (this.goal == CompetitionGoal.RANDOM) {
this.goal = getRandomGoal();
}
remainingTime = this.duration;
this.remainingTime = this.competitionConfig.getDuration();
this.startTime = Instant.now().getEpochSecond();
Collection<? extends Player> playerCollections = Bukkit.getOnlinePlayers();
if (playerCollections.size() >= minPlayers || forceStart) {
status = true;
if (ConfigReader.useRedis){
if (playerCollections.size() >= competitionConfig.getMinPlayers() || forceStart) {
currentCompetition = this;
if (ConfigManager.useRedis){
ranking = new RedisRankingImpl();
} else {
ranking = new RankingImpl();
ranking = new LocalRankingImpl();
}
startTimer();
if (startMessage != null){
playerCollections.forEach(player -> {
startMessage.forEach(message -> {
AdventureUtil.playerMessage(player, message);
});
});
for (String startMsg : competitionConfig.getStartMessage()) {
for (Player player : playerCollections) {
AdventureUtil.playerMessage(player, startMsg);
}
if (startCommand != null){
startCommand.forEach(command -> {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
});
}
for (String startCmd : competitionConfig.getStartCommand()) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), startCmd);
}
if (competitionConfig.isEnableBossBar()) {
bossBarManager = new BossBarManager(this);
bossBarManager.load();
}
}
else {
playerCollections.forEach(player -> {
AdventureUtil.playerMessage(player, ConfigReader.Message.notEnoughPlayers);
});
for (Player player : playerCollections) {
AdventureUtil.playerMessage(player, MessageManager.notEnoughPlayers);
}
}
}
@@ -112,63 +83,59 @@ public class Competition {
end();
}
}
}.runTaskTimer(CustomFishing.instance, 0, 20);
}.runTaskTimer(CustomFishing.plugin, 0, 20);
}
private boolean decreaseTime() {
long tVac;
long current = Instant.now().getEpochSecond();
progress = (float) remainingTime / duration;
remainingTime = duration - (current - startTime);
if ((tVac = (current - startTime) + 1) != duration - remainingTime) {
for (long i = duration - remainingTime; i < tVac; i++) {
if (remainingTime <= 0) return true;
remainingTime--;
public void cancel() {
if (this.bossBarManager != null) {
bossBarManager.unload();
}
}
return false;
ranking.clear();
this.timerTask.cancel();
currentCompetition = null;
}
public void end() {
BossBarManager.stopAllTimer();
if (this.bossBarManager != null) {
bossBarManager.unload();
}
this.timerTask.cancel();
status = false;
givePrize();
if (endMessage != null){
List<String> newMessage = new ArrayList<>();
endMessage.forEach(message -> {
for (String endMsg : competitionConfig.getEndMessage()) {
CompetitionPlayer[] competitionPlayers = ranking.getTop3Player();
float first = Optional.ofNullable(competitionPlayers[0]).orElse(CompetitionPlayer.emptyPlayer).getScore();
float second = Optional.ofNullable(competitionPlayers[1]).orElse(CompetitionPlayer.emptyPlayer).getScore();
float third = Optional.ofNullable(competitionPlayers[2]).orElse(CompetitionPlayer.emptyPlayer).getScore();
newMessage.add(message
.replace("{1st}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[0]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(ConfigReader.Message.noPlayer))
.replace("{2nd}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[1]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(ConfigReader.Message.noPlayer))
.replace("{3rd}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[2]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(ConfigReader.Message.noPlayer))
.replace("{1st_points}", first < 0 ? ConfigReader.Message.noScore : String.format("%.1f",(first)))
.replace("{2nd_points}", second < 0 ? ConfigReader.Message.noScore : String.format("%.1f",(second)))
.replace("{3rd_points}", third < 0 ? ConfigReader.Message.noScore : String.format("%.1f",(third))));
});
Bukkit.getOnlinePlayers().forEach(player -> {
newMessage.forEach(message -> {
AdventureUtil.playerMessage(player, message);
});
});
newMessage.add(endMsg
.replace("{1st}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[0]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(MessageManager.noPlayer))
.replace("{2nd}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[1]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(MessageManager.noPlayer))
.replace("{3rd}", Optional.ofNullable(Optional.ofNullable(competitionPlayers[2]).orElse(CompetitionPlayer.emptyPlayer).getPlayer()).orElse(MessageManager.noPlayer))
.replace("{1st_points}", first < 0 ? MessageManager.noScore : String.format("%.1f",(first)))
.replace("{2nd_points}", second < 0 ? MessageManager.noScore : String.format("%.1f",(second)))
.replace("{3rd_points}", third < 0 ? MessageManager.noScore : String.format("%.1f",(third))));
}
if (endCommand != null){
endCommand.forEach(command -> {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
});
for (Player player : Bukkit.getOnlinePlayers()) {
for (String msg : newMessage) {
AdventureUtil.playerMessage(player, msg);
}
Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.instance, ()-> {
}
for (String endCmd : competitionConfig.getEndCommand()) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), endCmd);
}
currentCompetition = null;
Bukkit.getScheduler().runTaskLaterAsynchronously(CustomFishing.plugin, ()-> {
ranking.clear();
}, 300);
}, 100);
}
public void givePrize(){
HashMap<String, ActionInterface[]> rewardsMap = competitionConfig.getRewards();
if (ranking.getSize() != 0 && rewardsMap != null) {
Iterator<String> iterator = ranking.getIterator();
int i = 1;
@@ -177,19 +144,19 @@ public class Competition {
String playerName = iterator.next();
Player player = Bukkit.getPlayer(playerName);
if (player != null){
for (ActionB action : rewardsMap.get(String.valueOf(i))) {
for (ActionInterface action : rewardsMap.get(String.valueOf(i))) {
action.doOn(player);
}
}
i++;
}
else {
List<ActionB> actions = rewardsMap.get("participation");
ActionInterface[] actions = rewardsMap.get("participation");
if (actions != null) {
iterator.forEachRemaining(playerName -> {
Player player = Bukkit.getPlayer(playerName);
if (player != null){
for (ActionB action : actions) {
for (ActionInterface action : actions) {
action.doOn(player);
}
}
@@ -203,27 +170,59 @@ public class Competition {
}
}
public void cancel() {
BossBarManager.stopAllTimer();
ranking.clear();
this.timerTask.cancel();
status = false;
private boolean decreaseTime() {
long tVac;
long current = Instant.now().getEpochSecond();
int duration = competitionConfig.getDuration();
progress = (float) remainingTime / duration;
remainingTime = duration - (current - startTime);
if ((tVac = (current - startTime) + 1) != duration - remainingTime) {
for (long i = duration - remainingTime; i < tVac; i++) {
if (remainingTime <= 0) return true;
remainingTime--;
}
}
return false;
}
public void refreshRanking(String player, float score) {
if (this.goal != Goal.TOTAL_SCORE) score = 1.0f;
ranking.refreshData(player, score);
private CompetitionGoal getRandomGoal() {
return CompetitionGoal.values()[new Random().nextInt(CompetitionGoal.values().length - 1)];
}
private Goal getRandomGoal() {
int goal = new Random().nextInt(Goal.values().length-1);
return Goal.values()[goal];
public static boolean hasCompetitionOn() {
return currentCompetition != null;
}
public long getDuration() {return duration;}
public long getRemainingTime() {return remainingTime;}
public boolean isGoingOn() {return status;}
public BossBarConfig getBossBarConfig() {return bossBarConfig;}
public Ranking getRanking() {return ranking;}
public List<String> getJoinCommand() {return joinCommand;}
public float getProgress() {
return progress;
}
public CompetitionConfig getCompetitionConfig() {
return competitionConfig;
}
public String getPlayerRank(Player player) {
return Optional.ofNullable(ranking.getPlayerRank(player.getName())).orElse(MessageManager.noRank);
}
public long getRemainingTime() {
return remainingTime;
}
public double getScore(Player player) {
return Optional.ofNullable(ranking.getCompetitionPlayer(player.getName())).orElse(CompetitionPlayer.emptyPlayer).getScore();
}
public float getFirstScore() {
return ranking.getFirstScore();
}
public String getFirstPlayer() {
return ranking.getFirstPlayer();
}
}

View File

@@ -1,64 +1,80 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition;
import net.momirealms.customfishing.competition.bossbar.BossBarConfig;
import net.momirealms.customfishing.object.action.ActionB;
import net.momirealms.customfishing.object.action.ActionInterface;
import java.util.HashMap;
import java.util.List;
public class CompetitionConfig {
private int duration;
private int minPlayers;
private List<String> startMessage;
private List<String> endMessage;
private List<String> startCommand;
private List<String> endCommand;
private List<String> joinCommand;
private Goal goal;
private BossBarConfig bossBarConfig;
private final int duration;
private final int minPlayers;
private final List<String> startMessage;
private final List<String> endMessage;
private final List<String> startCommand;
private final List<String> endCommand;
private final List<String> joinCommand;
private final CompetitionGoal goal;
private final BossBarConfig bossBarConfig;
private final boolean enableBossBar;
private HashMap<String, List<ActionB>> rewards;
private final HashMap<String, ActionInterface[]> rewards;
public CompetitionConfig(boolean enableBossBar){this.enableBossBar = enableBossBar;}
public void setDuration(int duration) {this.duration = duration;}
public void setBossBarConfig(BossBarConfig bossBarConfig) {this.bossBarConfig = bossBarConfig;}
public void setGoal(Goal goal) {this.goal = goal;}
public void setEndMessage(List<String> endMessage) {this.endMessage = endMessage;}
public void setStartMessage(List<String> startMessage) {this.startMessage = startMessage;}
public void setStartCommand(List<String> startCommand) {this.startCommand = startCommand;}
public void setEndCommand(List<String> endCommand) {this.endCommand = endCommand;}
public void setJoinCommand(List<String> joinCommand) {this.joinCommand = joinCommand;}
public void setMinPlayers(int minPlayers) {this.minPlayers = minPlayers;}
public HashMap<String, List<ActionB>> getRewards() {return rewards;}
public Goal getGoal() {return goal;}
public int getMinPlayers() {return minPlayers;}
public int getDuration() {return duration;}
public BossBarConfig getBossBarConfig() {return bossBarConfig;}
public boolean isEnableBossBar() {return enableBossBar;}
public List<String> getEndMessage() {return endMessage;}
public List<String> getStartMessage() {return startMessage;}
public void setRewards(HashMap<String, List<ActionB>> rewards) {this.rewards = rewards;}
public List<String> getEndCommand() {return endCommand;}
public List<String> getJoinCommand() {return joinCommand;}
public List<String> getStartCommand() {return startCommand;}
public CompetitionConfig(int duration, int minPlayers, List<String> startMessage, List<String> endMessage, List<String> startCommand, List<String> endCommand, List<String> joinCommand, CompetitionGoal goal, BossBarConfig bossBarConfig, boolean enableBossBar, HashMap<String, ActionInterface[]> rewards) {
this.duration = duration;
this.minPlayers = minPlayers;
this.startMessage = startMessage;
this.endMessage = endMessage;
this.startCommand = startCommand;
this.endCommand = endCommand;
this.joinCommand = joinCommand;
this.goal = goal;
this.bossBarConfig = bossBarConfig;
this.enableBossBar = enableBossBar;
this.rewards = rewards;
}
public int getDuration() {
return duration;
}
public int getMinPlayers() {
return minPlayers;
}
public List<String> getStartMessage() {
return startMessage;
}
public List<String> getEndMessage() {
return endMessage;
}
public List<String> getStartCommand() {
return startCommand;
}
public List<String> getEndCommand() {
return endCommand;
}
public List<String> getJoinCommand() {
return joinCommand;
}
public CompetitionGoal getGoal() {
return goal;
}
public BossBarConfig getBossBarConfig() {
return bossBarConfig;
}
public boolean isEnableBossBar() {
return enableBossBar;
}
public HashMap<String, ActionInterface[]> getRewards() {
return rewards;
}
}

View File

@@ -0,0 +1,9 @@
package net.momirealms.customfishing.competition;
public enum CompetitionGoal {
CATCH_AMOUNT,
TOTAL_SCORE,
RANDOM
}

View File

@@ -1,20 +1,3 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition;
import org.jetbrains.annotations.NotNull;
@@ -57,6 +40,10 @@ public class CompetitionPlayer implements Comparable<CompetitionPlayer>{
@Override
public String toString() {
return "CompetitionPlayer[player=" + this.player + ", score=" + this.score + ", catch-time=" + this.time + "]";
return "CompetitionPlayer{" +
"time=" + time +
", player='" + player + '\'' +
", score=" + score +
'}';
}
}

View File

@@ -1,90 +1,77 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.CustomFishing;
import org.bukkit.Bukkit;
import net.momirealms.customfishing.Function;
import net.momirealms.customfishing.manager.CompetitionManager;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import java.time.LocalTime;
public class CompetitionSchedule {
public class CompetitionSchedule extends Function {
public static Competition competition;
public static boolean hasBossBar;
private int doubleCheckTime;
private int checkTaskID;
public CompetitionSchedule(){
hasBossBar = false;
@Override
public void load() {
checkTime();
}
@Override
public void unload() {
stopCheck();
cancelCompetition();
}
private BukkitTask checkTimeTask;
private int doubleCheckTime;
public static boolean startCompetition(String competitionName) {
CompetitionConfig competitionConfig = ConfigReader.CompetitionsC.get(competitionName);
CompetitionConfig competitionConfig = CompetitionManager.competitionsC.get(competitionName);
if (competitionConfig == null) return false;
if (competition != null && competition.isGoingOn()){
competition.end();
if (Competition.currentCompetition != null) {
Competition.currentCompetition.end();
}
competition = new Competition(competitionConfig);
competition.begin(true);
hasBossBar = competitionConfig.isEnableBossBar();
Competition.currentCompetition = new Competition(competitionConfig);
Competition.currentCompetition.begin(true);
return true;
}
public static void endCompetition(){
if (competition != null){
competition.end();
public static void cancelCompetition() {
if (Competition.currentCompetition != null) {
Competition.currentCompetition.cancel();
}
}
public static void cancelCompetition(){
if (competition != null){
competition.cancel();
public static void endCompetition() {
if (Competition.currentCompetition != null) {
Competition.currentCompetition.end();
}
}
public void startCompetition(CompetitionConfig competitionConfig) {
if (competition != null && competition.isGoingOn()){
competition.end();
if (Competition.currentCompetition != null) {
Competition.currentCompetition.end();
}
competition = new Competition(competitionConfig);
competition.begin(false);
hasBossBar = competitionConfig.isEnableBossBar();
Competition.currentCompetition = new Competition(competitionConfig);
Competition.currentCompetition.begin(false);
}
public void checkTime() {
BukkitTask checkTimeTask = new BukkitRunnable(){
this.checkTimeTask = new BukkitRunnable() {
public void run() {
if (isANewMinute()) {
CompetitionConfig competitionConfig = ConfigReader.CompetitionsT.get(getCurrentTime());
CompetitionConfig competitionConfig = CompetitionManager.competitionsT.get(getCurrentTime());
if (competitionConfig != null) {
startCompetition(competitionConfig);
}
}
}
}.runTaskTimer(CustomFishing.instance, (60- LocalTime.now().getSecond())*20, 1200);
checkTaskID = checkTimeTask.getTaskId();
}.runTaskTimer(CustomFishing.plugin, (60 - LocalTime.now().getSecond()) * 20, 1200);
}
public void stopCheck() {
Bukkit.getScheduler().cancelTask(checkTaskID);
if (this.checkTimeTask != null) {
checkTimeTask.cancel();
}
}
public String getCurrentTime() {

View File

@@ -17,13 +17,41 @@
package net.momirealms.customfishing.competition.bossbar;
import net.kyori.adventure.bossbar.BossBar;
import org.bukkit.boss.BarColor;
public record BossBarConfig(String text, BossBar.Overlay overlay,
BossBar.Color color, int rate){
public class BossBarConfig {
public BossBar.Color getColor() {return color;}
public int getRate() {return rate;}
public BossBar.Overlay getOverlay() {return overlay;}
public String getText() {return text;}
private final String[] text;
private final int interval;
private final Overlay overlay;
private final BarColor color;
private final int rate;
public BossBarConfig(String[] text, Overlay overlay, BarColor color, int rate, int interval) {
this.text = text;
this.overlay = overlay;
this.color = color;
this.rate = rate;
this.interval = interval;
}
public String[] getText() {
return text;
}
public int getInterval() {
return interval;
}
public Overlay getOverlay() {
return overlay;
}
public BarColor getColor() {
return color;
}
public int getRate() {
return rate;
}
}

View File

@@ -1,77 +1,34 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition.bossbar;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.competition.CompetitionSchedule;
import net.momirealms.customfishing.utils.AdventureUtil;
import org.bukkit.Bukkit;
import net.momirealms.customfishing.Function;
import net.momirealms.customfishing.competition.Competition;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.HashMap;
public class BossBarManager extends Function {
public class BossBarManager implements Listener {
private final Competition competition;
public static HashMap<Player, BossBarTimer> cache = new HashMap<>();
@EventHandler
public void onJoin(PlayerJoinEvent event){
Player player = event.getPlayer();
if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()){
if (CompetitionSchedule.competition.getRanking().getCompetitionPlayer(player.getName()) != null && cache.get(player) == null){
BossBarTimer timerTask = new BossBarTimer(player, CompetitionSchedule.competition.getBossBarConfig());
cache.put(player, timerTask);
}else {
AdventureUtil.playerMessage(player, ConfigReader.Message.competitionOn);
}
}
public BossBarManager(Competition competition) {
this.competition = competition;
}
@EventHandler
public void onQuit(PlayerQuitEvent event){
Player player = event.getPlayer();
BossBarTimer timerTask = cache.get(player);
if (timerTask != null){
timerTask.stopTimer();
cache.remove(player);
}
@Override
public void load() {
super.load();
}
public static void stopAllTimer(){
cache.forEach(((player, timerTask) -> {
timerTask.stopTimer();
}));
cache.clear();
@Override
public void unload() {
super.unload();
}
public static void joinCompetition(Player player){
if (cache.get(player) == null) {
BossBarTimer timerTask = new BossBarTimer(player, CompetitionSchedule.competition.getBossBarConfig());
cache.put(player, timerTask);
if (CompetitionSchedule.competition.getJoinCommand() != null){
CompetitionSchedule.competition.getJoinCommand().forEach(command -> {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName()));
});
}
}
@Override
public void onQuit(Player player) {
super.onQuit(player);
}
@Override
public void onJoin(Player player) {
super.onJoin(player);
}
}

View File

@@ -1,103 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition.bossbar;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.bossbar.BossBar;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.competition.Competition;
import net.momirealms.customfishing.competition.CompetitionSchedule;
import net.momirealms.customfishing.hook.PapiHook;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Optional;
public class BossBarSender extends BukkitRunnable {
private final Player player;
private final Audience audience;
private BossBar bossBar;
private int timer;
private final BossBar.Color color;
private final BossBar.Overlay overlay;
private final String text;
private final int rate;
public BossBarSender(Player player, BossBarConfig bossbarConfig){
this.player = player;
this.audience = CustomFishing.adventure.player(player);
this.timer = 0;
this.color = bossbarConfig.getColor();
this.overlay = bossbarConfig.getOverlay();
this.text = bossbarConfig.getText();
this.rate = bossbarConfig.getRate();
}
public void hideBossbar(){
audience.hideBossBar(bossBar);
}
public void showBossbar(){
String newText = updateText();
bossBar = BossBar.bossBar(
CustomFishing.miniMessage.deserialize(newText),
Competition.progress,
color,
overlay);
audience.showBossBar(bossBar);
}
@Override
public void run() {
if (timer < rate){
timer++;
}else {
updateText();
String newText = updateText();
bossBar.name(CustomFishing.miniMessage.deserialize(newText));
bossBar.progress(Competition.progress);
timer = 0;
}
}
private String updateText() {
String text;
if (ConfigReader.Config.papi){
text = PapiHook.parse(player, this.text);
}else {
text = this.text;
}
String newText;
if (ConfigReader.Config.papi){
newText = PapiHook.parse(player, text.replace("{time}", String.valueOf(Competition.remainingTime))
.replace("{rank}", Optional.ofNullable(CompetitionSchedule.competition.getRanking().getPlayerRank(player.getName())).orElse(ConfigReader.Message.noRank))
.replace("{minute}", String.format("%02d",Competition.remainingTime/60))
.replace("{second}",String.format("%02d",Competition.remainingTime%60))
.replace("{point}", String.format("%.1f",Optional.ofNullable(CompetitionSchedule.competition.getRanking().getCompetitionPlayer(player.getName())).orElse(Competition.emptyPlayer).getScore())));
}else {
newText = text.replace("{time}", String.valueOf(Competition.remainingTime))
.replace("{rank}", Optional.ofNullable(CompetitionSchedule.competition.getRanking().getPlayerRank(player.getName())).orElse(ConfigReader.Message.noRank))
.replace("{minute}", String.format("%02d",Competition.remainingTime/60))
.replace("{second}",String.format("%02d",Competition.remainingTime%60))
.replace("{point}", String.format("%.1f",Optional.ofNullable(CompetitionSchedule.competition.getRanking().getCompetitionPlayer(player.getName())).orElse(Competition.emptyPlayer).getScore()));
}
return newText;
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition.bossbar;
import net.momirealms.customfishing.CustomFishing;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import java.util.HashMap;
public class BossBarTimer {
private HashMap<Integer, BossBarSender> bossbarCache = new HashMap<>();
public BossBarTimer(Player player, BossBarConfig bossBarConfig){
BossBarSender bossbar = new BossBarSender(player, bossBarConfig);
bossbar.showBossbar();
BukkitTask task = bossbar.runTaskTimerAsynchronously(CustomFishing.instance, 0,1);
bossbarCache.put(task.getTaskId(), bossbar);
}
public void stopTimer(){
bossbarCache.forEach((key,value)-> {
value.hideBossbar();
Bukkit.getScheduler().cancelTask(key);
});
bossbarCache = null;
}
}

View File

@@ -15,12 +15,12 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition;
public enum Goal {
TOTAL_SCORE,
CATCH_AMOUNT,
RANDOM
package net.momirealms.customfishing.competition.bossbar;
public enum Overlay {
NOTCHED_6,
NOTCHED_10,
NOTCHED_12,
NOTCHED_20,
PROGRESS
}

View File

@@ -0,0 +1,164 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition.bossbar;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.InternalStructure;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.competition.Competition;
import net.momirealms.customfishing.object.Reflection;
import net.momirealms.customfishing.object.TextCache;
import net.momirealms.customfishing.util.AdventureUtil;
import org.bukkit.boss.BarColor;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import java.util.UUID;
public class Sender {
private final Player player;
private int timer_1;
private int timer_2;
private int counter;
private final int size;
private final TextCache[] texts;
private TextCache text;
private BukkitTask bukkitTask;
private final UUID uuid;
private boolean force;
private final BossBarConfig config;
private boolean isShown;
private final BossBarManager bossBarManager;
public void setText(int position) {
this.text = texts[position];
this.force = true;
}
public Sender(Player player, BossBarConfig config, BossBarManager bossBarManager){
this.bossBarManager = bossBarManager;
String[] str = config.getText();
this.size = str.length;
texts = new TextCache[str.length];
for (int i = 0; i < str.length; i++) {
texts[i] = new TextCache(player, str[i]);
}
text = texts[0];
this.player = player;
this.uuid = UUID.randomUUID();
this.config = config;
this.isShown = false;
}
public void show() {
this.isShown = true;
try {
CustomFishing.protocolManager.sendServerPacket(player, getPacket());
} catch (InvocationTargetException e){
AdventureUtil.consoleMessage("<red>[CustomFishing] Failed to display bossbar for " + player.getName());
}
this.bukkitTask = new BukkitRunnable() {
@Override
public void run() {
if (size != 1) {
timer_2++;
if (timer_2 > config.getInterval()) {
timer_2 = 0;
counter++;
if (counter == size) {
counter = 0;
}
setText(counter);
}
}
if (timer_1 < config.getRate()){
timer_1++;
}
else {
timer_1 = 0;
if (text.update() || force) {
force = false;
try{
CustomFishing.protocolManager.sendServerPacket(player, getPacket());
}
catch (InvocationTargetException e){
AdventureUtil.consoleMessage("<red>[CustomFishing] Failed to update bossbar for " + player.getName());
}
}
}
}
}.runTaskTimerAsynchronously(CustomFishing.plugin,1,1);
}
private PacketContainer getPacket() {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.BOSS);
packet.getModifier().write(0, uuid);
InternalStructure internalStructure = packet.getStructures().read(1);
internalStructure.getChatComponents().write(0, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(
text.getLatestValue()
.replace("{rank}", Competition.currentCompetition.getPlayerRank(player))
.replace("{minute}", String.format("%02d", Competition.currentCompetition.getRemainingTime() / 60))
.replace("{second}",String.format("%02d", Competition.currentCompetition.getRemainingTime() % 60))
.replace("{point}", String.format("%.1f", Competition.currentCompetition.getScore(player))
.replace("{1st_score}", String.format("%.1f", Competition.currentCompetition.getFirstScore()))
.replace("{1st_player}", Competition.currentCompetition.getFirstPlayer())
)))));
internalStructure.getFloat().write(0,1F);
internalStructure.getEnumModifier(BarColor.class, 2).write(0, config.getColor());
internalStructure.getEnumModifier(Overlay.class, 3).write(0, config.getOverlay());
internalStructure.getModifier().write(4, false);
internalStructure.getModifier().write(5, false);
internalStructure.getModifier().write(6, false);
return packet;
}
public void hide() {
remove();
if (bukkitTask != null) bukkitTask.cancel();
this.isShown = false;
}
private void remove() {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.BOSS);
packet.getModifier().write(0, uuid);
packet.getModifier().write(1, Reflection.removeBar);
try{
CustomFishing.protocolManager.sendServerPacket(player, packet);
}catch (InvocationTargetException e){
AdventureUtil.consoleMessage("<red>[CustomFishing] Failed to remove bossbar for " + player.getName());
}
}
public boolean getStatus() {
return this.isShown;
}
public BossBarConfig getConfig() {
return config;
}
}

View File

@@ -1,27 +1,11 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition.ranking;
import net.momirealms.customfishing.competition.CompetitionPlayer;
import net.momirealms.customfishing.manager.MessageManager;
import java.util.*;
public class RankingImpl implements Ranking{
public class LocalRankingImpl implements RankingInterface {
private final Set<CompetitionPlayer> competitionPlayers = Collections.synchronizedSet(new TreeSet<>());
@@ -107,7 +91,6 @@ public class RankingImpl implements Ranking{
return null;
}
public float getScoreAt(int i) {
int index = 1;
for (CompetitionPlayer competitionPlayer : competitionPlayers) {
@@ -116,7 +99,7 @@ public class RankingImpl implements Ranking{
}
index++;
}
return -1.0f;
return 0f;
}
@Override
@@ -131,4 +114,14 @@ public class RankingImpl implements Ranking{
addPlayer(competitionPlayer);
}
}
@Override
public float getFirstScore() {
return getScoreAt(1);
}
@Override
public String getFirstPlayer() {
return Optional.ofNullable(getPlayerAt(1)).orElse(MessageManager.noPlayer);
}
}

View File

@@ -1,32 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition.ranking;
import net.momirealms.customfishing.competition.CompetitionPlayer;
import java.util.Iterator;
public interface Ranking {
void clear();
CompetitionPlayer getCompetitionPlayer(String player);
Iterator<String> getIterator();
int getSize();
String getPlayerRank(String player);
CompetitionPlayer[] getTop3Player();
void refreshData(String player, float score);
}

View File

@@ -0,0 +1,18 @@
package net.momirealms.customfishing.competition.ranking;
import net.momirealms.customfishing.competition.CompetitionPlayer;
import java.util.Iterator;
public interface RankingInterface {
void clear();
CompetitionPlayer getCompetitionPlayer(String player);
Iterator<String> getIterator();
int getSize();
String getPlayerRank(String player);
CompetitionPlayer[] getTop3Player();
void refreshData(String player, float score);
float getFirstScore();
String getFirstPlayer();
}

View File

@@ -1,31 +1,15 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.competition.ranking;
import net.momirealms.customfishing.competition.CompetitionPlayer;
import net.momirealms.customfishing.utils.JedisUtil;
import net.momirealms.customfishing.manager.MessageManager;
import net.momirealms.customfishing.util.JedisUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.resps.Tuple;
import java.util.Iterator;
import java.util.List;
public class RedisRankingImpl implements Ranking{
public class RedisRankingImpl implements RankingInterface {
public void addPlayer(CompetitionPlayer competitionPlayer) {
Jedis jedis = JedisUtil.getJedis();
@@ -111,4 +95,23 @@ public class RedisRankingImpl implements Ranking{
jedis.zincrby("cf_competition", score, player);
jedis.close();
}
@Override
public float getFirstScore() {
Jedis jedis = JedisUtil.getJedis();
List<Tuple> players = jedis.zrevrangeWithScores("cf_competition", 0, 0);
if (players == null) return 0;
if (players.size() == 0) return 0;
return (float) players.get(0).getScore();
}
@Override
public String getFirstPlayer() {
Jedis jedis = JedisUtil.getJedis();
List<String> player = jedis.zrevrange("cf_competition", 0,0);
jedis.close();
if (player == null) return MessageManager.noPlayer;
if (player.size() == 0) return MessageManager.noPlayer;
return player.get(0);
}
}

View File

@@ -27,7 +27,6 @@ package net.momirealms.customfishing.helper;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import net.momirealms.customfishing.CustomFishing;
import org.apache.commons.lang.StringUtils;
@@ -46,7 +45,7 @@ import java.util.Objects;
public final class LibraryLoader {
@SuppressWarnings("Guava")
private static final Supplier<URLClassLoaderAccess> URL_INJECTOR = Suppliers.memoize(() -> URLClassLoaderAccess.create((URLClassLoader) CustomFishing.instance.getClass().getClassLoader()));
private static final Supplier<URLClassLoaderAccess> URL_INJECTOR = Suppliers.memoize(() -> URLClassLoaderAccess.create((URLClassLoader) CustomFishing.plugin.getClass().getClassLoader()));
/**
* Resolves all {@link MavenLibrary} annotations on the given object.
@@ -78,7 +77,9 @@ public final class LibraryLoader {
}
public static void load(Dependency d) {
//Log.info(String.format("Loading dependency %s:%s:%s from %s", d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getRepoUrl()));
String name = d.getArtifactId() + "-" + d.getVersion();
File saveLocation = new File(getLibFolder(d), name + ".jar");
if (!saveLocation.exists()) {
@@ -97,23 +98,28 @@ public final class LibraryLoader {
}
if (!saveLocation.exists()) {
throw new RuntimeException("Unable to download dependency: " + d);
throw new RuntimeException("Unable to download dependency: " + d.toString());
}
try {
URL_INJECTOR.get().addURL(saveLocation.toURI().toURL());
} catch (Exception e) {
throw new RuntimeException("Unable to load dependency: " + saveLocation, e);
throw new RuntimeException("Unable to load dependency: " + saveLocation.toString(), e);
}
}
private static File getLibFolder(Dependency dependency) {
File pluginDataFolder = CustomFishing.instance.getDataFolder();
File pluginDataFolder = CustomFishing.plugin.getDataFolder();
File serverDir = pluginDataFolder.getParentFile().getParentFile();
File helperDir = new File(serverDir, "libraries");
String[] split = StringUtils.split(dependency.getGroupId(), ".");
File jarDir = new File(helperDir, split[0] + File.separator + split[1] + File.separator + dependency.artifactId + File.separator + dependency.version );
File jarDir;
if (split.length > 1){
jarDir = new File(helperDir, split[0] + File.separator + split[1] + File.separator + dependency.artifactId + File.separator + dependency.version );
}else {
jarDir = new File(helperDir, dependency.getGroupId() + File.separator + dependency.artifactId + File.separator + dependency.version );
}
jarDir.mkdirs();
return jarDir;
}

View File

@@ -37,23 +37,23 @@ import java.util.logging.Level;
public final class Log {
public static void info(@NotNull String s) {
CustomFishing.instance.getLogger().info(s);
CustomFishing.plugin.getLogger().info(s);
}
public static void warn(@NotNull String s) {
CustomFishing.instance.getLogger().warning(s);
CustomFishing.plugin.getLogger().warning(s);
}
public static void severe(@NotNull String s) {
CustomFishing.instance.getLogger().severe(s);
CustomFishing.plugin.getLogger().severe(s);
}
public static void warn(@NotNull String s, Throwable t) {
CustomFishing.instance.getLogger().log(Level.WARNING, s, t);
CustomFishing.plugin.getLogger().log(Level.WARNING, s, t);
}
public static void severe(@NotNull String s, Throwable t) {
CustomFishing.instance.getLogger().log(Level.SEVERE, s, t);
CustomFishing.plugin.getLogger().log(Level.SEVERE, s, t);
}
private Log() {

View File

@@ -27,11 +27,7 @@ package net.momirealms.customfishing.helper;
import org.jetbrains.annotations.NotNull;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.*;
/**
* Annotation to indicate the required libraries for a class.

View File

@@ -27,12 +27,7 @@ package net.momirealms.customfishing.helper;
import org.jetbrains.annotations.NotNull;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.*;
/**
* Annotation to indicate a required library for a class.

View File

@@ -25,13 +25,8 @@
package net.momirealms.customfishing.helper;
import org.jetbrains.annotations.NotNull;
import java.lang.annotation.*;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Represents a maven repository.
*/
@@ -45,7 +40,6 @@ public @interface Repository {
*
* @return the base url of the repository
*/
@NotNull
String url();
}

View File

@@ -1,11 +0,0 @@
package net.momirealms.customfishing.hook;
import dev.lone.itemsadder.api.CustomStack;
import org.bukkit.inventory.ItemStack;
public class ItemsAdderItem {
public static ItemStack getItemStack(String namespacedID){
return CustomStack.getInstance(namespacedID).getItemStack();
}
}

View File

@@ -1,14 +0,0 @@
package net.momirealms.customfishing.hook;
import net.Indyuce.mmoitems.MMOItems;
import net.Indyuce.mmoitems.api.Type;
import org.apache.commons.lang.StringUtils;
import org.bukkit.inventory.ItemStack;
public class MMOItemsHook {
public static ItemStack getItemStack(String name){
String[] split = StringUtils.split(name, ":");
return MMOItems.plugin.getMMOItem(Type.get(split[0]), split[1]).newBuilder().getItemStack();
}
}

View File

@@ -1,11 +0,0 @@
package net.momirealms.customfishing.hook;
import io.lumine.mythic.bukkit.MythicBukkit;
import org.bukkit.inventory.ItemStack;
public class MythicItems {
public static ItemStack getItemStack(String name){
return MythicBukkit.inst().getItemManager().getItemStack(name);
}
}

View File

@@ -1,50 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.hook;
import io.lumine.mythic.api.adapters.AbstractLocation;
import io.lumine.mythic.api.adapters.AbstractVector;
import io.lumine.mythic.api.mobs.MobManager;
import io.lumine.mythic.api.mobs.MythicMob;
import io.lumine.mythic.bukkit.MythicBukkit;
import io.lumine.mythic.bukkit.utils.serialize.Position;
import io.lumine.mythic.core.mobs.ActiveMob;
import net.momirealms.customfishing.object.MobVector;
import net.momirealms.customfishing.object.loot.Mob;
import org.bukkit.Location;
import org.bukkit.util.Vector;
import java.util.Optional;
public class MythicMobsUtil {
public static void summonMM(Location pLocation, Location bLocation, Mob mob){
MobManager mobManager = MythicBukkit.inst().getMobManager();
Optional<MythicMob> mythicMob = mobManager.getMythicMob(mob.getMmID());
if (mythicMob.isPresent()) {
MythicMob theMob = mythicMob.get();
Position position = Position.of(bLocation);
AbstractLocation abstractLocation = new AbstractLocation(position);
ActiveMob activeMob = theMob.spawn(abstractLocation, mob.getMmLevel());
MobVector mobVector = mob.getMobVector();
Vector vector = pLocation.subtract(bLocation).toVector().multiply((mobVector.getHorizontal())-1);
vector = vector.setY((vector.getY()+0.2)*mobVector.getVertical());
activeMob.getEntity().setVelocity(new AbstractVector(vector.getX(),vector.getY(),vector.getZ()));
}
}
}

View File

@@ -1,11 +0,0 @@
package net.momirealms.customfishing.hook;
import io.th0rgal.oraxen.items.OraxenItems;
import org.bukkit.inventory.ItemStack;
public class OraxenItem {
public static ItemStack getItemStack(String namespacedID){
return OraxenItems.getItemById(namespacedID).build();
}
}

View File

@@ -1,63 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.hook;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.competition.Competition;
import net.momirealms.customfishing.competition.CompetitionSchedule;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public class Placeholders extends PlaceholderExpansion {
@Override
public @NotNull String getIdentifier() {
return "competition";
}
@Override
public @NotNull String getAuthor() {
return "XiaoMoMi";
}
@Override
public @NotNull String getVersion() {
return "1.0";
}
@Override
public String onRequest(OfflinePlayer player, String params) {
if (params.equalsIgnoreCase("timeleft")){
if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()){
return String.valueOf(Competition.remainingTime);
}else {
return "0";
}
}
if (params.equalsIgnoreCase("rank")){
if (CompetitionSchedule.competition != null && CompetitionSchedule.competition.isGoingOn()){
return Optional.ofNullable(CompetitionSchedule.competition.getRanking().getPlayerRank(player.getName())).orElse(ConfigReader.Message.noRank);
}else {
return ConfigReader.Message.noRank;
}
}
return null;
}
}

View File

@@ -1,10 +0,0 @@
package net.momirealms.customfishing.hook.season;
import net.momirealms.customcrops.api.CustomCropsAPI;
import org.bukkit.World;
public class CustomCropsSeason implements SeasonInterface{
public String getSeason(World world){
return CustomCropsAPI.getSeason(world.getName());
}
}

View File

@@ -1,25 +0,0 @@
package net.momirealms.customfishing.hook.season;
import me.casperge.realisticseasons.api.SeasonsAPI;
import org.bukkit.World;
public class RealisticSeason implements SeasonInterface{
public String getSeason(World world){
SeasonsAPI seasonsapi = SeasonsAPI.getInstance();
switch (seasonsapi.getSeason(world)){
case SPRING -> {
return "spring";
}
case SUMMER -> {
return "summer";
}
case WINTER -> {
return "winter";
}
case FALL -> {
return "autumn";
}
}
return "null";
}
}

View File

@@ -1,18 +0,0 @@
package net.momirealms.customfishing.hook.skill;
import com.willfp.ecoskills.api.EcoSkillsAPI;
import com.willfp.ecoskills.skills.Skills;
import org.bukkit.entity.Player;
public class EcoSkill implements SkillXP {
@Override
public void addXp(Player player, double amount) {
EcoSkillsAPI.getInstance().giveSkillExperience(player, Skills.FISHING, amount);
}
@Override
public int getLevel(Player player) {
return EcoSkillsAPI.getInstance().getSkillLevel(player, Skills.FISHING);
}
}

View File

@@ -1,44 +0,0 @@
package net.momirealms.customfishing.hook.skill;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.Job;
import com.gamingmesh.jobs.container.JobProgression;
import com.gamingmesh.jobs.container.JobsPlayer;
import org.bukkit.entity.Player;
import java.util.List;
public class JobsReborn implements SkillXP{
@Override
public void addXp(Player player, double amount) {
JobsPlayer jobsPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
if (jobsPlayer != null) {
List<JobProgression> jobs = jobsPlayer.getJobProgression();
Job job = Jobs.getJob("Fisherman");
for (JobProgression progression : jobs)
if (progression.getJob().equals(job)){
progression.addExperience(amount);
}
}
}
@Override
public int getLevel(Player player) {
JobsPlayer jobsPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
if (jobsPlayer != null) {
List<JobProgression> jobs = jobsPlayer.getJobProgression();
Job job = Jobs.getJob("Fisherman");
for (JobProgression progression : jobs)
if (progression.getJob().equals(job))
return progression.getLevel();
}
return 0;
}
}

View File

@@ -0,0 +1,13 @@
package net.momirealms.customfishing.integration;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.jetbrains.annotations.Nullable;
public interface BlockInterface {
void removeBlock(Block block);
void placeBlock(String id, Location location);
@Nullable
String getID(Block block);
}

View File

@@ -0,0 +1,11 @@
package net.momirealms.customfishing.integration;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public interface ItemInterface {
@Nullable
ItemStack build(String id);
}

View File

@@ -0,0 +1,8 @@
package net.momirealms.customfishing.integration;
import net.momirealms.customfishing.object.loot.Mob;
import org.bukkit.Location;
public interface MobInterface {
void summon(Location playerLoc, Location summonLoc, Mob mob);
}

View File

@@ -1,7 +1,8 @@
package net.momirealms.customfishing.hook.season;
package net.momirealms.customfishing.integration;
import org.bukkit.World;
public interface SeasonInterface {
String getSeason(World world);
}

View File

@@ -0,0 +1,9 @@
package net.momirealms.customfishing.integration;
import org.bukkit.entity.Player;
public interface SkillInterface {
void addXp(Player player, double amount);
int getLevel(Player player);
}

View File

@@ -0,0 +1,27 @@
package net.momirealms.customfishing.integration.block;
import dev.lone.itemsadder.api.CustomBlock;
import net.momirealms.customfishing.integration.BlockInterface;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.jetbrains.annotations.Nullable;
public class ItemsAdderBlockHook implements BlockInterface {
@Override
public void removeBlock(Block block) {
CustomBlock.remove(block.getLocation());
}
@Override
public void placeBlock(String id, Location location) {
CustomBlock.place(id, location);
}
@Override
@Nullable
public String getID(Block block) {
CustomBlock customBlock = CustomBlock.byAlreadyPlaced(block);
return customBlock == null ? null : customBlock.getNamespacedID();
}
}

View File

@@ -0,0 +1,31 @@
package net.momirealms.customfishing.integration.block;
import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanic;
import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanicFactory;
import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanicListener;
import net.momirealms.customfishing.integration.BlockInterface;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.jetbrains.annotations.Nullable;
public class OraxenBlockHook implements BlockInterface {
@Override
public void removeBlock(Block block) {
block.setType(Material.AIR);
}
@Override
public void placeBlock(String id, Location location) {
NoteBlockMechanicFactory.setBlockModel(location.getBlock(), id);
}
@Nullable
@Override
public String getID(Block block) {
NoteBlockMechanic mechanic = NoteBlockMechanicListener.getNoteBlockMechanic(block);
if (mechanic == null) return null;
else return mechanic.getItemID();
}
}

View File

@@ -0,0 +1,16 @@
package net.momirealms.customfishing.integration.item;
import net.momirealms.customfishing.integration.ItemInterface;
import net.momirealms.customfishing.manager.LootManager;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public class CustomFishingItemHook implements ItemInterface {
@Override
@Nullable
public ItemStack build(String material) {
if (material.contains(":")) return null;
return LootManager.build(material);
}
}

View File

@@ -1,22 +1,22 @@
package net.momirealms.customfishing.hook;
package net.momirealms.customfishing.integration.item;
import com.willfp.eco.core.items.CustomItem;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTItem;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.manager.BonusManager;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataType;
import java.util.Map;
public class EcoItemRegister {
public class EcoItemHook {
public static void registerItems() {
// Rods
for (Map.Entry<String, ItemStack> entry : ConfigReader.RodItem.entrySet()) {
for (Map.Entry<String, ItemStack> entry : BonusManager.RODITEMS.entrySet()) {
new CustomItem(
new NamespacedKey(CustomFishing.instance, "rod_" + entry.getKey()),
new NamespacedKey(CustomFishing.plugin, "rod_" + entry.getKey()),
itemStack -> {
try {
NBTItem nbtItem = new NBTItem(itemStack);
@@ -32,9 +32,9 @@ public class EcoItemRegister {
).register();
}
// Baits
for (Map.Entry<String, ItemStack> entry : ConfigReader.BaitItem.entrySet()) {
for (Map.Entry<String, ItemStack> entry : BonusManager.BAITITEMS.entrySet()) {
new CustomItem(
new NamespacedKey(CustomFishing.instance, "bait_" + entry.getKey()),
new NamespacedKey(CustomFishing.plugin, "bait_" + entry.getKey()),
itemStack -> {
try {
NBTItem nbtItem = new NBTItem(itemStack);
@@ -50,9 +50,9 @@ public class EcoItemRegister {
).register();
}
// Utils
for (Map.Entry<String, ItemStack> entry : ConfigReader.UtilItem.entrySet()) {
for (Map.Entry<String, ItemStack> entry : BonusManager.UTILITEMS.entrySet()) {
new CustomItem(
new NamespacedKey(CustomFishing.instance, "util_" + entry.getKey()),
new NamespacedKey(CustomFishing.plugin, "util_" + entry.getKey()),
itemStack -> {
try {
NBTItem nbtItem = new NBTItem(itemStack);

View File

@@ -0,0 +1,18 @@
package net.momirealms.customfishing.integration.item;
import dev.lone.itemsadder.api.CustomStack;
import net.momirealms.customfishing.integration.ItemInterface;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public class ItemsAdderItemHook implements ItemInterface {
@Override
@Nullable
public ItemStack build(String material) {
if (!material.startsWith("ItemsAdder:")) return null;
material = material.substring(11);
CustomStack customStack = CustomStack.getInstance(material);
return customStack == null ? null : customStack.getItemStack();
}
}

View File

@@ -0,0 +1,22 @@
package net.momirealms.customfishing.integration.item;
import net.Indyuce.mmoitems.MMOItems;
import net.Indyuce.mmoitems.api.Type;
import net.Indyuce.mmoitems.api.item.mmoitem.MMOItem;
import net.momirealms.customfishing.integration.ItemInterface;
import org.apache.commons.lang.StringUtils;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public class MMOItemsItemHook implements ItemInterface {
@Nullable
@Override
public ItemStack build(String material) {
if (!material.startsWith("MMOItems:")) return null;
material = material.substring(9);
String[] split = StringUtils.split(material, ":");
MMOItem mmoItem = MMOItems.plugin.getMMOItem(Type.get(split[0]), split[1]);
return mmoItem == null ? null : mmoItem.newBuilder().getItemStack();
}
}

View File

@@ -1,4 +1,4 @@
package net.momirealms.customfishing.hook;
package net.momirealms.customfishing.integration.item;
import com.gmail.nossr50.config.treasure.FishingTreasureConfig;
import com.gmail.nossr50.datatypes.skills.SubSkillType;
@@ -20,14 +20,13 @@ import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class McMMOTreasure {
/*
these codes are partly from mcMMO, because of the cancelled event limitation
Plugin has to get the loot in a raw way
*/
public static ItemStack getTreasure(Player player){
FishingManager fishingManager = UserManager.getPlayer(player).getFishingManager();
FishingTreasure treasure = getFishingTreasure(player, fishingManager.getLootTier());
@@ -65,97 +64,67 @@ public class McMMOTreasure {
private static Map<Enchantment, Integer> processMagicHunter(@NotNull ItemStack treasureDrop, int tier) {
Map<Enchantment, Integer> enchants = new HashMap<>();
List<EnchantmentTreasure> fishingEnchantments = null;
double diceRoll = Misc.getRandom().nextDouble() * 100;
for (Rarity rarity : Rarity.values()) {
double dropRate = FishingTreasureConfig.getInstance().getEnchantmentDropRate(tier, rarity);
if (diceRoll <= dropRate) {
if (treasureDrop.getType() == Material.ENCHANTED_BOOK) {
diceRoll = dropRate + 1;
continue;
}
fishingEnchantments = FishingTreasureConfig.getInstance().fishingEnchantments.get(rarity);
break;
}
diceRoll -= dropRate;
}
if (fishingEnchantments == null) {
return enchants;
}
Collections.shuffle(fishingEnchantments, Misc.getRandom());
int specificChance = 1;
for (EnchantmentTreasure enchantmentTreasure : fishingEnchantments) {
Enchantment possibleEnchantment = enchantmentTreasure.getEnchantment();
if (treasureDrop.getItemMeta().hasConflictingEnchant(possibleEnchantment) || Misc.getRandom().nextInt(specificChance) != 0) {
continue;
}
enchants.put(possibleEnchantment, enchantmentTreasure.getLevel());
specificChance *= 2;
}
return enchants;
}
private static @Nullable FishingTreasure getFishingTreasure(Player player, int tier) {
double diceRoll = Misc.getRandom().nextDouble() * 100;
int luck;
if (player.getInventory().getItemInMainHand().getType() == Material.FISHING_ROD) {
luck = player.getInventory().getItemInMainHand().getEnchantmentLevel(Enchantment.LUCK);
}
else {
luck = player.getInventory().getItemInOffHand().getEnchantmentLevel(Enchantment.LUCK);
}
diceRoll *= (1.0 - luck * mcMMO.p.getGeneralConfig().getFishingLureModifier() / 100);
FishingTreasure treasure = null;
for (Rarity rarity : Rarity.values()) {
double dropRate = FishingTreasureConfig.getInstance().getItemDropRate(tier, rarity);
if (diceRoll <= dropRate) {
List<FishingTreasure> fishingTreasures = FishingTreasureConfig.getInstance().fishingRewards.get(rarity);
if (fishingTreasures.isEmpty()) {
return null;
}
treasure = fishingTreasures.get(Misc.getRandom().nextInt(fishingTreasures.size()));
break;
}
diceRoll -= dropRate;
}
if (treasure == null) {
return null;
}
ItemStack treasureDrop = treasure.getDrop().clone();
short maxDurability = treasureDrop.getType().getMaxDurability();
if (maxDurability > 0) {
treasureDrop.setDurability((short) (Misc.getRandom().nextInt(maxDurability)));
}
treasure.setDrop(treasureDrop);
return treasure;
}
}

View File

@@ -0,0 +1,24 @@
package net.momirealms.customfishing.integration.item;
import io.lumine.mythic.bukkit.MythicBukkit;
import io.lumine.mythic.core.items.ItemExecutor;
import net.momirealms.customfishing.integration.ItemInterface;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public class MythicMobsItemHook implements ItemInterface {
private final ItemExecutor itemManager;
public MythicMobsItemHook() {
this.itemManager = MythicBukkit.inst().getItemManager();
}
@Override
@Nullable
public ItemStack build(String material) {
if (!material.startsWith("MythicMobs:")) return null;
material = material.substring(11);
return itemManager.getItemStack(material);
}
}

View File

@@ -0,0 +1,19 @@
package net.momirealms.customfishing.integration.item;
import io.th0rgal.oraxen.items.ItemBuilder;
import io.th0rgal.oraxen.items.OraxenItems;
import net.momirealms.customfishing.integration.ItemInterface;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public class OraxenItemHook implements ItemInterface {
@Override
@Nullable
public ItemStack build(String material) {
if (!material.startsWith("Oraxen:")) return null;
material = material.substring(7);
ItemBuilder itemBuilder = OraxenItems.getItemById(material);
return itemBuilder == null ? null : itemBuilder.build();
}
}

View File

@@ -0,0 +1,40 @@
package net.momirealms.customfishing.integration.mob;
import io.lumine.mythic.api.adapters.AbstractLocation;
import io.lumine.mythic.api.adapters.AbstractVector;
import io.lumine.mythic.api.mobs.MobManager;
import io.lumine.mythic.api.mobs.MythicMob;
import io.lumine.mythic.bukkit.MythicBukkit;
import io.lumine.mythic.bukkit.utils.serialize.Position;
import io.lumine.mythic.core.mobs.ActiveMob;
import net.momirealms.customfishing.integration.MobInterface;
import net.momirealms.customfishing.object.MobVector;
import net.momirealms.customfishing.object.loot.Mob;
import org.bukkit.Location;
import org.bukkit.util.Vector;
import java.util.Optional;
public class MythicMobsMobHook implements MobInterface {
private final MobManager mobManager;
public MythicMobsMobHook() {
this.mobManager = MythicBukkit.inst().getMobManager();
}
@Override
public void summon(Location playerLoc, Location summonLoc, Mob mob){
Optional<MythicMob> mythicMob = mobManager.getMythicMob(mob.getMobID());
if (mythicMob.isPresent()) {
MythicMob theMob = mythicMob.get();
Position position = Position.of(summonLoc);
AbstractLocation abstractLocation = new AbstractLocation(position);
ActiveMob activeMob = theMob.spawn(abstractLocation, mob.getMobLevel());
MobVector mobVector = mob.getMobVector();
Vector vector = playerLoc.subtract(summonLoc).toVector().multiply((mobVector.horizontal()) - 1);
vector = vector.setY((vector.getY() + 0.2) * mobVector.vertical());
activeMob.getEntity().setVelocity(new AbstractVector(vector.getX(), vector.getY(), vector.getZ()));
}
}
}

View File

@@ -0,0 +1,34 @@
package net.momirealms.customfishing.integration.papi;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class CompetitionPapi extends PlaceholderExpansion {
@Override
public @NotNull String getIdentifier() {
return "competition";
}
@Override
public @NotNull String getAuthor() {
return "XiaoMoMi";
}
@Override
public @NotNull String getVersion() {
return "1.2";
}
@Override
public boolean persist() {
return true;
}
@Override
public @Nullable String onPlaceholderRequest(Player player, @NotNull String params) {
return super.onPlaceholderRequest(player, params);
}
}

View File

@@ -0,0 +1,49 @@
package net.momirealms.customfishing.integration.papi;
import me.clip.placeholderapi.PlaceholderAPI;
import net.momirealms.customfishing.Function;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PlaceholderManager extends Function {
private final Pattern placeholderPattern = Pattern.compile("%([^%]*)%");
private final CompetitionPapi competitionPapi;
public PlaceholderManager() {
this.competitionPapi = new CompetitionPapi();
load();
}
public String parse(Player player, String text) {
return PlaceholderAPI.setPlaceholders(player, text);
}
public String parse(OfflinePlayer offlinePlayer, String text) {
return PlaceholderAPI.setPlaceholders(offlinePlayer, text);
}
@Override
public void load() {
competitionPapi.register();
}
@Override
public void unload() {
if (this.competitionPapi != null) competitionPapi.unregister();
}
public List<String> detectPlaceholders(String text){
if (text == null || !text.contains("%")) return Collections.emptyList();
List<String> placeholders = new ArrayList<>();
Matcher matcher = placeholderPattern.matcher(text);
while (matcher.find()) placeholders.add(matcher.group());
return placeholders;
}
}

View File

@@ -0,0 +1,4 @@
package net.momirealms.customfishing.integration.season;
public class CustomCropsSeasonImpl {
}

View File

@@ -0,0 +1,13 @@
package net.momirealms.customfishing.integration.season;
import me.casperge.realisticseasons.api.SeasonsAPI;
import net.momirealms.customfishing.integration.SeasonInterface;
import org.bukkit.World;
public class RealisticSeasonsImpl implements SeasonInterface {
@Override
public String getSeason(World world) {
return SeasonsAPI.getInstance().getSeason(world).toString();
}
}

View File

@@ -15,17 +15,23 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.hook.skill;
package net.momirealms.customfishing.integration.skill;
import com.archyx.aureliumskills.api.AureliumAPI;
import com.archyx.aureliumskills.leveler.Leveler;
import com.archyx.aureliumskills.skills.Skill;
import net.momirealms.customfishing.integration.SkillInterface;
import org.bukkit.entity.Player;
public class Aurelium implements SkillXP{
public class AureliumsHook implements SkillInterface {
private static final Leveler leveler = AureliumAPI.getPlugin().getLeveler();
private static final Skill skill = AureliumAPI.getPlugin().getSkillRegistry().getSkill("fishing");
private final Leveler leveler;
private final Skill skill;
public AureliumsHook() {
leveler = AureliumAPI.getPlugin().getLeveler();
skill = AureliumAPI.getPlugin().getSkillRegistry().getSkill("fishing");
}
@Override
public void addXp(Player player, double amount) {

View File

@@ -15,22 +15,28 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.hook.skill;
package net.momirealms.customfishing.integration.skill;
import net.Indyuce.mmocore.experience.EXPSource;
import net.Indyuce.mmocore.experience.Profession;
import com.willfp.ecoskills.api.EcoSkillsAPI;
import com.willfp.ecoskills.skills.Skills;
import net.momirealms.customfishing.integration.SkillInterface;
import org.bukkit.entity.Player;
public class MMOCore implements SkillXP{
public class EcoSkillsHook implements SkillInterface {
public EcoSkillsAPI ecoSkillsAPI;
public EcoSkillsHook() {
ecoSkillsAPI = EcoSkillsAPI.getInstance();
}
@Override
public void addXp(Player player, double amount) {
Profession profession = net.Indyuce.mmocore.MMOCore.plugin.professionManager.get("fishing");
profession.giveExperience(net.Indyuce.mmocore.MMOCore.plugin.dataProvider.getDataManager().get(player), amount, null , EXPSource.OTHER);
ecoSkillsAPI.giveSkillExperience(player, Skills.FARMING, amount);
}
@Override
public int getLevel(Player player) {
return net.Indyuce.mmocore.MMOCore.plugin.dataProvider.getDataManager().get(player).getLevel();
return ecoSkillsAPI.getSkillLevel(player, Skills.FISHING);
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.integration.skill;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.PlayerManager;
import com.gamingmesh.jobs.container.Job;
import com.gamingmesh.jobs.container.JobProgression;
import com.gamingmesh.jobs.container.JobsPlayer;
import net.momirealms.customfishing.integration.SkillInterface;
import org.bukkit.entity.Player;
import java.util.List;
public class JobsRebornHook implements SkillInterface {
private final PlayerManager playerManager;
public JobsRebornHook() {
this.playerManager = Jobs.getPlayerManager();
}
@Override
public void addXp(Player player, double amount) {
JobsPlayer jobsPlayer = playerManager.getJobsPlayer(player);
if (jobsPlayer != null) {
List<JobProgression> jobs = jobsPlayer.getJobProgression();
Job job = Jobs.getJob("Fisherman");
for (JobProgression progression : jobs)
if (progression.getJob().equals(job))
progression.addExperience(amount);
}
}
@Override
public int getLevel(Player player) {
JobsPlayer jobsPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
if (jobsPlayer != null) {
List<JobProgression> jobs = jobsPlayer.getJobProgression();
Job job = Jobs.getJob("Fisherman");
for (JobProgression progression : jobs)
if (progression.getJob().equals(job))
return progression.getLevel();
}
return 0;
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.integration.skill;
import net.Indyuce.mmocore.MMOCore;
import net.Indyuce.mmocore.experience.EXPSource;
import net.Indyuce.mmocore.experience.Profession;
import net.Indyuce.mmocore.manager.data.PlayerDataManager;
import net.momirealms.customfishing.integration.SkillInterface;
import org.bukkit.entity.Player;
public class MMOCoreHook implements SkillInterface {
private final Profession profession;
private final PlayerDataManager playerDataManager;
public MMOCoreHook() {
profession = MMOCore.plugin.professionManager.get("fishing");
playerDataManager = MMOCore.plugin.dataProvider.getDataManager();
}
@Override
public void addXp(Player player, double amount) {
profession.giveExperience(playerDataManager.get(player), amount, null ,EXPSource.OTHER);
}
@Override
public int getLevel(Player player) {
return playerDataManager.get(player).getLevel();
}
}

View File

@@ -15,13 +15,14 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.hook.skill;
package net.momirealms.customfishing.integration.skill;
import com.gmail.nossr50.api.ExperienceAPI;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import net.momirealms.customfishing.integration.SkillInterface;
import org.bukkit.entity.Player;
public class mcMMO implements SkillXP{
public class mcMMOHook implements SkillInterface {
@Override
public void addXp(Player player, double amount) {

View File

@@ -0,0 +1,20 @@
package net.momirealms.customfishing.listener;
import net.momirealms.customfishing.manager.FishingManager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
public class InteractListener implements Listener {
private final FishingManager fishingManager;
public InteractListener(FishingManager fishingManager) {
this.fishingManager = fishingManager;
}
@EventHandler
public void onInteract(PlayerInteractEvent event) {
fishingManager.onInteract(event);
}
}

View File

@@ -6,10 +6,10 @@ import com.gamingmesh.jobs.container.Job;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class JobsListener implements Listener {
public class JobsRebornXPListener implements Listener {
@EventHandler
public void onExpAdd(JobsExpGainEvent event){
public void onXpGain(JobsExpGainEvent event) {
Job job = Jobs.getJob("Fisherman");
if (event.getJob().equals(job)){
event.setExp(0);

View File

@@ -1,84 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.listener;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTItem;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import java.util.HashMap;
public class MMOItemsConverter implements Listener {
private final HashMap<Player, Long> coolDown = new HashMap<>();
@EventHandler
public void onFish(PlayerFishEvent event){
if (event.getState() == PlayerFishEvent.State.FISHING){
Player player = event.getPlayer();
long time = System.currentTimeMillis();
if (time - (coolDown.getOrDefault(player, time - 5000)) < 5000) {
return;
}
coolDown.put(player, time);
PlayerInventory inventory = player.getInventory();
ItemStack mainHand = inventory.getItemInMainHand();
if(mainHand.getType() == Material.FISHING_ROD){
NBTItem nbtItem = new NBTItem(mainHand);
if (nbtItem.getCompound("CustomFishing") == null) {
if (!nbtItem.getString("MMOITEMS_ITEM_ID").equals("")){
NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing");
nbtCompound.setString("type","rod");
nbtCompound.setString("id",nbtItem.getString("MMOITEMS_ITEM_ID"));
mainHand.setItemMeta(nbtItem.getItem().getItemMeta());
}
}
}
ItemStack offHand = inventory.getItemInOffHand();
if(offHand.getType() == Material.FISHING_ROD){
NBTItem nbtItem = new NBTItem(offHand);
if (nbtItem.getCompound("CustomFishing") == null) {
if (!nbtItem.getString("MMOITEMS_ITEM_ID").equals("")){
NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing");
nbtCompound.setString("type", "rod");
nbtCompound.setString("id", nbtItem.getString("MMOITEMS_ITEM_ID"));
offHand.setItemMeta(nbtItem.getItem().getItemMeta());
}
}
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event){
coolDown.remove(event.getPlayer());
}
}

View File

@@ -1,84 +1,15 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* 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 <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.listener;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTItem;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import net.momirealms.customfishing.manager.FishingManager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import java.util.HashMap;
public class MMOItemsListener implements Listener {
private final HashMap<Player, Long> coolDown = new HashMap<>();
public record MMOItemsListener(FishingManager manager) implements Listener {
@EventHandler
public void onFish(PlayerFishEvent event) {
if (event.getState() == PlayerFishEvent.State.FISHING){
Player player = event.getPlayer();
long time = System.currentTimeMillis();
if (time - (coolDown.getOrDefault(player, time - 5000)) < 5000) {
return;
}
coolDown.put(player, time);
PlayerInventory inventory = player.getInventory();
ItemStack mainHand = inventory.getItemInMainHand();
if(mainHand.getType() == Material.FISHING_ROD){
NBTItem nbtItem = new NBTItem(mainHand);
if (nbtItem.getCompound("CustomFishing") == null) {
if (!nbtItem.getString("MMOITEMS_ITEM_ID").equals("")){
NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing");
nbtCompound.setString("type","rod");
nbtCompound.setString("id",nbtItem.getString("MMOITEMS_ITEM_ID"));
mainHand.setItemMeta(nbtItem.getItem().getItemMeta());
}
}
}
ItemStack offHand = inventory.getItemInOffHand();
if(offHand.getType() == Material.FISHING_ROD){
NBTItem nbtItem = new NBTItem(offHand);
if (nbtItem.getCompound("CustomFishing") == null) {
if (!nbtItem.getString("MMOITEMS_ITEM_ID").equals("")){
NBTCompound nbtCompound = nbtItem.addCompound("CustomFishing");
nbtCompound.setString("type", "rod");
nbtCompound.setString("id", nbtItem.getString("MMOITEMS_ITEM_ID"));
offHand.setItemMeta(nbtItem.getItem().getItemMeta());
}
}
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event){
coolDown.remove(event.getPlayer());
if (event.getState() != PlayerFishEvent.State.FISHING) return;
manager.onMMOItemsRodCast(event);
}
}

View File

@@ -1,17 +0,0 @@
package net.momirealms.customfishing.listener;
import net.momirealms.customfishing.CustomFishing;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class PapiUnregister implements Listener {
@EventHandler
public void onReload(me.clip.placeholderapi.events.ExpansionUnregisterEvent event){
if (CustomFishing.placeholders != null){
if (event.getExpansion().equals(CustomFishing.placeholders)){
CustomFishing.placeholders.register();
}
}
}
}

View File

@@ -15,7 +15,7 @@ public class PickUpListener implements Listener {
public void onPickUp(PlayerAttemptPickupItemEvent event){
ItemStack itemStack = event.getItem().getItemStack();
NBTItem nbtItem = new NBTItem(itemStack);
if (nbtItem.hasKey("M_Owner")){
if (!nbtItem.hasKey("M_Owner")) return;
if (!Objects.equals(nbtItem.getString("M_Owner"), event.getPlayer().getName())){
event.setCancelled(true);
}
@@ -24,15 +24,13 @@ public class PickUpListener implements Listener {
itemStack.setItemMeta(nbtItem.getItem().getItemMeta());
}
}
}
@EventHandler
public void onMove(InventoryPickupItemEvent event){
ItemStack itemStack = event.getItem().getItemStack();
NBTItem nbtItem = new NBTItem(itemStack);
if (nbtItem.hasKey("M_Owner")){
if (!nbtItem.hasKey("M_Owner")) return;
nbtItem.removeKey("M_Owner");
itemStack.setItemMeta(nbtItem.getItem().getItemMeta());
}
}
}

View File

@@ -0,0 +1,62 @@
package net.momirealms.customfishing.listener;
import net.momirealms.customfishing.manager.ConfigManager;
import net.momirealms.customfishing.manager.FishingManager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerFishEvent;
public record PlayerFishListener(
FishingManager manager) implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void onFishMONITOR(PlayerFishEvent event) {
if (!ConfigManager.priority.equals("MONITOR")) return;
selectState(event);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onFishHIGHEST(PlayerFishEvent event) {
if (!ConfigManager.priority.equals("HIGHEST")) return;
selectState(event);
}
@EventHandler(priority = EventPriority.HIGH)
public void onFishHIGH(PlayerFishEvent event) {
if (!ConfigManager.priority.equals("HIGH")) return;
selectState(event);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onFishNORMAL(PlayerFishEvent event) {
if (!ConfigManager.priority.equals("NORMAL")) return;
selectState(event);
}
@EventHandler(priority = EventPriority.LOW)
public void onFishLOW(PlayerFishEvent event) {
if (!ConfigManager.priority.equals("LOW")) return;
selectState(event);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onFishLOWEST(PlayerFishEvent event) {
if (!ConfigManager.priority.equals("LOWEST")) return;
selectState(event);
}
public void selectState(PlayerFishEvent event) {
if (event.isCancelled()) return;
if (!ConfigManager.getWorldsList().contains(event.getHook().getLocation().getWorld())) return;
switch (event.getState()) {
case FISHING -> manager.onFishing(event);
case REEL_IN -> manager.onReelIn(event);
case CAUGHT_ENTITY -> manager.onCaughtEntity(event);
case CAUGHT_FISH -> manager.onCaughtFish(event);
case FAILED_ATTEMPT -> manager.onFailedAttempt(event);
case BITE -> manager.onBite(event);
case IN_GROUND -> manager.onInGround(event);
}
}
}

View File

@@ -0,0 +1,20 @@
package net.momirealms.customfishing.listener;
import net.momirealms.customfishing.Function;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public record SimpleListener(Function function) implements Listener {
@EventHandler
public void onJoin(PlayerJoinEvent event) {
function.onJoin(event.getPlayer());
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
function.onQuit(event.getPlayer());
}
}

View File

@@ -0,0 +1,201 @@
package net.momirealms.customfishing.manager;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.object.Bonus;
import net.momirealms.customfishing.object.Item;
import net.momirealms.customfishing.object.LeveledEnchantment;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ConfigUtil;
import net.momirealms.customfishing.util.ItemStackUtil;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.util.*;
public class BonusManager {
public static HashMap<String, ItemStack> BAITITEMS;
public static HashMap<String, Bonus> BAIT;
public static HashMap<String, ItemStack> RODITEMS;
public static HashMap<String, Bonus> ROD;
public static HashMap<String, Bonus> ENCHANTS = new HashMap<>();
public static HashMap<String, ItemStack> UTILITEMS;
public static void load() {
BAIT = new HashMap<>();
BAITITEMS = new HashMap<>();
ROD = new HashMap<>();
RODITEMS = new HashMap<>();
ENCHANTS = new HashMap<>();
loadRod();
loadBait();
loadEnchant();
loadUtil();
}
private static void loadUtil() {
UTILITEMS = new HashMap<>();
File util_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "utils");
if (!util_file.exists()) {
if (!util_file.mkdir()) return;
CustomFishing.plugin.saveResource("utils" + File.separator + "fishfinder.yml", false);
CustomFishing.plugin.saveResource("utils" + File.separator + "totem_items.yml", false);
}
File[] files = util_file.listFiles();
if (files == null) return;
for (File file : files) {
YamlConfiguration config = YamlConfiguration.loadConfiguration(file);
Set<String> keys = config.getKeys(false);
for (String key : keys) {
Item item = new Item(Material.valueOf(config.getString(key + ".material", "PAPER").toUpperCase()));
setItemProperties(config, key, item);
UTILITEMS.put(key, ItemStackUtil.addIdentifier(ItemStackUtil.getFromItem(item), "util", key));
}
}
AdventureUtil.consoleMessage("[CustomFishing] Loaded <green>" + UTILITEMS.size() + " <gray>utils");
}
private static void loadEnchant() {
ENCHANTS = new HashMap<>();
YamlConfiguration config = ConfigUtil.getConfig("enchant-bonus.yml");
Set<String> keys = config.getKeys(false);
for (String key : keys) {
config.getConfigurationSection(key).getKeys(false).forEach(level -> {
Bonus bonus = new Bonus();
config.getConfigurationSection(key + "." + level).getKeys(false).forEach(modifier -> {
switch (modifier) {
case "weight-add" -> {
HashMap<String, Integer> pm = new HashMap<>();
config.getConfigurationSection(key + "." + level + ".weight-add").getValues(false).forEach((group, value) -> {
pm.put(group, (Integer) value);
});
bonus.setWeightAS(pm);
}
case "weight-multiply" -> {
HashMap<String, Double> mq = new HashMap<>();
config.getConfigurationSection(key + "." + level + ".weight-multiply").getValues(false).forEach((group, value) -> {
mq.put(group, Double.parseDouble(String.valueOf(value))-1);
});
bonus.setWeightMD(mq);
}
case "time" -> bonus.setTime(config.getDouble(key + "." + level + ".time"));
case "difficulty" -> bonus.setDifficulty(config.getInt(key + "." + level + ".difficulty"));
case "double-loot" -> bonus.setDoubleLoot(config.getDouble(key + "." + level + ".double-loot"));
case "score" -> bonus.setScore(config.getDouble(key + "." + level + ".score"));
}
});
ENCHANTS.put(key + ":" + level, bonus);
});
}
AdventureUtil.consoleMessage("[CustomFishing] Loaded <green>" + ENCHANTS.size() + " <gray>enchantments");
}
private static void loadBait() {
BAITITEMS = new HashMap<>();
BAIT = new HashMap<>();
File bait_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "baits");
if (!bait_file.exists()) {
if (!bait_file.mkdir()) return;
CustomFishing.plugin.saveResource("baits" + File.separator + "default.yml", false);
}
File[] files = bait_file.listFiles();
if (files == null) return;
for (File file : files) {
YamlConfiguration config = YamlConfiguration.loadConfiguration(file);
Set<String> keys = config.getKeys(false);
for (String key : keys) {
Item item = new Item(Material.valueOf(config.getString(key + ".material", "PAPER").toUpperCase()));
setItemProperties(config, key, item);
BAITITEMS.put(key, ItemStackUtil.addIdentifier(ItemStackUtil.getFromItem(item), "bait", key));
if (config.contains(key + ".modifier")) {
BAIT.put(key, getBonus(config, key));
}
}
}
AdventureUtil.consoleMessage("[CustomFishing] Loaded <green>" + BAITITEMS.size() + " <gray>baits");
}
private static Bonus getBonus(YamlConfiguration config, String key) {
Bonus bonus = new Bonus();
config.getConfigurationSection(key + ".modifier").getKeys(false).forEach(modifier -> {
switch (modifier) {
case "weight-add" -> {
HashMap<String, Integer> as = new HashMap<>();
config.getConfigurationSection(key + ".modifier.weight-add").getValues(false).forEach((group, value) -> {
as.put(group, (Integer) value);
});
bonus.setWeightAS(as);
}
case "weight-multiply" -> {
HashMap<String, Double> md = new HashMap<>();
config.getConfigurationSection(key + ".modifier.weight-multiply").getValues(false).forEach((group, value) -> {
md.put(group, Double.parseDouble(String.valueOf(value))-1);
});
bonus.setWeightMD(md);
}
case "time" -> bonus.setTime(config.getDouble(key + ".modifier.time"));
case "difficulty" -> bonus.setDifficulty(config.getInt(key + ".modifier.difficulty"));
case "double-loot" -> bonus.setDoubleLoot(config.getDouble(key + ".modifier.double-loot"));
case "score" -> bonus.setScore(config.getDouble(key + ".modifier.score"));
}
});
return bonus;
}
private static void loadRod() {
ROD = new HashMap<>();
RODITEMS = new HashMap<>();
File rod_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "rods");
if (!rod_file.exists()) {
if (!rod_file.mkdir()) return;
CustomFishing.plugin.saveResource("rods" + File.separator + "default.yml", false);
}
File[] files = rod_file.listFiles();
if (files == null) return;
for (File file : files) {
YamlConfiguration config = YamlConfiguration.loadConfiguration(file);
Set<String> keys = config.getKeys(false);
for (String key : keys) {
Item item = new Item(Material.FISHING_ROD);
setItemProperties(config, key, item);
RODITEMS.put(key, ItemStackUtil.addIdentifier(ItemStackUtil.getFromItem(item), "rod", key));
if (config.contains(key + ".modifier")) {
ROD.put(key, getBonus(config, key));
}
}
}
AdventureUtil.consoleMessage("[CustomFishing] Loaded <green>" + RODITEMS.size() + " <gray>rods");
}
public static void setItemProperties(YamlConfiguration config, String key, Item item) {
item.setUnbreakable(config.getBoolean(key + ".unbreakable", false));
if (config.contains(key + ".display.lore")) item.setLore(config.getStringList(key + ".display.lore"));
if (config.contains(key + ".display.name")) item.setName(config.getString(key + ".display.name"));
if (config.contains(key + ".custom-model-data")) item.setCustomModelData(config.getInt(key + ".custom-model-data"));
if (config.contains(key + ".enchantments")) {
List<LeveledEnchantment> enchantmentList = new ArrayList<>();
config.getConfigurationSection(key + ".enchantments").getKeys(false).forEach(enchant -> {
LeveledEnchantment leveledEnchantment = new LeveledEnchantment(
NamespacedKey.fromString(enchant),
config.getInt(key + ".enchantments." + enchant)
);
enchantmentList.add(leveledEnchantment);
});
item.setEnchantment(enchantmentList);
}
if (config.contains(key + ".item_flags")) {
ArrayList<ItemFlag> itemFlags = new ArrayList<>();
config.getStringList(key + ".item_flags").forEach(flag -> itemFlags.add(ItemFlag.valueOf(flag)));
item.setItemFlags(itemFlags);
}
if (config.contains(key + ".nbt")) {
Map<String, Object> nbt = config.getConfigurationSection(key + ".nbt").getValues(false);
item.setNbt(nbt);
}
}
}

View File

@@ -0,0 +1,77 @@
package net.momirealms.customfishing.manager;
import net.momirealms.customfishing.Function;
import net.momirealms.customfishing.competition.CompetitionConfig;
import net.momirealms.customfishing.competition.CompetitionGoal;
import net.momirealms.customfishing.competition.bossbar.BossBarConfig;
import net.momirealms.customfishing.competition.bossbar.Overlay;
import net.momirealms.customfishing.object.action.ActionInterface;
import net.momirealms.customfishing.object.action.CommandActionImpl;
import net.momirealms.customfishing.object.action.MessageActionImpl;
import net.momirealms.customfishing.util.ConfigUtil;
import org.bukkit.boss.BarColor;
import org.bukkit.configuration.file.YamlConfiguration;
import org.checkerframework.checker.units.qual.C;
import java.util.*;
public class CompetitionManager extends Function {
public static HashMap<String, CompetitionConfig> competitionsT;
public static HashMap<String, CompetitionConfig> competitionsC;
@Override
public void load() {
competitionsC = new HashMap<>();
competitionsT = new HashMap<>();
if (ConfigManager.enableCompetition) loadCompetitions();
}
@Override
public void unload() {
if (competitionsC != null) competitionsC.clear();
if (competitionsT != null) competitionsT.clear();
}
public void loadCompetitions(){
YamlConfiguration config = ConfigUtil.getConfig("competition.yml");
Set<String> keys = config.getKeys(false);
keys.forEach(key -> {
boolean enableBsb = config.getBoolean(key + ".bossbar.enable", false);
BossBarConfig bossBarConfig = new BossBarConfig(
config.getStringList(key + ".bossbar.text").toArray(new String[0]),
Overlay.valueOf(config.getString(key + ".bossbar.overlay","SOLID").toUpperCase()),
BarColor.valueOf(config.getString(key + ".bossbar.color","WHITE").toUpperCase()),
config.getInt(key + ".bossbar.refresh-rate",10),
config.getInt(key + ".bossbar.switch-interval", 15)
);
HashMap<String, ActionInterface[]> rewardsMap = new HashMap<>();
Objects.requireNonNull(config.getConfigurationSection(key + ".prize")).getKeys(false).forEach(rank -> {
List<ActionInterface> rewards = new ArrayList<>();
if (config.contains(key + ".prize." + rank + ".messages"))
rewards.add(new MessageActionImpl(config.getStringList(key + ".prize." + rank + ".messages").toArray(new String[0]), null));
if (config.contains(key + ".prize." + rank + ".commands"))
rewards.add(new CommandActionImpl(config.getStringList(key + ".prize." + rank + ".commands").toArray(new String[0]), null));
rewardsMap.put(rank, rewards.toArray(new ActionInterface[0]));
});
CompetitionConfig competitionConfig = new CompetitionConfig(
config.getInt(key + ".duration",600),
config.getInt(key + ".min-players",1),
config.getStringList(key + ".broadcast.start"),
config.getStringList(key + ".broadcast.end"),
config.getStringList(key + ".command.start"),
config.getStringList(key + ".command.end"),
config.getStringList(key + ".command.join"),
CompetitionGoal.valueOf(config.getString(key + ".goal", "RANDOM")),
bossBarConfig,
enableBsb,
rewardsMap
);
config.getStringList(key + ".start-time").forEach(time -> competitionsT.put(time, competitionConfig));
competitionsC.put(key, competitionConfig);
});
}
}

View File

@@ -0,0 +1,123 @@
package net.momirealms.customfishing.manager;
import com.gamingmesh.jobs.CMILib.ConfigReader;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ConfigUtil;
import net.momirealms.customfishing.util.JedisUtil;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.configuration.file.YamlConfiguration;
import java.util.ArrayList;
import java.util.List;
public class ConfigManager {
public static World[] worlds;
public static List<World> worldList;
public static boolean whiteOrBlack;
public static String priority;
public static String lang;
public static boolean otherLootBar;
public static boolean enableVanillaLoot;
public static boolean enableMcMMOLoot;
public static double vanillaLootRatio;
public static double mcMMOLootChance;
public static boolean needOpenWater;
public static boolean needRodForLoots;
public static boolean needRodToFish;
public static boolean rodLoseDurability;
public static int fishFinderCoolDown;
public static boolean enableCompetition;
public static boolean disableJobsXp;
public static boolean convertMMOItems;
public static boolean preventPickUp;
public static boolean enableFishingBag;
public static boolean alwaysFishingBar;
public static String[] successTitle;
public static String[] successSubTitle;
public static int successFadeIn;
public static int successFadeStay;
public static int successFadeOut;
public static String[] failureTitle;
public static String[] failureSubTitle;
public static int failureFadeIn;
public static int failureFadeStay;
public static int failureFadeOut;
public static boolean useRedis;
public static void load() {
ConfigUtil.update("config.yml");
YamlConfiguration config = ConfigUtil.getConfig("config.yml");
lang = config.getString("lang","english");
whiteOrBlack = config.getString("worlds.mode","whitelist").equals("whitelist");
List<String> worldsName = config.getStringList("worlds.list");
worlds = new World[worldsName.size()];
for (int i = 0; i < worldsName.size(); i++) {
if (Bukkit.getWorld(worldsName.get(i)) != null) {
worlds[i] = Bukkit.getWorld(worldsName.get(i));
}
}
worldList = new ArrayList<>();
for (World world : worlds) {
if (world == null) continue;
worldList.add(world);
}
worlds = worldList.toArray(new World[0]);
alwaysFishingBar = config.getBoolean("mechanics.other-loots.fishing-bar", true);
otherLootBar = config.getBoolean("mechanics.other-loots.fishing-bar", true);
enableVanillaLoot = config.getBoolean("mechanics.other-loots.vanilla.enable", true);
vanillaLootRatio = config.getDouble("mechanics.other-loots.vanilla.ratio", 0.4);
enableMcMMOLoot = config.getBoolean("mechanics.other-loots.mcMMO.enable", false);
mcMMOLootChance = config.getDouble("mechanics.other-loots.mcMMO.chance", 0.5);
needOpenWater = config.getBoolean("mechanics.need-open-water", true);
needRodForLoots = config.getBoolean("mechanics.need-special-rod.for-loots", false);
needRodToFish = config.getBoolean("mechanics.need-special-rod.to-fish", false);
rodLoseDurability = config.getBoolean("mechanics.rod-lose-durability", true);
fishFinderCoolDown = config.getInt("mechanics.fishfinder-cooldown", 3000);
enableCompetition = config.getBoolean("mechanics.fishing-competition", true);
priority = config.getString("other-settings.event-priority", "NORMAL").toUpperCase();
disableJobsXp = config.getBoolean("other-settings.disable-JobsReborn-fishing-exp", false);
preventPickUp = config.getBoolean("other-settings.prevent-other-players-pick-up-loot", false);
convertMMOItems = config.getBoolean("other-settings.convert-MMOItems-rods", false);
successTitle = config.getStringList("titles.success.title").toArray(new String[0]);
successSubTitle = config.getStringList("titles.success.subtitle").toArray(new String[0]);
successFadeIn = config.getInt("titles.success.fade.in", 10) * 50;
successFadeStay = config.getInt("titles.success.fade.stay", 30) * 50;
successFadeOut = config.getInt("titles.success.fade.out", 10) * 50;
failureTitle = config.getStringList("titles.failure.title").toArray(new String[0]);
failureSubTitle = config.getStringList("titles.failure.subtitle").toArray(new String[0]);
failureFadeIn = config.getInt("titles.failure.fade.in", 10) * 50;
failureFadeStay = config.getInt("titles.failure.fade.stay", 30) * 50;
failureFadeOut = config.getInt("titles.failure.fade.out", 10) * 50;
tryEnableJedis();
}
public static List<World> getWorldsList() {
if (whiteOrBlack) {
return worldList;
}
else {
List<World> worldList = new ArrayList<>(Bukkit.getWorlds());
worldList.removeAll(ConfigManager.worldList);
return worldList;
}
}
public static void tryEnableJedis(){
YamlConfiguration configuration = ConfigUtil.getConfig("redis.yml");
useRedis = false;
if (configuration.getBoolean("redis.enable")){
JedisUtil.initializeRedis(configuration);
useRedis = true;
}
}
}

View File

@@ -0,0 +1,757 @@
package net.momirealms.customfishing.manager;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTItem;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.Function;
import net.momirealms.customfishing.api.event.FishFinderEvent;
import net.momirealms.customfishing.api.event.FishHookEvent;
import net.momirealms.customfishing.api.event.FishResultEvent;
import net.momirealms.customfishing.api.event.RodCastEvent;
import net.momirealms.customfishing.integration.MobInterface;
import net.momirealms.customfishing.integration.item.McMMOTreasure;
import net.momirealms.customfishing.listener.*;
import net.momirealms.customfishing.object.*;
import net.momirealms.customfishing.object.action.ActionInterface;
import net.momirealms.customfishing.object.loot.DroppedItem;
import net.momirealms.customfishing.object.loot.Loot;
import net.momirealms.customfishing.object.loot.Mob;
import net.momirealms.customfishing.object.requirements.RequirementInterface;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ItemStackUtil;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.FishHook;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class FishingManager extends Function {
private final PlayerFishListener playerFishListener;
private final InteractListener interactListener;
private PickUpListener pickUpListener;
private MMOItemsListener mmoItemsListener;
private JobsRebornXPListener jobsRebornXPListener;
private final HashMap<Player, Long> coolDown;
private final HashMap<Player, FishHook> hooksCache;
private final HashMap<Player, Loot> nextLoot;
private final HashMap<Player, Bonus> nextBonus;
private final HashMap<Player, VanillaLoot> vanillaLoot;
private final ConcurrentHashMap<Player, FishingPlayer> fishingPlayerCache;
public FishingManager() {
this.playerFishListener = new PlayerFishListener(this);
this.interactListener = new InteractListener(this);
this.coolDown = new HashMap<>();
this.hooksCache = new HashMap<>();
this.nextLoot = new HashMap<>();
this.nextBonus = new HashMap<>();
this.vanillaLoot = new HashMap<>();
this.fishingPlayerCache = new ConcurrentHashMap<>();
load();
}
@Override
public void load() {
Bukkit.getPluginManager().registerEvents(this.playerFishListener, CustomFishing.plugin);
Bukkit.getPluginManager().registerEvents(this.interactListener, CustomFishing.plugin);
if (ConfigManager.preventPickUp) {
this.pickUpListener = new PickUpListener();
Bukkit.getPluginManager().registerEvents(this.pickUpListener, CustomFishing.plugin);
}
if (ConfigManager.convertMMOItems) {
this.mmoItemsListener = new MMOItemsListener(this);
Bukkit.getPluginManager().registerEvents(this.mmoItemsListener, CustomFishing.plugin);
}
if (ConfigManager.disableJobsXp) {
this.jobsRebornXPListener = new JobsRebornXPListener();
Bukkit.getPluginManager().registerEvents(this.jobsRebornXPListener, CustomFishing.plugin);
}
}
@Override
public void unload() {
HandlerList.unregisterAll(this.playerFishListener);
HandlerList.unregisterAll(this.interactListener);
if (this.pickUpListener != null) HandlerList.unregisterAll(this.pickUpListener);
if (this.mmoItemsListener != null) HandlerList.unregisterAll(this.mmoItemsListener);
if (this.jobsRebornXPListener != null) HandlerList.unregisterAll(this.jobsRebornXPListener);
}
public void onFishing(PlayerFishEvent event) {
final Player player = event.getPlayer();
final FishHook fishHook = event.getHook();
hooksCache.put(player, fishHook);
if (isCoolDown(player, 2000)) return;
Bukkit.getScheduler().runTaskAsynchronously(CustomFishing.plugin, () -> {
PlayerInventory inventory = player.getInventory();
boolean noSpecialRod = true;
boolean noRod = true;
boolean noBait = true;
Bonus initialBonus = new Bonus();
initialBonus.setDifficulty(0);
initialBonus.setDoubleLoot(0);
initialBonus.setTime(1);
initialBonus.setScore(1);
initialBonus.setWeightMD(new HashMap<>());
initialBonus.setWeightAS(new HashMap<>());
ItemStack mainHandItem = inventory.getItemInMainHand();
Material mainHandItemType = mainHandItem.getType();
if (mainHandItemType != Material.AIR) {
if (mainHandItemType == Material.FISHING_ROD) {
noRod = false;
enchantBonus(initialBonus, mainHandItem);
}
NBTItem mainHandNBTItem = new NBTItem(mainHandItem);
NBTCompound nbtCompound = mainHandNBTItem.getCompound("CustomFishing");
if (nbtCompound != null) {
if (nbtCompound.getString("type").equals("rod")) {
Bonus rodBonus = BonusManager.ROD.get(nbtCompound.getString("id"));
if (rodBonus != null){
initialBonus.addBonus(rodBonus);
noSpecialRod = false;
}
}
else if (nbtCompound.getString("type").equals("bait")) {
Bonus baitBonus = BonusManager.BAIT.get(nbtCompound.getString("id"));
if (baitBonus != null) {
initialBonus.addBonus(baitBonus);
mainHandItem.setAmount(mainHandItem.getAmount() - 1);
noBait = false;
}
}
}
}
ItemStack offHandItem = inventory.getItemInOffHand();
Material offHandItemType = offHandItem.getType();
if (offHandItemType != Material.AIR){
if (noRod && offHandItemType == Material.FISHING_ROD) {
enchantBonus(initialBonus, offHandItem);
}
NBTItem offHandNBTItem = new NBTItem(offHandItem);
NBTCompound nbtCompound = offHandNBTItem.getCompound("CustomFishing");
if (nbtCompound != null) {
if (noBait && nbtCompound.getString("type").equals("bait")) {
Bonus baitBonus = BonusManager.BAIT.get(nbtCompound.getString("id"));
if (baitBonus != null){
initialBonus.addBonus(baitBonus);
offHandItem.setAmount(offHandItem.getAmount() - 1);
noBait = false;
}
}
else if (noSpecialRod && nbtCompound.getString("type").equals("rod")) {
Bonus rodBonus = BonusManager.ROD.get(nbtCompound.getString("id"));
if (rodBonus != null) {
initialBonus.addBonus(rodBonus);
noSpecialRod = false;
}
}
}
}
if (ConfigManager.enableFishingBag && noBait) {
//育儿袋
}
RodCastEvent rodCastEvent = new RodCastEvent(player, initialBonus);
if (rodCastEvent.isCancelled()) {
event.setCancelled(true);
return;
}
nextBonus.put(player, initialBonus);
List<Loot> possibleLoots = getPossibleLootList(new FishingCondition(fishHook.getLocation(), player), false);
List<Loot> availableLoots = new ArrayList<>();
if (possibleLoots.size() == 0){
nextLoot.put(player, null);
return;
}
if (ConfigManager.needRodForLoots && noSpecialRod){
if (!ConfigManager.enableVanillaLoot) AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.noRod);
nextLoot.put(player, null);
}
if (ConfigManager.needRodToFish && noSpecialRod){
nextLoot.put(player, Loot.EMPTY);
}
if ((ConfigManager.needRodForLoots || ConfigManager.needRodToFish) && noSpecialRod) return;
HashMap<String, Integer> as = initialBonus.getWeightAS();
HashMap<String, Double> md = initialBonus.getWeightMD();
double[] weights = new double[possibleLoots.size()];
int index = 0;
for (Loot loot : possibleLoots){
double weight = loot.getWeight();
String group = loot.getGroup();
if (group != null){
if (as.get(group) != null){
weight += as.get(group);
}
if (md.get(group) != null){
weight *= md.get(group);
}
}
if (weight <= 0) continue;
availableLoots.add(loot);
weights[index++] = weight;
}
double total = Arrays.stream(weights).sum();
double[] weightRatios = new double[index];
for (int i = 0; i < index; i++){
weightRatios[i] = weights[i]/total;
}
double[] weightRange = new double[index];
double startPos = 0;
for (int i = 0; i < index; i++) {
weightRange[i] = startPos + weightRatios[i];
startPos += weightRatios[i];
}
double random = Math.random();
int pos = Arrays.binarySearch(weightRange, random);
if (pos < 0) {
pos = -pos - 1;
}
if (pos < weightRange.length && random < weightRange[pos]) {
nextLoot.put(player, availableLoots.get(pos));
return;
}
nextLoot.put(player, null);
});
}
public void onCaughtFish(PlayerFishEvent event) {
final Player player = event.getPlayer();
if (!(event.getCaught() instanceof Item item)) return;
FishingPlayer fishingPlayer = fishingPlayerCache.remove(player);
if (fishingPlayer == null) {
if (ConfigManager.enableVanillaLoot) {
// Not a vanilla loot
if (ConfigManager.vanillaLootRatio < Math.random()) {
event.setCancelled(true);
Loot loot = nextLoot.get(player);
if (loot != null) {
vanillaLoot.remove(player);
}
else {
vanillaLoot.put(player, new VanillaLoot(item.getItemStack(), event.getExpToDrop()));
}
showPlayerBar(player, loot);
}
// Is vanilla loot
else {
if (ConfigManager.alwaysFishingBar) {
event.setCancelled(true);
vanillaLoot.put(player, new VanillaLoot(item.getItemStack(), event.getExpToDrop()));
showPlayerBar(player, null);
}
//else vanilla fishing mechanic
}
}
else {
// No custom loot
Loot loot = nextLoot.get(player);
if (loot == null) {
item.remove();
event.setExpToDrop(0);
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.noLoot);
}
else {
event.setCancelled(true);
showPlayerBar(player, loot);
}
}
}
else {
item.remove();
event.setExpToDrop(0);
proceedReelIn(event, player, fishingPlayer);
}
}
private void proceedReelIn(PlayerFishEvent event, Player player, FishingPlayer fishingPlayer) {
fishingPlayer.cancel();
Loot loot = nextLoot.remove(player);
VanillaLoot vanilla = vanillaLoot.remove(player);
player.removePotionEffect(PotionEffectType.SLOW);
if (ConfigManager.needOpenWater && !event.getHook().isInOpenWater()){
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.notOpenWater);
return;
}
if (fishingPlayer.isSuccess()) {
if (ConfigManager.rodLoseDurability) loseDurability(player);
Location location = event.getHook().getLocation();
if (vanilla != null) {
dropVanillaLoot(player, vanilla, location, fishingPlayer.isDouble());
return;
}
if (loot instanceof Mob mob) {
summonMob(player, loot, location, mob);
return;
}
if (loot instanceof DroppedItem droppedItem){
if (ConfigManager.enableMcMMOLoot && Math.random() < ConfigManager.mcMMOLootChance){
if (dropMcMMOLoot(player, location, fishingPlayer.isDouble())){
return;
}
}
dropCustomFishingLoot(player, location, droppedItem, fishingPlayer.isDouble());
}
}
else {
fail(player, loot, vanilla != null);
}
}
public void onReelIn(PlayerFishEvent event) {
final Player player = event.getPlayer();
FishingPlayer fishingPlayer = fishingPlayerCache.remove(player);
if (fishingPlayer == null) return;
proceedReelIn(event, player, fishingPlayer);
}
private void dropCustomFishingLoot(Player player, Location location, DroppedItem droppedItem, boolean isDouble) {
ItemStack drop = getCustomFishingLootItemStack(droppedItem, player);
FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_LOOT, isDouble, drop);
Bukkit.getPluginManager().callEvent(fishResultEvent);
if (fishResultEvent.isCancelled()) {
return;
}
dropItem(player, location, fishResultEvent.isDouble(), drop);
for (ActionInterface action : droppedItem.getSuccessActions())
action.doOn(player);
sendSuccessTitle(player, droppedItem.getNick());
}
private ItemStack getCustomFishingLootItemStack(DroppedItem droppedItem, Player player) {
String key = droppedItem.getMaterial();
ItemStack drop = CustomFishing.plugin.getIntegrationManager().build(key);
if (drop.getType() != Material.AIR) {
if (droppedItem.getRandomEnchants() != null)
ItemStackUtil.addRandomEnchants(drop, droppedItem.getRandomEnchants());
if (droppedItem.isRandomDurability())
ItemStackUtil.addRandomDamage(drop);
if (ConfigManager.preventPickUp)
ItemStackUtil.addOwner(drop, player.getName());
}
return drop;
}
private boolean dropMcMMOLoot(Player player, Location location, boolean isDouble) {
ItemStack itemStack = McMMOTreasure.getTreasure(player);
if (itemStack == null) return false;
FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_VANILLA, isDouble, itemStack);
Bukkit.getPluginManager().callEvent(fishResultEvent);
if (fishResultEvent.isCancelled()) {
return true;
}
player.giveExp(new Random().nextInt(24), true);
dropItem(player, location, fishResultEvent.isDouble(), itemStack);
sendSuccessTitle(player, itemStack);
return true;
}
private void dropItem(Player player, Location location, boolean isDouble, ItemStack itemStack) {
if (itemStack.getType() == Material.AIR) return;
Entity item = location.getWorld().dropItem(location, itemStack);
Vector vector = player.getLocation().subtract(location).toVector().multiply(0.1);
vector = vector.setY((vector.getY()+0.2) * 1.2);
item.setVelocity(vector);
if (isDouble){
Entity item2 = location.getWorld().dropItem(location, itemStack);
item2.setVelocity(vector);
}
}
private void dropVanillaLoot(Player player, VanillaLoot vanillaLoot, Location location, boolean isDouble) {
ItemStack itemStack;
itemStack = vanillaLoot.getItemStack();
if (ConfigManager.enableMcMMOLoot && Math.random() < ConfigManager.mcMMOLootChance){
ItemStack mcMMOItemStack = McMMOTreasure.getTreasure(player);
if (mcMMOItemStack != null){
itemStack = mcMMOItemStack;
}
}
FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_VANILLA, isDouble, itemStack);
Bukkit.getPluginManager().callEvent(fishResultEvent);
if (fishResultEvent.isCancelled()) {
return;
}
player.giveExp(vanillaLoot.getXp(), true);
AdventureUtil.playerSound(player, Sound.Source.PLAYER, Key.key("minecraft:entity.experience_orb.pickup"), 1, 1);
dropItem(player, location, isDouble, itemStack);
sendSuccessTitle(player, itemStack);
}
private void summonMob(Player player, Loot loot, Location location, Mob mob) {
MobInterface mobInterface = CustomFishing.plugin.getIntegrationManager().getMobInterface();
if (mobInterface == null) return;
FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.CAUGHT_MOB, false, null);
if (fishResultEvent.isCancelled()) {
return;
}
mobInterface.summon(player.getLocation(), location, mob);
for (ActionInterface action : loot.getSuccessActions())
action.doOn(player);
sendSuccessTitle(player, loot.getNick());
}
@NotNull
private Component getTitleComponent(ItemStack itemStack, String text) {
Component component;
if (text.contains("{loot}")){
text = text.replace("{loot}","|");
if (text.startsWith("|")){
component = getDisplayName(itemStack).append(MiniMessage.miniMessage().deserialize(text.substring(1)));
}
else if (text.endsWith("|")){
component = MiniMessage.miniMessage().deserialize(text.substring(0,text.length() - 1)).append(getDisplayName(itemStack));
}
else {
String[] titleSplit = StringUtils.split(text, "|");
component = MiniMessage.miniMessage().deserialize(titleSplit[0]).append(getDisplayName(itemStack)).append(MiniMessage.miniMessage().deserialize(titleSplit[1]));
}
}
else {
component = MiniMessage.miniMessage().deserialize(text);
}
return component;
}
private void sendSuccessTitle(Player player, String loot) {
AdventureUtil.playerTitle(
player,
ConfigManager.successTitle[new Random().nextInt(ConfigManager.successTitle.length)]
.replace("{loot}", loot)
.replace("{player}", player.getName()),
ConfigManager.successSubTitle[new Random().nextInt(ConfigManager.successSubTitle.length)]
.replace("{loot}", loot)
.replace("{player}", player.getName()),
ConfigManager.successFadeIn,
ConfigManager.successFadeStay,
ConfigManager.successFadeOut
);
}
private void sendSuccessTitle(Player player, ItemStack itemStack) {
String title = ConfigManager.successTitle[new Random().nextInt(ConfigManager.successTitle.length)];
Component titleComponent = getTitleComponent(itemStack, title);
String subTitle = ConfigManager.successSubTitle[new Random().nextInt(ConfigManager.successSubTitle.length)];
Component subtitleComponent = getTitleComponent(itemStack, subTitle);
AdventureUtil.playerTitle(
player,
titleComponent,
subtitleComponent,
ConfigManager.successFadeIn,
ConfigManager.successFadeStay,
ConfigManager.successFadeOut
);
}
private void loseDurability(Player player) {
if (player.getGameMode() == GameMode.CREATIVE) return;
PlayerInventory inventory = player.getInventory();
ItemStack mainHand = inventory.getItemInMainHand();
if (mainHand.getType() == Material.FISHING_ROD){
setDurability(mainHand);
}
else {
ItemStack offHand = inventory.getItemInOffHand();
if (offHand.getType() == Material.FISHING_ROD){
setDurability(offHand);
}
}
}
private void setDurability(ItemStack rod) {
Damageable damageable = (Damageable) rod.getItemMeta();
if (damageable.isUnbreakable()) return;
Enchantment enchantment = Enchantment.DURABILITY;
if (Math.random() < (1 / (double) (damageable.getEnchantLevel(enchantment) + 1))){
damageable.setDamage(damageable.getDamage() + 1);
Bukkit.getScheduler().runTaskLater(CustomFishing.plugin, () -> rod.setItemMeta(damageable),1);
}
}
private void fail(Player player, Loot loot, boolean isVanilla) {
FishResultEvent fishResultEvent = new FishResultEvent(player, FishResult.FAILURE, false, null);
Bukkit.getServer().getPluginManager().callEvent(fishResultEvent);
if (fishResultEvent.isCancelled()) {
return;
}
if (!isVanilla && loot != null){
for (ActionInterface action : loot.getFailureActions())
action.doOn(player);
}
AdventureUtil.playerTitle(
player,
ConfigManager.failureTitle[new Random().nextInt(ConfigManager.failureTitle.length)],
ConfigManager.failureSubTitle[new Random().nextInt(ConfigManager.failureSubTitle.length)],
ConfigManager.failureFadeIn,
ConfigManager.failureFadeStay,
ConfigManager.failureFadeOut
);
}
public void onCaughtEntity(PlayerFishEvent event) {
final Player player = event.getPlayer();
if (fishingPlayerCache.remove(player) != null && event.getCaught() != null){
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.hookOther);
}
}
public void onFailedAttempt(PlayerFishEvent event) {
//Empty
}
public void onBite(PlayerFishEvent event) {
//Empty
}
public void onInGround(PlayerFishEvent event) {
FishHook fishHook = event.getHook();
Block belowBlock = fishHook.getLocation().clone().subtract(0,1,0).getBlock();
Block inBlock = fishHook.getLocation().getBlock();
if (inBlock.getType() == Material.AIR && belowBlock.getType() == Material.ICE) {
}
else if (inBlock.getType() == Material.LAVA) {
}
}
public void onMMOItemsRodCast(PlayerFishEvent event) {
final Player player = event.getPlayer();
if (isCoolDown(player, 5000)) return;
PlayerInventory inventory = player.getInventory();
setCustomTag(inventory.getItemInMainHand());
setCustomTag(inventory.getItemInOffHand());
}
private void setCustomTag(ItemStack itemStack) {
if(itemStack.getType() != Material.FISHING_ROD) return;
NBTItem nbtItem = new NBTItem(itemStack);
if (nbtItem.getCompound("CustomFishing") != null) return;
if (!nbtItem.hasKey("MMOITEMS_ITEM_ID")) return;
ItemStackUtil.addIdentifier(itemStack, "rod", nbtItem.getString("MMOITEMS_ITEM_ID"));
}
public boolean isCoolDown(Player player, long delay) {
long time = System.currentTimeMillis();
if (time - (coolDown.getOrDefault(player, time - delay)) < delay) return true;
coolDown.put(player, time);
return false;
}
private void enchantBonus(Bonus initialBonus, ItemStack mainHandItem) {
Map<Enchantment, Integer> enchantments = mainHandItem.getEnchantments();
for (Map.Entry<Enchantment, Integer> en : enchantments.entrySet()) {
String key = en.getKey().getKey() + ":" + en.getValue();
Bonus enchantBonus = BonusManager.ENCHANTS.get(key);
if (enchantBonus != null) {
initialBonus.addBonus(enchantBonus);
}
}
}
private List<Loot> getPossibleLootList(FishingCondition fishingCondition, boolean finder) {
List<Loot> available = new ArrayList<>();
outer:
for (Loot loot : LootManager.WATERLOOTS.values()) {
if (finder && !loot.isShowInFinder()) continue;
RequirementInterface[] requirements = loot.getRequirements();
if (requirements == null){
available.add(loot);
}
else {
for (RequirementInterface requirement : requirements){
if (!requirement.isConditionMet(fishingCondition)){
continue outer;
}
}
available.add(loot);
}
}
return available;
}
public void onInteract(PlayerInteractEvent event) {
ItemStack itemStack = event.getItem();
if (itemStack == null || itemStack.getType() == Material.AIR) return;
NBTItem nbtItem = new NBTItem(itemStack);
NBTCompound cfCompound = nbtItem.getCompound("CustomFishing");
if (cfCompound != null && cfCompound.getString("type").equals("util") && cfCompound.getString("id").equals("fishfinder")) {
useFinder(event.getPlayer());
return;
}
Block block = event.getClickedBlock();
if (block == null) return;
String totemID = nbtItem.getString("totem");
if (totemID.equals("")) return;
if (!TotemManager.TOTEMS.containsKey(totemID)) return;
}
private void useFinder(Player player) {
if (isCoolDown(player, ConfigManager.fishFinderCoolDown)) return;
List<Loot> possibleLoots = getPossibleLootList(new FishingCondition(player.getLocation(), player), true);
FishFinderEvent fishFinderEvent = new FishFinderEvent(player, possibleLoots);
Bukkit.getPluginManager().callEvent(fishFinderEvent);
if (fishFinderEvent.isCancelled()) {
return;
}
if (possibleLoots.size() == 0) {
AdventureUtil.playerMessage(player, MessageManager.prefix + MessageManager.noLoot);
return;
}
StringBuilder stringBuilder = new StringBuilder(MessageManager.prefix + MessageManager.possibleLoots);
possibleLoots.forEach(loot -> stringBuilder.append(loot.getNick()).append(MessageManager.splitChar));
AdventureUtil.playerMessage(player, stringBuilder.substring(0, stringBuilder.length() - MessageManager.splitChar.length()));
}
private void showPlayerBar(Player player, @Nullable Loot loot){
Layout layout;
if (loot != null && loot.getLayout() != null){
layout = loot.getLayout()[new Random().nextInt(loot.getLayout().length)];
}
else {
//Not null
layout = LayoutManager.LAYOUTS.values().stream().findAny().get();
}
int speed;
int timer;
int time;
if (loot != null){
speed = loot.getDifficulty().speed();
timer = loot.getDifficulty().timer();
time = loot.getTime();
}
else {
speed = new Random().nextInt(5);
time = 10000;
timer = 1;
}
Bonus bonus = nextBonus.get(player);
boolean isDouble =false;
if (bonus != null) {
speed += bonus.getDifficulty();
isDouble = Math.random() < bonus.getDoubleLoot();
}
if (speed < 1){
speed = 1;
}
Difficulty difficult = new Difficulty(timer, speed);
FishHookEvent fishHookEvent = new FishHookEvent(player, difficult);
Bukkit.getPluginManager().callEvent(fishHookEvent);
if (fishHookEvent.isCancelled()) {
return;
}
FishingPlayer fishingPlayer = new FishingPlayer(System.currentTimeMillis() + time, player, layout, difficult, this, isDouble);
fishingPlayer.runTaskTimerAsynchronously(CustomFishing.plugin, 0, 1);
fishingPlayerCache.put(player, fishingPlayer);
if (vanillaLoot.get(player) == null && loot != null){
for (ActionInterface action : loot.getHookActions()) {
action.doOn(player);
}
}
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, time/50,3));
}
@Override
public void onQuit(Player player) {
coolDown.remove(player);
nextLoot.remove(player);
nextBonus.remove(player);
vanillaLoot.remove(player);
// prevent bar duplication
FishHook fishHook = hooksCache.remove(player);
if (fishHook != null) fishHook.remove();
}
@Nullable
public FishingPlayer getFishingPlayer(Player player) {
return fishingPlayerCache.get(player);
}
public void removeFishingPlayer(Player player) {
fishingPlayerCache.remove(player);
}
private Component getDisplayName(ItemStack itemStack){
NBTItem nbtItem = new NBTItem(itemStack);
NBTCompound nbtCompound = nbtItem.getCompound("display");
if (nbtCompound != null){
String name = nbtCompound.getString("Name");
if (!name.equals("")){
return GsonComponentSerializer.gson().deserialize(name);
}
}
String type = itemStack.getType().toString().toLowerCase();
if (itemStack.getType().isBlock()) return GsonComponentSerializer.gson().deserialize("{\"translate\":\"block.minecraft." + type + "\"}");
else return GsonComponentSerializer.gson().deserialize("{\"translate\":\"item.minecraft." + type + "\"}");
}
}

View File

@@ -0,0 +1,144 @@
package net.momirealms.customfishing.manager;
import net.momirealms.customfishing.Function;
import net.momirealms.customfishing.integration.ItemInterface;
import net.momirealms.customfishing.integration.MobInterface;
import net.momirealms.customfishing.integration.SeasonInterface;
import net.momirealms.customfishing.integration.SkillInterface;
import net.momirealms.customfishing.integration.item.*;
import net.momirealms.customfishing.integration.mob.MythicMobsMobHook;
import net.momirealms.customfishing.integration.papi.PlaceholderManager;
import net.momirealms.customfishing.integration.season.RealisticSeasonsImpl;
import net.momirealms.customfishing.integration.skill.*;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ConfigUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class IntegrationManager extends Function {
private SeasonInterface seasonInterface;
private SkillInterface skillInterface;
private ItemInterface[] itemInterfaces;
private MobInterface mobInterface;
private PlaceholderManager placeholderManager;
public IntegrationManager() {
load();
}
@Override
public void load() {
PluginManager pluginManager = Bukkit.getPluginManager();
if (this.placeholderManager != null) {
this.placeholderManager.unload();
}
if (pluginManager.getPlugin("PlaceholderAPI") != null) {
this.placeholderManager = new PlaceholderManager();
}
List<ItemInterface> itemInterfaceList = new ArrayList<>();
itemInterfaceList.add(new CustomFishingItemHook());
if (pluginManager.getPlugin("ItemsAdder") != null) itemInterfaceList.add(new ItemsAdderItemHook());
if (pluginManager.getPlugin("Oraxen") != null) itemInterfaceList.add(new OraxenItemHook());
if (pluginManager.getPlugin("MMOItems") != null) itemInterfaceList.add(new MMOItemsItemHook());
if (pluginManager.getPlugin("MythicMobs") != null) {
itemInterfaceList.add(new MythicMobsItemHook());
this.mobInterface = new MythicMobsMobHook();
}
this.itemInterfaces = itemInterfaceList.toArray(new ItemInterface[0]);
if (pluginManager.getPlugin("eco") != null) {
EcoItemHook.registerItems();
}
YamlConfiguration config = ConfigUtil.getConfig("config.yml");
if (config.getBoolean("integration.RealisticSeasons", false) && pluginManager.getPlugin("RealisticSeasons") != null) {
this.seasonInterface = new RealisticSeasonsImpl();
hookMessage("RealisticSeasons");
} else if (config.getBoolean("integration.CustomCrops", false) && pluginManager.getPlugin("CustomCrops") != null) {
//TODO
this.seasonInterface = null;
hookMessage("CustomCrops");
}
if (config.getBoolean("integration.mcMMO", false) && Bukkit.getPluginManager().getPlugin("mcMMO") != null) {
this.skillInterface = new mcMMOHook();
hookMessage("mcMMO");
} else if (config.getBoolean("integration.MMOCore", false) && Bukkit.getPluginManager().getPlugin("MMOCore") != null) {
this.skillInterface = new MMOCoreHook();
hookMessage("MMOCore");
} else if (config.getBoolean("integration.AureliumSkills", false) && Bukkit.getPluginManager().getPlugin("AureliumSkills") != null) {
this.skillInterface = new AureliumsHook();
hookMessage("AureliumSkills");
} else if (config.getBoolean("integration.EcoSkills", false) && Bukkit.getPluginManager().getPlugin("EcoSkills") != null) {
this.skillInterface = new EcoSkillsHook();
hookMessage("EcoSkills");
} else if (config.getBoolean("integration.JobsReborn", false) && Bukkit.getPluginManager().getPlugin("Jobs") != null) {
this.skillInterface = new JobsRebornHook();
hookMessage("JobsReborn");
}
}
@Override
public void unload() {
this.seasonInterface = null;
this.skillInterface = null;
this.itemInterfaces = null;
this.mobInterface = null;
if (this.placeholderManager != null) {
this.placeholderManager.unload();
this.placeholderManager = null;
}
}
@Nullable
public SeasonInterface getSeasonInterface() {
return seasonInterface;
}
@Nullable
public SkillInterface getSkillInterface() {
return skillInterface;
}
@NotNull
public ItemInterface[] getItemInterfaces() {
return itemInterfaces;
}
@Nullable
public MobInterface getMobInterface() {
return mobInterface;
}
@Nullable
public PlaceholderManager getPlaceholderManager() {
return placeholderManager;
}
@NotNull
public ItemStack build(String key) {
for (ItemInterface itemInterface : itemInterfaces) {
ItemStack itemStack = itemInterface.build(key);
if (itemStack != null) {
return itemStack;
}
}
return new ItemStack(Material.AIR);
}
private void hookMessage(String plugin){
AdventureUtil.consoleMessage("[CustomFishing] <white>" + plugin + " Hooked!");
}
}

View File

@@ -0,0 +1,41 @@
package net.momirealms.customfishing.manager;
import net.momirealms.customfishing.object.Layout;
import net.momirealms.customfishing.util.ConfigUtil;
import org.bukkit.configuration.file.YamlConfiguration;
import java.util.HashMap;
import java.util.Objects;
import java.util.Set;
public class LayoutManager {
public static HashMap<String, Layout> LAYOUTS;
public static void load() {
LAYOUTS = new HashMap<>();
YamlConfiguration config = ConfigUtil.getConfig("bars.yml");
Set<String> keys = config.getKeys(false);
for (String key : keys) {
int range = config.getInt(key + ".range");
Set<String> rates = Objects.requireNonNull(config.getConfigurationSection(key + ".layout")).getKeys(false);
double[] successRate = new double[rates.size()];
for(int i = 0; i < rates.size(); i++)
successRate[i] = config.getDouble(key + ".layout." + (i + 1));
int size = rates.size() * range - 1;
Layout layout = new Layout(
range,
successRate,
size,
config.getString(key + ".subtitle.start","<font:customfishing:default>"),
config.getString(key + ".subtitle.bar",""),
config.getString(key + ".subtitle.pointer",""),
config.getString(key + ".subtitle.offset",""),
config.getString(key + ".subtitle.end","</font>"),
config.getString(key + ".subtitle.pointer_offset",""),
config.getString(key + ".title"," ")
);
LAYOUTS.put(key, layout);
}
}
}

View File

@@ -0,0 +1,215 @@
package net.momirealms.customfishing.manager;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.object.*;
import net.momirealms.customfishing.object.action.*;
import net.momirealms.customfishing.object.loot.DroppedItem;
import net.momirealms.customfishing.object.loot.Loot;
import net.momirealms.customfishing.object.loot.Mob;
import net.momirealms.customfishing.object.requirements.*;
import net.momirealms.customfishing.util.AdventureUtil;
import net.momirealms.customfishing.util.ItemStackUtil;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
public class LootManager {
public static HashMap<String, Loot> WATERLOOTS;
public static HashMap<String, Loot> LAVALOOTS;
public static HashMap<String, ItemStack> LOOTITEMS;
@Nullable
public static Loot getLoot(String key) {
return WATERLOOTS.get(key);
}
@Nullable
public static ItemStack build(String key) {
ItemStack itemStack = LOOTITEMS.get(key);
return itemStack == null ? null : itemStack.clone();
}
public static void load() {
WATERLOOTS = new HashMap<>();
LAVALOOTS = new HashMap<>();
LOOTITEMS = new HashMap<>();
loadItems();
loadMobs();
AdventureUtil.consoleMessage("[CustomFishing] Loaded <green>" + (LAVALOOTS.size() + WATERLOOTS.size()) + " <gray>loots");
}
private static void loadMobs() {
if (Bukkit.getPluginManager().getPlugin("MythicMobs") == null) return;
File mob_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "mobs");
if (!mob_file.exists()) {
if (!mob_file.mkdir()) return;
CustomFishing.plugin.saveResource("mobs" + File.separator + "example.yml", false);
}
File[] files = mob_file.listFiles();
if (files == null) return;
for (File file : files) {
YamlConfiguration config = YamlConfiguration.loadConfiguration(file);
Set<String> keys = config.getKeys(false);
for (String key : keys) {
if (!config.getBoolean(key + ".enable", true)) continue;
// Bar mechanic
String[] diff = StringUtils.split(config.getString(key + ".difficulty", "1-1"),"-");
Difficulty difficulty = new Difficulty(Integer.parseInt(diff[0]), Integer.parseInt(diff[1]));
int weight = config.getInt(key + ".weight",10);
int time = config.getInt(key + ".time",10000);
Mob loot = new Mob(
key,
difficulty,
time,
weight,
config.getString(key + ".mythicmobsID", key),
config.getInt(key + ".level", 0),
new MobVector(
config.getDouble(key + ".vector.horizontal",1.1),
config.getDouble(key + ".vector.vertical",1.3)
));
if (config.contains(key + ".nick")) loot.setNick(config.getString(key + ".nick"));
else loot.setNick(ChatColor.stripColor(config.getString(key + ".mythicmobsID", key)));
setActionsAndRequirements(config, loot, key);
WATERLOOTS.put(key, loot);
}
}
}
private static void loadItems() {
File loot_file = new File(CustomFishing.plugin.getDataFolder() + File.separator + "loots");
if (!loot_file.exists()) {
if (!loot_file.mkdir()) return;
CustomFishing.plugin.saveResource("loots" + File.separator + "default.yml", false);
CustomFishing.plugin.saveResource("loots" + File.separator + "example.yml", false);
}
File[] files = loot_file.listFiles();
if (files == null) return;
for (File file : files) {
YamlConfiguration config = YamlConfiguration.loadConfiguration(file);
Set<String> keys = config.getKeys(false);
for (String key : keys) {
if (!config.getBoolean(key + ".enable", true)) continue;
String material = config.getString(key + ".material","COD");
// Bar mechanic
String[] diff = StringUtils.split(config.getString(key + ".difficulty", "1-1"),"-");
Difficulty difficulty = new Difficulty(Integer.parseInt(diff[0]), Integer.parseInt(diff[1]));
int weight = config.getInt(key + ".weight",10);
int time = config.getInt(key + ".time",10000);
DroppedItem loot = new DroppedItem(
key,
difficulty,
time,
weight,
material.contains(":") ? material : key);
// Set nick
if (config.contains(key + ".nick")) loot.setNick(config.getString(key + ".nick"));
else loot.setNick(ChatColor.stripColor(config.getString(key + ".display.name", key)));
loot.setRandomDurability(config.getBoolean(key + ".random-durability", false));
if (config.contains(key + ".random-enchantments")){
List<LeveledEnchantment> randomEnchants = new ArrayList<>();
config.getConfigurationSection(key + ".random-enchantments").getValues(false).forEach((order, enchant) -> {
if (enchant instanceof MemorySection memorySection){
LeveledEnchantment enchantment = new LeveledEnchantment(NamespacedKey.fromString(memorySection.getString("enchant")), memorySection.getInt("level"));
enchantment.setChance(memorySection.getDouble("chance"));
randomEnchants.add(enchantment);
}
});
loot.setRandomEnchants(randomEnchants.toArray(new LeveledEnchantment[0]));
}
setActionsAndRequirements(config, loot, key);
if (config.getBoolean(key + ".in-lava", false)) {
LAVALOOTS.put(key, loot);
} else {
WATERLOOTS.put(key, loot);
}
// Construct ItemStack
if (material.contains(":")) {
continue;
}
Item item = new Item(Material.valueOf(material.toUpperCase()));
BonusManager.setItemProperties(config, key, item);
if (item.getMaterial() == Material.AIR) LOOTITEMS.put(key, new ItemStack(Material.AIR));
else LOOTITEMS.put(key, ItemStackUtil.getFromItem(item));
}
}
}
private static void setActionsAndRequirements(YamlConfiguration config, Loot loot, String key) {
if (config.contains(key + ".layout")) {
List<Layout> layoutList = new ArrayList<>();
for (String layoutName : config.getStringList(key + ".layout")) {
Layout layout = LayoutManager.LAYOUTS.get(layoutName);
if (layout == null) {
AdventureUtil.consoleMessage("<red>[CustomFishing] Bar " + layoutName + " doesn't exist");
continue;
}
layoutList.add(layout);
}
loot.setLayout(layoutList.toArray(new Layout[0]));
}
loot.setScore(config.getDouble(key + ".score", 0));
loot.setShowInFinder(config.getBoolean(key + ".show-in-fishfinder", true));
if (config.contains(key + ".group")) loot.setGroup(config.getString(key + ".group"));
// Set actions
List<ActionInterface> successActions = new ArrayList<>();
if (config.contains(key + ".action.success.message")) successActions.add(new MessageActionImpl(config.getStringList(key + ".action.success.message").toArray(new String[0]), loot.getNick()));
if (config.contains(key + ".action.success.command")) successActions.add(new CommandActionImpl(config.getStringList(key + ".action.success.command").toArray(new String[0]), loot.getNick()));
if (config.contains(key + ".action.success.exp")) successActions.add(new VanillaXPImpl(config.getInt(key + ".action.success.exp"), false));
if (config.contains(key + ".action.success.mending")) successActions.add(new VanillaXPImpl(config.getInt(key + ".action.success.mending"), true));
if (config.contains(key + ".action.success.skill-xp")) successActions.add(new SkillXPImpl(config.getInt(key + ".action.success.skill-xp")));
if (config.contains(key + ".action.success.sound")) successActions.add(new SoundActionImpl(config.getString(key + ".action.success.sound")));
loot.setSuccessActions(successActions.toArray(new ActionInterface[0]));
List<ActionInterface> failureActions = new ArrayList<>();
if (config.contains(key + ".action.failure.message")) failureActions.add(new MessageActionImpl(config.getStringList(key + ".action.failure.message").toArray(new String[0]), loot.getNick()));
if (config.contains(key + ".action.failure.command")) failureActions.add(new CommandActionImpl(config.getStringList(key + ".action.failure.command").toArray(new String[0]), loot.getNick()));
if (config.contains(key + ".action.failure.exp")) failureActions.add(new VanillaXPImpl(config.getInt(key + ".action.failure.exp"), false));
if (config.contains(key + ".action.failure.mending")) failureActions.add(new VanillaXPImpl(config.getInt(key + ".action.failure.mending"), true));
if (config.contains(key + ".action.failure.skill-xp")) failureActions.add(new SkillXPImpl(config.getInt(key + ".action.failure.skill-xp")));
if (config.contains(key + ".action.failure.sound")) failureActions.add(new SoundActionImpl(config.getString(key + ".action.failure.sound")));
loot.setFailureActions(failureActions.toArray(new ActionInterface[0]));
List<ActionInterface> hookActions = new ArrayList<>();
if (config.contains(key + ".action.hook.message")) hookActions.add(new MessageActionImpl(config.getStringList(key + ".action.hook.message").toArray(new String[0]), loot.getNick()));
if (config.contains(key + ".action.hook.command")) hookActions.add(new CommandActionImpl(config.getStringList(key + ".action.hook.command").toArray(new String[0]), loot.getNick()));
if (config.contains(key + ".action.hook.exp")) hookActions.add(new VanillaXPImpl(config.getInt(key + ".action.hook.exp"), false));
if (config.contains(key + ".action.hook.mending")) hookActions.add(new VanillaXPImpl(config.getInt(key + ".action.hook.mending"), true));
if (config.contains(key + ".action.hook.skill-xp")) hookActions.add(new SkillXPImpl(config.getInt(key + ".action.hook.skill-xp")));
if (config.contains(key + ".action.hook.sound")) hookActions.add(new SoundActionImpl(config.getString(key + ".action.hook.sound")));
loot.setHookActions(hookActions.toArray(new ActionInterface[0]));
if (config.contains(key + ".requirements")){
List<RequirementInterface> requirements = new ArrayList<>();
config.getConfigurationSection(key + ".requirements").getKeys(false).forEach(requirement -> {
switch (requirement){
case "weather" -> requirements.add(new WeatherImpl(config.getStringList(key + ".requirements.weather")));
case "ypos" -> requirements.add(new YPosImpl(config.getStringList(key + ".requirements.ypos")));
case "season" -> requirements.add(new SeasonImpl(config.getStringList(key + ".requirements.season")));
case "world" -> requirements.add(new WorldImpl(config.getStringList(key + ".requirements.world")));
case "biome" -> requirements.add(new BiomeImpl(config.getStringList(key + ".requirements.biome")));
case "permission" -> requirements.add(new PermissionImpl(config.getString(key + ".requirements.permission")));
case "time" -> requirements.add(new TimeImpl(config.getStringList(key + ".requirements.time")));
case "skill-level" -> requirements.add(new SkillLevelImpl(config.getInt(key + ".requirements.skill-level")));
case "papi-condition" -> requirements.add(new CustomPapi(config.getConfigurationSection(key + ".requirements.papi-condition").getValues(false)));
}
});
loot.setRequirements(requirements.toArray(new RequirementInterface[0]));
}
}
}

View File

@@ -0,0 +1,72 @@
package net.momirealms.customfishing.manager;
import net.momirealms.customfishing.util.ConfigUtil;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
public class MessageManager {
public static String prefix;
public static String reload;
public static String nonArgs;
public static String unavailableArgs;
public static String escape;
public static String noPerm;
public static String notExist;
public static String noConsole;
public static String wrongAmount;
public static String lackArgs;
public static String notOnline;
public static String giveItem;
public static String getItem;
public static String coolDown;
public static String possibleLoots;
public static String splitChar;
public static String noLoot;
public static String notOpenWater;
public static String competitionOn;
public static String notEnoughPlayers;
public static String noRank;
public static String forceSuccess;
public static String forceFailure;
public static String forceEnd;
public static String forceCancel;
public static String noPlayer;
public static String noScore;
public static String noRod;
public static String hookOther;
public static void load() {
YamlConfiguration config = ConfigUtil.getConfig("messages" + File.separator + "messages_" + ConfigManager.lang +".yml");
prefix = config.getString("messages.prefix", "messages.prefix is missing");
reload = config.getString("messages.reload", "messages.reload is missing");
nonArgs = config.getString("messages.none-args", "messages.none-args is missing");
unavailableArgs = config.getString("messages.none-args", "messages.invalid-args is missing");
escape = config.getString("messages.escape", "messages.escape is missing");
noPerm = config.getString("messages.no-perm", "messages.no-perm is missing");
notExist = config.getString("messages.not-exist", "messages.not-exist is missing");
noConsole = config.getString("messages.no-console", "messages.no-console is missing");
wrongAmount = config.getString("messages.wrong-amount", "messages.wrong-amount is missing");
lackArgs = config.getString("messages.lack-args", "messages.lack-args is missing");
notOnline = config.getString("messages.not-online", "messages.not-online is missing");
giveItem = config.getString("messages.give-item", "messages.give-item is missing");
getItem = config.getString("messages.get-item", "messages.get-item is missing");
coolDown = config.getString("messages.cooldown", "messages.cooldown is missing");
possibleLoots = config.getString("messages.possible-loots", "messages.possible-loots is missing");
splitChar = config.getString("messages.split-char", "messages.split-char is missing");
noLoot = config.getString("messages.no-loot", "messages.no-loot is missing");
notOpenWater = config.getString("messages.not-open-water", "messages.not-open-water is missing");
competitionOn = config.getString("messages.competition-ongoing", "messages.competition-ongoing is missing");
notEnoughPlayers = config.getString("messages.players-not-enough", "messages.players-not-enough is missing");
noRank = config.getString("messages.no-rank", "messages.no-rank is missing");
forceSuccess = config.getString("messages.force-competition-success", "messages.force-competition-success is missing");
forceFailure = config.getString("messages.force-competition-failure", "messages.force-competition-failure is missing");
forceEnd = config.getString("messages.force-competition-end", "messages.force-competition-end is missing");
forceCancel = config.getString("messages.force-competition-cancel","messages.force-competition-cancel is messing");
noPlayer = config.getString("messages.no-player", "messages.no-player is missing");
noScore = config.getString("messages.no-score", "messages.no-score is missing");
noRod = config.getString("messages.no-rod", "messages.no-rod is missing");
hookOther = config.getString("messages.hook-other-entity","messages.hook-other-entity is missing");
}
}

View File

@@ -0,0 +1,9 @@
package net.momirealms.customfishing.manager;
import java.util.HashMap;
public class TotemManager {
public static HashMap<String, String> TOTEMS;
}

View File

@@ -1,30 +1,32 @@
package net.momirealms.customfishing.object;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class Bonus {
private HashMap<String, Double> weightMQ;
private HashMap<String, Integer> weightPM;
private HashMap<String, Double> weightMD;
private HashMap<String, Integer> weightAS;
private double time;
private double score;
private int difficulty;
private double doubleLoot;
public HashMap<String, Double> getWeightMQ() {
return weightMQ;
public HashMap<String, Double> getWeightMD() {
return weightMD;
}
public void setWeightMQ(HashMap<String, Double> weightMQ) {
this.weightMQ = weightMQ;
public void setWeightMD(HashMap<String, Double> weightMD) {
this.weightMD = weightMD;
}
public HashMap<String, Integer> getWeightPM() {
return weightPM;
public HashMap<String, Integer> getWeightAS() {
return weightAS;
}
public void setWeightPM(HashMap<String, Integer> weightPM) {
this.weightPM = weightPM;
public void setWeightAS(HashMap<String, Integer> weightAS) {
this.weightAS = weightAS;
}
public double getTime() {
@@ -58,4 +60,25 @@ public class Bonus {
public void setDoubleLoot(double doubleLoot) {
this.doubleLoot = doubleLoot;
}
public void addBonus(Bonus anotherBonus) {
HashMap<String, Integer> weightAS = anotherBonus.getWeightAS();
if (weightAS != null){
for (Map.Entry<String, Integer> en : weightAS.entrySet()) {
String group = en.getKey();
this.weightAS.put(group, Optional.ofNullable(this.weightAS.get(group)).orElse(0) + en.getValue());
}
}
HashMap<String, Double> weightMD = anotherBonus.getWeightMD();
if (weightMD != null){
for (Map.Entry<String, Double> en : weightMD.entrySet()) {
String group = en.getKey();
this.weightMD.put(group, Optional.ofNullable(this.weightMD.get(group)).orElse(1d) + en.getValue());
}
}
if (anotherBonus.getTime() != 0) this.time *= anotherBonus.getTime();
if (anotherBonus.getDoubleLoot() != 0) this.doubleLoot += anotherBonus.getDoubleLoot();
if (anotherBonus.getDifficulty() != 0) this.difficulty += anotherBonus.getDifficulty();
if (anotherBonus.getScore() != 0) this.score *= anotherBonus.getScore();
}
}

View File

@@ -19,11 +19,13 @@ package net.momirealms.customfishing.object;
public record Difficulty(int timer, int speed) {
public int getTimer() {
return this.timer;
@Override
public int timer() {
return timer;
}
public int getSpeed() {
return this.speed;
@Override
public int speed() {
return speed;
}
}

View File

@@ -0,0 +1,9 @@
package net.momirealms.customfishing.object;
public enum FishResult {
FAILURE,
CAUGHT_MOB,
CAUGHT_LOOT,
CAUGHT_VANILLA
}

View File

@@ -15,10 +15,11 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.requirements;
package net.momirealms.customfishing.object;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.hook.PapiHook;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.integration.papi.PlaceholderManager;
import net.momirealms.customfishing.object.requirements.CustomPapi;
import org.bukkit.Location;
import org.bukkit.entity.Player;
@@ -33,11 +34,12 @@ public class FishingCondition{
public FishingCondition(Location location, Player player) {
this.location = location;
this.player = player;
if (ConfigReader.Config.papi){
PlaceholderManager placeholderManager = CustomFishing.plugin.getIntegrationManager().getPlaceholderManager();
if (placeholderManager != null) {
this.papiMap = new HashMap<>();
CustomPapi.allPapi.forEach(papi -> {
this.papiMap.put(papi, PapiHook.parse(player, papi));
});
for (String papi : CustomPapi.allPapi) {
this.papiMap.put(papi, placeholderManager.parse(player, papi));
}
}
}

Some files were not shown because too many files have changed in this diff Show More