9
0
mirror of https://github.com/Xiao-MoMi/Custom-Fishing.git synced 2025-12-29 03:49:07 +00:00

1.0-SNAPSHOT

This commit is contained in:
Xiao-MoMi
2022-07-05 15:43:36 +08:00
parent 0938696c28
commit ba6d42f102
38 changed files with 2655 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
package net.momirealms.customfishing;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.title.Title;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.time.Duration;
public class AdventureManager {
public static void consoleMessage(String s) {
Audience au = CustomFishing.adventure.sender(Bukkit.getConsoleSender());
MiniMessage mm = MiniMessage.miniMessage();
Component parsed = mm.deserialize(s);
au.sendMessage(parsed);
}
public static void playerMessage(Player player, String s) {
Audience au = CustomFishing.adventure.player(player);
MiniMessage mm = MiniMessage.miniMessage();
Component parsed = mm.deserialize(s);
au.sendMessage(parsed);
}
public static void playerTitle(Player player, String s1, String s2, int in, int duration, int out) {
Audience au = CustomFishing.adventure.player(player);
MiniMessage mm = MiniMessage.miniMessage();
Title.Times times = Title.Times.times(Duration.ofMillis(in), Duration.ofMillis(duration), Duration.ofMillis(out));
Title title = Title.title(mm.deserialize(s1), mm.deserialize(s2), times);
au.showTitle(title);
}
}

View File

@@ -0,0 +1,491 @@
package net.momirealms.customfishing;
import net.momirealms.customfishing.requirements.*;
import net.momirealms.customfishing.utils.*;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.util.*;
public class ConfigReader{
public static HashMap<String, LootInstance> LOOT = new HashMap<>();
public static HashMap<String, ItemStack> LOOTITEM = new HashMap<>();
public static HashMap<String, UtilInstance> UTIL = new HashMap<>();
public static HashMap<String, ItemStack> UTILITEM = new HashMap<>();
public static HashMap<String, LayoutUtil> LAYOUT = new HashMap<>();
private static YamlConfiguration getConfig(String configName) {
File file = new File(CustomFishing.instance.getDataFolder(), configName);
if (!file.exists()) {
CustomFishing.instance.saveResource(configName, false);
}
return YamlConfiguration.loadConfiguration(file);
}
public static void Reload() {
Config.loadConfig();
Message.loadMessage();
Title.loadTitle();
loadLoot();
loadUtil();
}
public static class Config {
public static boolean wg;
public static boolean mm;
public static boolean papi;
public static boolean season;
public static boolean vanillaDrop;
public static boolean needOpenWater;
public static String season_papi;
public static int fishFinderCoolDown;
public static void loadConfig() {
CustomFishing.instance.saveDefaultConfig();
CustomFishing.instance.reloadConfig();
FileConfiguration config = CustomFishing.instance.getConfig();
wg = config.getBoolean("config.integrations.WorldGuard");
if (wg){
if (Bukkit.getPluginManager().getPlugin("WorldGuard") == null){
AdventureManager.consoleMessage("<red>[CustomFishing] 未检测到 WorldGuard!</red>");
wg = false;
}else {
AdventureManager.consoleMessage("<gradient:#0070B3:#A0EACF>[CustomFishing] </gradient><green>WorldGuard Hooked!");
}
}
mm = config.getBoolean("config.integrations.MythicMobs");
if (mm){
if (Bukkit.getPluginManager().getPlugin("MythicMobs") == null){
AdventureManager.consoleMessage("<red>[CustomFishing] 未检测到 MythicMobs!</red>");
mm = false;
}else {
AdventureManager.consoleMessage("<gradient:#0070B3:#A0EACF>[CustomFishing] </gradient><green>MythicMobs Hooked!");
}
}
papi = config.getBoolean("config.integrations.PlaceholderAPI");
if (papi){
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") == null){
AdventureManager.consoleMessage("<red>[CustomFishing] 未检测到 PlaceholderAPI!</red>");
papi = false;
}else {
AdventureManager.consoleMessage("<gradient:#0070B3:#A0EACF>[CustomFishing] </gradient><green>PlaceholderAPI Hooked!");
}
}
season = config.getBoolean("config.season.enable");
if (!papi && season){
season = false;
AdventureManager.consoleMessage("<red>[CustomFishing] 使用季节特性请先打开 PlaceholderAPI 兼容!</red>");
}
if (season){
season_papi = config.getString("config.season.papi");
}else {
season_papi = null;
}
vanillaDrop = config.getBoolean("config.vanilla-loot-when-no-custom-fish");
needOpenWater = config.getBoolean("config.need-open-water");
fishFinderCoolDown = config.getInt("config.fishfinder-cooldown");
/*
计算获取布局
*/
LAYOUT.clear();
Set<String> keys = Objects.requireNonNull(config.getConfigurationSection("config.success-rate")).getKeys(false);
keys.forEach(key -> {
int range = config.getInt("config.success-rate." + key + ".range");
Set<String> rates = Objects.requireNonNull(config.getConfigurationSection("config.success-rate." + key + ".layout")).getKeys(false);
double[] successRate = new double[rates.size()];
for(int i = 0; i < rates.size(); i++){
successRate[i] = config.getDouble("config.success-rate." + key + ".layout." +(i + 1));
}
int size = rates.size()*range -1;
LayoutUtil layout = new LayoutUtil(key, range, successRate, size);
layout.setTitle(config.getString("config.success-rate." + key + ".title"," "));
layout.setBar(config.getString("config.success-rate." + key + ".subtitle.bar",""));
layout.setEnd(config.getString("config.success-rate." + key + ".subtitle.end","</font>"));
layout.setStart(config.getString("config.success-rate." + key + ".subtitle.start","<font:customfishing:default>"));
layout.setPointer(config.getString("config.success-rate." + key + ".subtitle.pointer",""));
layout.setPointerOffset(config.getString("config.success-rate." + key + ".subtitle.pointer_offset",""));
layout.setOffset(config.getString("config.success-rate." + key + ".subtitle.offset",""));
LAYOUT.put(key, layout);
});
}
}
public static class Message {
public static String prefix;
public static String reload;
public static String escape;
public static String noPerm;
public static String notExist;
public static String noConsole;
public static String wrongAmount;
public static String lackArgs;
public static String notOnline;
public static String giveItem;
public static String getItem;
public static String coolDown;
public static String possibleLoots;
public static String splitChar;
public static String noLoot;
public static String notOpenWater;
public static void loadMessage() {
YamlConfiguration config = getConfig("messages.yml");
prefix = config.getString("messages.prefix");
reload = config.getString("messages.reload");
escape = config.getString("messages.escape");
noPerm = config.getString("messages.no-perm");
notExist = config.getString("messages.not-exist");
noConsole = config.getString("messages.no-console");
wrongAmount = config.getString("messages.wrong-amount");
lackArgs = config.getString("messages.lack-args");
notOnline = config.getString("messages.not-online");
giveItem = config.getString("messages.give-item");
getItem = config.getString("messages.get-item");
coolDown = config.getString("messages.cooldown");
possibleLoots = config.getString("messages.possible-loots");
splitChar = config.getString("messages.split-char");
noLoot = config.getString("messages.no-loot");
notOpenWater = config.getString("messages.not-open-water");
}
}
public static class Title {
public static List<String> success_title;
public static List<String> success_subtitle;
public static int success_in;
public static int success_out;
public static int success_stay;
public static List<String> failure_title;
public static List<String> failure_subtitle;
public static int failure_in;
public static int failure_out;
public static int failure_stay;
public static void loadTitle() {
YamlConfiguration config = getConfig("titles.yml");
success_title = config.getStringList("titles.success.title");
success_subtitle = config.getStringList("titles.success.subtitle");
success_in = config.getInt("titles.success.fade.in")*50;
success_out = config.getInt("titles.success.fade.out")*50;
success_stay = config.getInt("titles.success.fade.stay")*50;
failure_title = config.getStringList("titles.failure.title");
failure_subtitle = config.getStringList("titles.failure.subtitle");
failure_in = config.getInt("titles.failure.fade.in")*50;
failure_out = config.getInt("titles.failure.fade.out")*50;
failure_stay = config.getInt("titles.failure.fade.stay")*50;
}
}
/*
载入Loot战利品
*/
public static void loadLoot() {
LOOT.clear();
LOOTITEM.clear();
YamlConfiguration config = getConfig("loots.yml");
Set<String> keys = Objects.requireNonNull(config.getConfigurationSection("items")).getKeys(false);
keys.forEach(key -> {
/*
必设置的内容,为构造所需
*/
String name;
if (config.contains("items." + key + ".display.name")) {
name = config.getString("items." + key + ".display.name");
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的物品名称!</red>");
return;
}
Difficulty difficulty;
if (config.contains("items." + key + ".difficulty")) {
String[] split = StringUtils.split(config.getString("items." + key + ".difficulty"), "-");
assert split != null;
if (Integer.parseInt(split[1]) <= 0 || Integer.parseInt(split[0]) <= 0){
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! " + key + " 的捕获难度必须为正整数与正整数的组合!</red>");
return;
}else {
difficulty = new Difficulty(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
}
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的捕获难度!</red>");
return;
}
int weight;
if (config.contains("items." + key + ".weight")) {
weight = config.getInt("items." + key + ".weight");
if (weight <= 0){
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! " + key + " 的捕获权重必须为正整数!</red>");
return;
}
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的捕获权重!</red>");
return;
}
int time;
if (config.contains("items." + key + ".time")) {
time = config.getInt("items." + key + ".time");
if (time <= 0){
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! " + key + " 的捕捉时间必须为正整数!</red>");
return;
}
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的捕捉时间!</red>");
return;
}
//新建单例
LootInstance loot = new LootInstance(key, name, difficulty, weight, time);
/*
必须设置的内容,但并非构造所需
*/
if (config.contains("items." + key + ".material")) {
loot.setMaterial(config.getString("items." + key + ".material"));
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的物品材质!</red>");
return;
}
/*
可选的设置内容
*/
if (config.contains("items." + key + ".display.lore"))
loot.setLore(config.getStringList("items." + key + ".display.lore"));
if (config.contains("items." + key + ".nbt"))
loot.setNbt(config.getMapList("items." + key + ".nbt").get(0));
if (config.contains("items."+ key +".nick")){
loot.setNick(config.getString("items."+key+".nick"));
}else {
loot.setNick(loot.getName());
}
if (config.contains("items." + key + ".action.message"))
loot.setMsg(config.getString("items." + key + ".action.message"));
if (config.contains("items." + key + ".action.command"))
loot.setCommands(config.getStringList("items." + key + ".action.command"));
if (config.contains("items." + key + "layout"))
loot.setLayout(config.getString("items." + key + "layout"));
/*
设置捕获条件
*/
if (config.contains("items." + key + ".requirements")){
List<Requirement> requirements = new ArrayList<>();
Objects.requireNonNull(config.getConfigurationSection("items." + key + ".requirements")).getKeys(false).forEach(requirement -> {
switch (requirement){
case "weather" -> requirements.add(new Weather(config.getStringList("items." + key + ".requirements.weather")));
case "ypos" -> requirements.add(new YPos(config.getStringList("items." + key + ".requirements.ypos")));
case "season" -> {
if (Config.season){
requirements.add(new Season(config.getStringList("items." + key + ".requirements.season")));
}else {
AdventureManager.consoleMessage("<red>[CustomFishing] 使用季节特性请先在 config.yml 中启用季节特性!</red>");
}
}
case "world" -> requirements.add(new World(config.getStringList("items." + key + ".requirements.world")));
case "biome" -> requirements.add(new Biome(config.getStringList("items." + key + ".requirements.biome")));
case "permission" -> requirements.add(new Permission(config.getString("items." + key + ".requirements.permission")));
case "region" -> {
if (Config.wg){
requirements.add(new Region(config.getStringList("items." + key + ".requirements.regions")));
}else {
AdventureManager.consoleMessage("<red>[CustomFishing] 指定钓鱼区域需要启用 WorldGuard 兼容!</red>");
}
}
case "time" -> requirements.add(new Time(config.getStringList("items." + key + ".requirements.time")));
}
});
loot.setRequirements(requirements);
}
//添加单例进缓存
LOOT.put(key, loot);
//添加根据单例生成的NBT物品进缓存
LootInstance.addLoot2cache(key);
});
if (config.contains("mobs") && Config.mm){
Set<String> mobs = Objects.requireNonNull(config.getConfigurationSection("mobs")).getKeys(false);
mobs.forEach(key -> {
/*
必设置的内容,为构造所需
*/
String name;
if (config.contains("mobs." + key + ".name")) {
name = config.getString("mobs." + key + ".name");
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的怪物名称!</red>");
return;
}
Difficulty difficulty;
if (config.contains("mobs." + key + ".difficulty")) {
String[] split = StringUtils.split(config.getString("mobs." + key + ".difficulty"), "-");
assert split != null;
if (Integer.parseInt(split[1]) <= 0 || Integer.parseInt(split[0]) <= 0){
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! " + key + " 的捕获难度必须为正整数与正整数的组合!</red>");
return;
}else {
difficulty = new Difficulty(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
}
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的捕获难度!</red>");
return;
}
int weight;
if (config.contains("mobs." + key + ".weight")) {
weight = config.getInt("mobs." + key + ".weight");
if (weight <= 0){
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! " + key + " 的捕获权重必须为正整数!</red>");
return;
}
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的捕获权重!</red>");
return;
}
int time;
if (config.contains("mobs." + key + ".time")) {
time = config.getInt("mobs." + key + ".time");
if (time <= 0){
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! " + key + " 的捕捉时间必须为正整数!</red>");
return;
}
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的捕捉时间!</red>");
return;
}
//新建单例
LootInstance loot = new LootInstance(key, name, difficulty, weight, time);
//设置昵称
loot.setNick(name);
//设置MM怪ID
if (config.contains("mobs." + key + ".mythicmobsID")) {
loot.setMm(config.getString("mobs." + key + ".mythicmobsID"));
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的MM怪ID!</red>");
return;
}
//设置MM怪位移
if (config.contains("mobs." + key + ".vector.horizontal") && config.contains("mobs." + key + ".vector.vertical")) {
loot.setVectorUtil(new VectorUtil(config.getDouble("mobs." + key + ".vector.horizontal"), config.getDouble("mobs." + key + ".vector.vertical")));
} else {
loot.setVectorUtil(new VectorUtil(1.1, 1.3));
}
if (config.contains("mobs." + key + ".level"))
loot.setMmLevel(config.getInt("mobs." + key + ".level", 0));
if (config.contains("mobs." + key + ".action.message"))
loot.setMsg(config.getString("mobs." + key + ".action.message"));
if (config.contains("mobs." + key + ".action.command"))
loot.setCommands(config.getStringList("mobs." + key + ".action.command"));
if (config.contains("mobs." + key + "layout"))
loot.setLayout(config.getString("mobs." + key + "layout"));
/*
设置捕获条件
*/
if (config.contains("mobs." + key + ".requirements")){
List<Requirement> requirements = new ArrayList<>();
Objects.requireNonNull(config.getConfigurationSection("mobs." + key + ".requirements")).getKeys(false).forEach(requirement -> {
switch (requirement){
case "weather" -> requirements.add(new Weather(config.getStringList("mobs." + key + ".requirements.weather")));
case "ypos" -> requirements.add(new YPos(config.getStringList("mobs." + key + ".requirements.ypos")));
case "season" -> {
if (Config.season){
requirements.add(new Season(config.getStringList("mobs." + key + ".requirements.season")));
}else {
AdventureManager.consoleMessage("<red>[CustomFishing] 使用季节特性请先在 config.yml 中启用季节特性!</red>");
}
}
case "world" -> requirements.add(new World(config.getStringList("mobs." + key + ".requirements.world")));
case "biome" -> requirements.add(new Biome(config.getStringList("mobs." + key + ".requirements.biome")));
case "permission" -> requirements.add(new Permission(config.getString("mobs." + key + ".requirements.permission")));
case "region" -> {
if (Config.wg){
requirements.add(new Region(config.getStringList("mobs." + key + ".requirements.regions")));
}else {
AdventureManager.consoleMessage("<red>[CustomFishing] 指定钓鱼区域需要启用 WorldGuard 兼容!</red>");
}
}
case "time" -> requirements.add(new Time(config.getStringList("mobs." + key + ".requirements.time")));
}
});
loot.setRequirements(requirements);
}
//丢入缓存
LOOT.put(key, loot);
});
if (keys.size() != LOOTITEM.size() || mobs.size() != LOOT.size()- LOOTITEM.size()) {
AdventureManager.consoleMessage("<red>[CustomFishing] loots.yml 文件存在配置错误!</red>");
} else {
AdventureManager.consoleMessage("<gradient:#0070B3:#A0EACF>[CustomFishing] </gradient><white>从 loots.yml 载入了<green>" + keys.size() + "<white>条物品数据");
AdventureManager.consoleMessage("<gradient:#0070B3:#A0EACF>[CustomFishing] </gradient><white>从 loots.yml 载入了<green>" + mobs.size() + "<white>条怪物数据");
}
return;
}
if (keys.size() != LOOTITEM.size()){
AdventureManager.consoleMessage("<red>[CustomFishing] loots.yml 文件存在配置错误!</red>");
} else {
AdventureManager.consoleMessage("<gradient:#0070B3:#A0EACF>[CustomFishing] </gradient><white>从 loots.yml 载入了<green>" + keys.size() + "<white>条物品数据");
}
}
/*
载入util物品
*/
public static void loadUtil() {
UTIL.clear();
UTILITEM.clear();
YamlConfiguration config = getConfig("utils.yml");
Set<String> keys = Objects.requireNonNull(config.getConfigurationSection("utils")).getKeys(false);
keys.forEach(key -> {
/*
必设置的内容,为构造所需
*/
String name;
if (config.contains("utils." + key + ".display.name")) {
name = config.getString("utils." + key + ".display.name");
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的物品名称!</red>");
return;
}
String material;
if (config.contains("utils." + key + ".material")) {
material = config.getString("utils." + key + ".material");
} else {
AdventureManager.consoleMessage("<red>[CustomFishing] 错误! 未设置 " + key + " 的物品材质!</red>");
return;
}
//构造
UtilInstance utilInstance = new UtilInstance(key, name, material);
if (config.contains("utils." + key + ".display.lore"))
utilInstance.setLore(config.getStringList("utils." + key + ".display.lore"));
if (config.contains("utils." + key + ".nbt"))
utilInstance.setNbt(config.getMapList("utils." + key + ".nbt").get(0));
UTIL.put(key, utilInstance);
UtilInstance.addUtil2cache(key);
});
if (keys.size() != UTILITEM.size()){
AdventureManager.consoleMessage("<red>[CustomFishing] utils.yml 文件存在配置错误!</red>");
} else {
AdventureManager.consoleMessage("<gradient:#0070B3:#A0EACF>[CustomFishing] </gradient><white>从 utils.yml 载入了<green>" + keys.size() + "<white>条工具数据");
}
}
}

View File

@@ -0,0 +1,36 @@
package net.momirealms.customfishing;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.momirealms.customfishing.command.Execute;
import net.momirealms.customfishing.command.TabComplete;
import net.momirealms.customfishing.listener.PlayerListener;
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 BukkitAudiences adventure;
@Override
public void onEnable() {
instance = this;
adventure = BukkitAudiences.create(this);
Objects.requireNonNull(Bukkit.getPluginCommand("customfishing")).setExecutor(new Execute());
Objects.requireNonNull(Bukkit.getPluginCommand("customfishing")).setTabCompleter(new TabComplete());
Bukkit.getPluginManager().registerEvents(new PlayerListener(),this);
ConfigReader.Reload();
AdventureManager.consoleMessage("<gradient:#0070B3:#A0EACF>[CustomFishing] </gradient><gray>插件已加载! 作者:小默米 QQ:3266959688");
}
@Override
public void onDisable() {
AdventureManager.consoleMessage("<gradient:#0070B3:#A0EACF>[CustomFishing] </gradient><gray>插件已卸载! 作者:小默米 QQ:3266959688");
if(adventure != null) {
adventure.close();
adventure = null;
}
}
}

View File

@@ -0,0 +1,205 @@
package net.momirealms.customfishing.command;
import net.momirealms.customfishing.AdventureManager;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.utils.LootInstance;
import net.momirealms.customfishing.utils.UtilInstance;
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 javax.annotation.ParametersAreNonnullByDefault;
public class Execute implements CommandExecutor {
@Override
@ParametersAreNonnullByDefault
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
//没有权限的快走啦
if (!(sender.hasPermission("customfishing.admin") || sender.isOp())) {
AdventureManager.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.noPerm);
return true;
}
//参数打不全的赶紧走开
if (args.length < 1){
lackArgs(sender);
return true;
}
//重载命令
if (args[0].equalsIgnoreCase("reload")) {
ConfigReader.Reload();
if (sender instanceof Player){
AdventureManager.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.reload);
}else {
AdventureManager.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.reload);
}
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])){
noItem(sender);
return true;
}
if (args.length == 4){
LootInstance.givePlayerLoot(player, args[3], 1);
AdventureManager.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;
}
LootInstance.givePlayerLoot(player, args[3], Integer.parseInt(args[4]));
AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3]));
}
}else {
AdventureManager.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])){
noItem(sender);
return true;
}
if (args.length == 5){
LootInstance.givePlayerLoot(player, args[4], 1);
giveItem(sender, args[3], args[4], 1);
}else {
if (Integer.parseInt(args[5]) < 1){
wrongAmount(sender);
return true;
}
LootInstance.givePlayerLoot(player, args[4], Integer.parseInt(args[5]));
giveItem(sender, args[3], args[4], Integer.parseInt(args[5]));
}
return true;
}
}
/*
给予实用物品
*/
else if(args[1].equalsIgnoreCase("util")){
if (args[2].equalsIgnoreCase("get")) {
//检验参数长度 [0]items [1]loot [2]get [3]xxx [4](amount)
if (sender instanceof Player player){
//是否存在于缓存中
if (!ConfigReader.UTIL.containsKey(args[3])){
noItem(sender);
return true;
}
if (args.length == 4){
UtilInstance.givePlayerUtil(player, args[3], 1);
AdventureManager.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;
}
UtilInstance.givePlayerUtil(player, args[3], Integer.parseInt(args[4]));
AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.getItem.replace("{Amount}", args[4]).replace("{Item}",args[3]));
}
}else {
AdventureManager.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.UTIL.containsKey(args[4])){
noItem(sender);
return true;
}
if (args.length == 5){
UtilInstance.givePlayerUtil(player, args[4], 1);
giveItem(sender, args[3], args[4], 1);
}else {
if (Integer.parseInt(args[5]) < 1){
wrongAmount(sender);
return true;
}
UtilInstance.givePlayerUtil(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){
AdventureManager.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.lackArgs);
}else {
AdventureManager.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.lackArgs);
}
}
private void notOnline(CommandSender sender){
if (sender instanceof Player){
AdventureManager.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.notOnline);
}else {
AdventureManager.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.notOnline);
}
}
private void noItem(CommandSender sender){
if (sender instanceof Player){
AdventureManager.playerMessage((Player) sender,ConfigReader.Message.prefix + ConfigReader.Message.notExist);
}else {
AdventureManager.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){
AdventureManager.playerMessage((Player) sender, string);
}else {
AdventureManager.consoleMessage(string);
}
}
private void wrongAmount(CommandSender sender){
if (sender instanceof Player){
AdventureManager.playerMessage((Player) sender, ConfigReader.Message.prefix + ConfigReader.Message.wrongAmount);
}else {
AdventureManager.consoleMessage(ConfigReader.Message.prefix + ConfigReader.Message.wrongAmount);
}
}
}

View File

@@ -0,0 +1,84 @@
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 javax.annotation.ParametersAreNonnullByDefault;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TabComplete implements TabCompleter {
@Override
@ParametersAreNonnullByDefault
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
//没有权限还想补全?
if (!(sender.hasPermission("customfishing.admin") || sender.isOp())) {
return null;
}
if (args.length == 1){
return Arrays.asList("reload","items");
}
if (args.length == 2){
if (args[0].equalsIgnoreCase("items")){
return Arrays.asList("loot","bait","rod","util");
}
}
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")){
return Arrays.asList("get","give");
}
}
}
if (args.length == 4){
if (args[0].equalsIgnoreCase("items")){
if (args[1].equalsIgnoreCase("loot")){
if (args[2].equalsIgnoreCase("give")){
return online_players();
}
if (args[2].equalsIgnoreCase("get")){
return loots();
}
}else if(args[1].equalsIgnoreCase("util")){
if (args[2].equalsIgnoreCase("give")){
return online_players();
}
if (args[2].equalsIgnoreCase("get")){
return utils();
}
}
}
}
if (args.length == 5){
if (args[0].equalsIgnoreCase("items")){
if (args[1].equalsIgnoreCase("loot")){
if (args[2].equalsIgnoreCase("give")){
return loots();
}
}else if(args[1].equalsIgnoreCase("util")){
if (args[2].equalsIgnoreCase("give")){
return utils();
}
}
}
}
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(){
return new ArrayList<>(ConfigReader.LOOTITEM.keySet());
}
private List<String> utils(){
return new ArrayList<>(ConfigReader.UTIL.keySet());
}
}

View File

@@ -0,0 +1,242 @@
package net.momirealms.customfishing.listener;
import de.tr7zw.changeme.nbtapi.NBTItem;
import net.momirealms.customfishing.AdventureManager;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.requirements.FishingCondition;
import net.momirealms.customfishing.requirements.Requirement;
import net.momirealms.customfishing.timer.Timer;
import net.momirealms.customfishing.utils.FishingPlayer;
import net.momirealms.customfishing.utils.LayoutUtil;
import net.momirealms.customfishing.utils.LootInstance;
import net.momirealms.customfishing.utils.MMUtil;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class PlayerListener implements Listener {
private final HashMap<Player, Long> coolDown = new HashMap<>();
private final HashMap<Player, LootInstance> nextLoot = new HashMap<>();
public static ConcurrentHashMap<Player, FishingPlayer> fishingPlayers = new ConcurrentHashMap<>();
@EventHandler
public void onFish(PlayerFishEvent event){
PlayerFishEvent.State state = event.getState();
Player player = event.getPlayer();
//抛竿
if (state.equals(PlayerFishEvent.State.FISHING)){
//设置冷却时间
long time = System.currentTimeMillis();
if (time - (coolDown.getOrDefault(player, time - 1000)) < 1000) {
return;
}
coolDown.put(player, time);
//获取抛竿位置处可能的Loot实例列表
List<LootInstance> possibleLoots = getPossibleLootList(new FishingCondition(player, event.getHook().getLocation()));
if (possibleLoots.size() == 0){
nextLoot.put(player, null);
return;
}
//计算总权重
int totalWeight = 0;
for (LootInstance loot : possibleLoots){
totalWeight += loot.getWeight();
}
//计算每种鱼权重所占的比例并输入数组
double[] weightRatios = new double[possibleLoots.size()];
int index = 0;
for (LootInstance loot : possibleLoots) {
double weight = loot.getWeight();
weightRatios[index++] = weight / totalWeight;
}
//根据权重比例划分定义域
double[] weights = new double[possibleLoots.size()];
double startPos = 0;
for (int i = 0; i < index; i++) {
weights[i] = startPos + weightRatios[i];
startPos += weightRatios[i];
}
//根据随机数所落区间获取Loot实例
double random = Math.random();
int pos = Arrays.binarySearch(weights, random);
if (pos < 0) {
//二分法,数组中不存在该元素,则会返回 -(插入点 + 1)
pos = -pos - 1;
} else {
//如果存在,那真是中大奖了!
nextLoot.put(player, possibleLoots.get(pos));
return;
}
if (pos < weights.length && random < weights[pos]) {
nextLoot.put(player, possibleLoots.get(pos));
return;
}
//以防万一,丢入空值
nextLoot.put(player, null);
}
//咬钩
else if (state.equals(PlayerFishEvent.State.BITE)){
//如果没有特殊鱼就返回
if (nextLoot.get(player) == null) return;
//如果正在钓一个鱼了,那么也返回
if (fishingPlayers.get(player) != null) return;
LootInstance lootInstance = nextLoot.get(player);
//获取布局名,或是随机布局
String layout = Optional.ofNullable(lootInstance.getLayout()).orElseGet(() ->{
Random generator = new Random();
Object[] values = ConfigReader.LAYOUT.keySet().toArray();
return (String) values[generator.nextInt(values.length)];
});
//根据鱼的时间放入玩家实例,并应用药水效果
fishingPlayers.put(player,
new FishingPlayer(System.currentTimeMillis() + lootInstance.getTime(),
new Timer(player, lootInstance.getDifficulty(), layout)
)
);
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, lootInstance.getTime()/50,3));
}
//正常钓到鱼 & 正常收杆
else if (state.equals(PlayerFishEvent.State.CAUGHT_FISH) || state.equals(PlayerFishEvent.State.REEL_IN)){
//发现有特殊鱼,那么必须掉落特殊鱼
if (fishingPlayers.get(player) != null){
//清除原版战利品
if (event.getCaught() != null){
event.getCaught().remove();
}
LootInstance lootInstance = nextLoot.get(player);
LayoutUtil layout = ConfigReader.LAYOUT.get(fishingPlayers.get(player).getTimer().getLayout());
int last = (fishingPlayers.get(player).getTimer().getTimerTask().getProgress() + 1)/layout.getRange();
fishingPlayers.remove(player);
player.removePotionEffect(PotionEffectType.SLOW);
if (!event.getHook().isInOpenWater()){
AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.notOpenWater);
return;
}
if (Math.random() < layout.getSuccessRate()[last]){
//捕鱼成功
Location location = event.getHook().getLocation();
//钓上来的是MM怪吗
if (lootInstance.getMm() != null){
MMUtil.summonMM(player.getLocation(), location, lootInstance);
}else {
Entity item = location.getWorld().dropItem(location, ConfigReader.LOOTITEM.get(lootInstance.getKey()));
Vector vector = player.getLocation().subtract(location).toVector().multiply(0.1);
vector = vector.setY((vector.getY()+0.2)*1.2);
item.setVelocity(vector);
}
if (lootInstance.getMsg() != null){
//发送消息
AdventureManager.playerMessage(player, ConfigReader.Message.prefix + lootInstance.getMsg().replace("{loot}",lootInstance.getNick()).replace("{player}", player.getName()));
}
if (lootInstance.getCommands() != null){
//执行指令
lootInstance.getCommands().forEach(command ->{
String finalCommand = command.
replaceAll("\\{x}", String.valueOf(Math.round(location.getX()))).
replaceAll("\\{y}", String.valueOf(Math.round(location.getY()))).
replaceAll("\\{z}", String.valueOf(Math.round(location.getZ()))).
replaceAll("\\{player}", event.getPlayer().getName()).
replaceAll("\\{world}", player.getWorld().getName()).
replaceAll("\\{loot}", lootInstance.getNick());
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), finalCommand);
});
}
//发送Title
AdventureManager.playerTitle(player, ConfigReader.Title.success_title.get((int) (ConfigReader.Title.success_title.size()*Math.random())).replace("{loot}",lootInstance.getNick()), ConfigReader.Title.success_subtitle.get((int) (ConfigReader.Title.success_subtitle.size()*Math.random())).replace("{loot}",lootInstance.getNick()), ConfigReader.Title.success_in, ConfigReader.Title.success_stay, ConfigReader.Title.success_out);
}else {
//移除正在钓鱼的状态
fishingPlayers.remove(player);
//捕鱼失败Title
AdventureManager.playerTitle(player, ConfigReader.Title.failure_title.get((int) (ConfigReader.Title.failure_title.size()*Math.random())), ConfigReader.Title.failure_subtitle.get((int) (ConfigReader.Title.failure_subtitle.size()*Math.random())), ConfigReader.Title.failure_in, ConfigReader.Title.failure_stay, ConfigReader.Title.failure_out);
}
}
//筛选后发现这个地方没有特殊鱼
else {
//是否能钓到原版掉落物
if (!ConfigReader.Config.vanillaDrop){
if (event.getCaught() != null){
event.getCaught().remove();
}
}
}
}
}
@EventHandler
public void onQUit(PlayerQuitEvent event){
Player player = event.getPlayer();
player.removePotionEffect(PotionEffectType.SLOW);
coolDown.remove(player);
nextLoot.remove(player);
fishingPlayers.remove(player);
}
@EventHandler
public void onInteract(PlayerInteractEvent event){
if (!event.hasItem()) return;
if (!(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) return;
NBTItem nbtItem = new NBTItem(event.getItem());
if (nbtItem.getCompound("CustomFishing") == null) return;
if (nbtItem.getCompound("CustomFishing").getString("type").equals("util") || nbtItem.getCompound("CustomFishing").getString("id").equals("fishfinder")){
Player player = event.getPlayer();
//设置冷却时间
long time = System.currentTimeMillis();
if (time - (coolDown.getOrDefault(player, time - ConfigReader.Config.fishFinderCoolDown)) < ConfigReader.Config.fishFinderCoolDown) {
AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.coolDown);
return;
}
coolDown.put(player, time);
//获取玩家位置处可能的Loot实例列表
List<LootInstance> possibleLoots = getPossibleLootList(new FishingCondition(player, player.getLocation()));
if (possibleLoots.size() == 0){
AdventureManager.playerMessage(player, ConfigReader.Message.prefix + ConfigReader.Message.noLoot);
return;
}
StringBuilder stringBuilder = new StringBuilder(ConfigReader.Message.prefix + ConfigReader.Message.possibleLoots);
possibleLoots.forEach(loot -> stringBuilder.append(loot.getNick()).append(ConfigReader.Message.splitChar));
AdventureManager.playerMessage(player, stringBuilder.substring(0, stringBuilder.length()-1));
}
}
/*
获取可能的Loot列表
*/
private List<LootInstance> getPossibleLootList(FishingCondition fishingCondition) {
List<LootInstance> available = new ArrayList<>();
ConfigReader.LOOT.keySet().forEach(key -> {
LootInstance loot = ConfigReader.LOOT.get(key);
List<Requirement> requirements = loot.getRequirements();
if (requirements == null){
available.add(loot);
}else {
boolean isMet = true;
for (Requirement requirement : requirements){
if (!requirement.isConditionMet(fishingCondition)){
isMet = false;
}
}
if (isMet){
available.add(loot);
}
}
});
return available;
}
}

View File

@@ -0,0 +1,21 @@
package net.momirealms.customfishing.requirements;
import java.util.List;
public record Biome(List<String> biomes) implements Requirement {
public List<String> getBiomes() {
return this.biomes;
}
@Override
public boolean isConditionMet(FishingCondition fishingCondition) {
String currentBiome = fishingCondition.getLocation().getBlock().getBiome().getKey().toString();
for (String biome : biomes) {
if (currentBiome.equalsIgnoreCase(biome)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,12 @@
package net.momirealms.customfishing.requirements;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public record FishingCondition(Player player, Location location) {
public Location getLocation() { return location; }
public Player getPlayer() {
return player;
}
}

View File

@@ -0,0 +1,13 @@
package net.momirealms.customfishing.requirements;
public record Permission(String permission) implements Requirement {
public String getPermission() {
return this.permission;
}
@Override
public boolean isConditionMet(FishingCondition fishingCondition) {
return fishingCondition.getPlayer().hasPermission(permission);
}
}

View File

@@ -0,0 +1,30 @@
package net.momirealms.customfishing.requirements;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import java.util.List;
public record Region(List<String> regions) implements Requirement {
public List<String> getRegions() {
return this.regions;
}
@Override
public boolean isConditionMet(FishingCondition fishingCondition) {
RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
RegionQuery query = container.createQuery();
ApplicableRegionSet set = query.getApplicableRegions(BukkitAdapter.adapt(fishingCondition.getLocation()));
for (ProtectedRegion protectedRegion : set) {
if (regions.contains(protectedRegion.getId())) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,5 @@
package net.momirealms.customfishing.requirements;
public interface Requirement {
boolean isConditionMet(FishingCondition fishingCondition);
}

View File

@@ -0,0 +1,25 @@
package net.momirealms.customfishing.requirements;
import me.clip.placeholderapi.PlaceholderAPI;
import net.momirealms.customfishing.ConfigReader;
import org.bukkit.ChatColor;
import java.util.List;
public record Season(List<String> seasons) implements Requirement {
public List<String> getSeasons() {
return this.seasons;
}
@Override
public boolean isConditionMet(FishingCondition fishingCondition) {
String currentSeason = ChatColor.stripColor(PlaceholderAPI.setPlaceholders(fishingCondition.getPlayer(), ConfigReader.Config.season_papi));
for (String season : seasons) {
if (season.equalsIgnoreCase(currentSeason)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,24 @@
package net.momirealms.customfishing.requirements;
import org.apache.commons.lang.StringUtils;
import java.util.List;
public record Time(List<String> times) implements Requirement{
public List<String> getTimes() {
return this.times;
}
@Override
public boolean isConditionMet(FishingCondition fishingCondition) {
long time = fishingCondition.getLocation().getWorld().getTime();
for (String range : times) {
String[] timeMinMax = StringUtils.split(range, "~");
if (time > Long.parseLong(timeMinMax[0]) && time < Long.parseLong(timeMinMax[1])) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,36 @@
package net.momirealms.customfishing.requirements;
import net.momirealms.customfishing.AdventureManager;
import org.bukkit.World;
import java.util.List;
public record Weather(List<String> weathers) implements Requirement {
public List<String> getWeathers() {
return this.weathers;
}
@Override
public boolean isConditionMet(FishingCondition fishingCondition) {
World world = fishingCondition.getLocation().getWorld();
if (world != null) {
String currentWeather;
if (world.isThundering()) {
currentWeather = "thunder";
} else if (world.isClearWeather()) {
currentWeather = "clear";
} else {
currentWeather = "rain";
}
for (String weather : weathers) {
if (weather.equalsIgnoreCase(currentWeather)) {
return true;
}
}
return false;
}
AdventureManager.consoleMessage("<red>[CustomFishing] 这条消息不应该出现,玩家钓鱼时所处的世界并不存在!</red>");
return false;
}
}

View File

@@ -0,0 +1,22 @@
package net.momirealms.customfishing.requirements;
import net.momirealms.customfishing.AdventureManager;
import java.util.List;
public record World(List<String> worlds) implements Requirement {
public List<String> getWorlds() {
return this.worlds;
}
@Override
public boolean isConditionMet(FishingCondition fishingCondition) {
org.bukkit.World world = fishingCondition.getLocation().getWorld();
if (world != null) {
return worlds.contains(world.getName());
}
AdventureManager.consoleMessage("<red>[CustomFishing] 这条消息不应该出现,玩家钓鱼时所处的世界并不存在!</red>");
return false;
}
}

View File

@@ -0,0 +1,24 @@
package net.momirealms.customfishing.requirements;
import org.apache.commons.lang.StringUtils;
import java.util.List;
public record YPos(List<String> yPos) implements Requirement {
public List<String> getYPos() {
return this.yPos;
}
@Override
public boolean isConditionMet(FishingCondition fishingCondition) {
int y = (int) fishingCondition.getLocation().getY();
for (String range : yPos) {
String[] yMinMax = StringUtils.split(range, "~");
if (y > Integer.parseInt(yMinMax[0]) && y < Integer.parseInt(yMinMax[1])) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,24 @@
package net.momirealms.customfishing.timer;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.utils.Difficulty;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
public class Timer {
private final TimerTask timerTask;
private final BukkitTask task;
private final String layout;
public Timer(Player player, Difficulty difficulty, String layout) {
this.layout = layout;
this.timerTask = new TimerTask(player, difficulty, layout);
this.task = timerTask.runTaskTimerAsynchronously(CustomFishing.instance, 1,1);
timerTask.setTaskID(task.getTaskId());
}
public TimerTask getTimerTask(){ return this.timerTask; }
public int getTaskID (){ return this.task.getTaskId(); }
public String getLayout(){return this.layout;}
}

View File

@@ -0,0 +1,111 @@
package net.momirealms.customfishing.timer;
import net.momirealms.customfishing.AdventureManager;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.CustomFishing;
import net.momirealms.customfishing.utils.Difficulty;
import net.momirealms.customfishing.utils.LayoutUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
import static net.momirealms.customfishing.listener.PlayerListener.fishingPlayers;
public class TimerTask extends BukkitRunnable {
private final Player player;
private final Difficulty difficulty;
private int taskID;
private int progress;
private int internalTimer;
private final int size;
private boolean face;
private final String start;
private final String bar;
private final String pointer;
private final String offset;
private final String end;
private final String pointerOffset;
private final String title;
public TimerTask(Player player, Difficulty difficulty, String layout){
this.player = player;
this.difficulty = difficulty;
this.progress = 0;
this.internalTimer = 0;
this.face = true;
LayoutUtil layoutUtil = ConfigReader.LAYOUT.get(layout);
this.start = layoutUtil.getStart();
this.bar = layoutUtil.getBar();
this.pointer = layoutUtil.getPointer();
this.offset = layoutUtil.getOffset();
this.end = layoutUtil.getEnd();
this.pointerOffset = layoutUtil.getPointerOffset();
this.title = layoutUtil.getTitle();
this.size = layoutUtil.getSize();
}
public int getProgress() { return this.progress; }
public void setTaskID(int taskID){
this.taskID = taskID;
}
@Override
public void run() {
//移除提前收杆玩家
if (fishingPlayers.get(player) == null){
Bukkit.getScheduler().cancelTask(taskID);
return;
}
//移除切换物品的玩家
if (player.getInventory().getItemInMainHand().getType() != Material.FISHING_ROD){
fishingPlayers.remove(player);
Bukkit.getScheduler().cancelTask(taskID);
Bukkit.getScheduler().callSyncMethod(CustomFishing.instance, ()-> {
player.removePotionEffect(PotionEffectType.SLOW);
return null;
});
return;
}
//移除超时玩家
if (System.currentTimeMillis() > fishingPlayers.get(player).getFishingTime()){
fishingPlayers.remove(player);
Bukkit.getScheduler().cancelTask(taskID);
return;
}
int timer = difficulty.getTimer() - 1;
int speed = difficulty.getSpeed();
//设置指针方向
if (progress <= speed - 1){
face = true;
}else if(progress >= size - speed + 1){
face = false;
}
//内部计时器操控
if (internalTimer < timer){
internalTimer++;
}else {
if (face){
internalTimer -= timer;
progress += speed;
}else {
internalTimer -= timer;
progress -= speed;
}
}
//发送title
StringBuilder stringBuilder = new StringBuilder(start + bar + pointerOffset);
for (int index = 0; index <= size; index++){
if (index == progress){
stringBuilder.append(pointer);
}else {
stringBuilder.append(offset);
}
}
stringBuilder.append(end);
AdventureManager.playerTitle(player, title, stringBuilder.toString(),0,300,0);
}
}

View File

@@ -0,0 +1,12 @@
package net.momirealms.customfishing.utils;
public record Difficulty(int timer, int speed) {
public int getTimer() {
return this.timer;
}
public int getSpeed() {
return this.speed;
}
}

View File

@@ -0,0 +1,14 @@
package net.momirealms.customfishing.utils;
import net.momirealms.customfishing.timer.Timer;
public record FishingPlayer(Long fishingTime, Timer timer) {
public Long getFishingTime() {
return this.fishingTime;
}
public Timer getTimer() {
return this.timer;
}
}

View File

@@ -0,0 +1,44 @@
package net.momirealms.customfishing.utils;
public class LayoutUtil {
private final String key;
private final int range;
private final double[] successRate;
private final int size;
private String start;
private String bar;
private String pointer;
private String offset;
private String end;
private String pointerOffset;
private String title;
public LayoutUtil(String key, int range, double[] successRate, int size){
this.key = key;
this.range = range;
this.successRate = successRate;
this.size = size;
}
public void setBar(String bar) {this.bar = bar;}
public void setEnd(String end) {this.end = end;}
public void setOffset(String offset) {this.offset = offset;}
public void setPointer(String pointer) {this.pointer = pointer;}
public void setPointerOffset(String pointerOffset) {this.pointerOffset = pointerOffset;}
public void setStart(String start) {this.start = start;}
public void setTitle(String title) {this.title = title;}
public String getKey(){return this.key;}
public int getRange(){return this.range;}
public double[] getSuccessRate(){return this.successRate;}
public int getSize(){return this.size;}
public String getBar() {return bar;}
public String getEnd() {return end;}
public String getOffset() {return offset;}
public String getPointer() {return pointer;}
public String getPointerOffset() {return pointerOffset;}
public String getStart() {return start;}
public String getTitle() {return title;}
}

View File

@@ -0,0 +1,122 @@
package net.momirealms.customfishing.utils;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTItem;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.momirealms.customfishing.ConfigReader;
import net.momirealms.customfishing.requirements.Requirement;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.*;
public class LootInstance {
private final String key;
private final String name;
private String nick;
private List<String> lore;
private Map<?, ?> nbt;
private String material;
private String msg;
private String mm;
private String layout;
private VectorUtil vectorUtil;
private final Difficulty difficulty;
private final int weight;
private List<Requirement> requirements;
private final int time;
private int mmLevel;
private List<String> commands;
public LootInstance(String key, String name, Difficulty difficulty, int weight, int time){
this.key = key;
this.name = name;
this.difficulty = difficulty;
this.weight = weight;
this.time = time;
}
public String getKey(){
return this.key;
}
public String getNick(){ return this.nick; }
public String getMsg(){ return this.msg; }
public String getLayout(){ return this.layout; }
public String getMm(){ return this.mm; }
public List<String> getLore(){
return this.lore;
}
public List<String> getCommands(){return this.commands;}
public Difficulty getDifficulty(){
return this.difficulty;
}
public int getWeight(){
return this.weight;
}
public String getName(){
return this.name;
}
public String getMaterial(){
return this.material;
}
public Map<?, ?> getNbt(){
return this.nbt;
}
public List<Requirement> getRequirements() { return this.requirements; }
public int getTime(){ return this.time; }
public int getMmLevel(){ return this.mmLevel; }
public VectorUtil getVectorUtil(){ return this.vectorUtil; }
public void setLore(List<String> lore){
this.lore = lore;
}
public void setNbt(Map<?, ?> nbt){
this.nbt = nbt;
}
public void setRequirements(List<Requirement> requirements) { this.requirements = requirements; }
public void setMaterial(String material){ this.material = material; }
public void setNick(String nick){ this.nick = nick; }
public void setMsg(String msg){ this.msg = msg; }
public void setMm(String mm){ this.mm = mm; }
public void setLayout(String layout){ this.layout = layout; }
public void setVectorUtil(VectorUtil vectorUtil){ this.vectorUtil = vectorUtil; }
public void setCommands(List<String> commands){ this.commands = commands; }
public void setMmLevel(int mmLevel){ this.mmLevel = mmLevel; }
/*
将实例转换为缓存中的NBT物品
*/
public static void addLoot2cache(String lootKey){
//从缓存中请求物品Item
LootInstance loot = ConfigReader.LOOT.get(lootKey);
ItemStack itemStack = new ItemStack(Material.valueOf(loot.material.toUpperCase()));
NBTItem nbtItem = new NBTItem(itemStack);
//设置Name和Lore
NBTCompound display = nbtItem.addCompound("display");
display.setString("Name", GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize("<italic:false>"+loot.name)));
if(loot.lore != null){
List<String> lores = display.getStringList("Lore");
loot.lore.forEach(lore -> lores.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize("<italic:false>"+lore))));
}
//设置NBT
//添加物品进入缓存
if (loot.nbt != null){
NBTUtil nbtUtil = new NBTUtil(loot.nbt, nbtItem.getItem());
ConfigReader.LOOTITEM.put(lootKey, nbtUtil.getNBTItem().getItem());
}else {
ConfigReader.LOOTITEM.put(lootKey, nbtItem.getItem());
}
}
/*
给予玩家某NBT物品
*/
public static void givePlayerLoot(Player player, String lootKey, int amount){
ItemStack itemStack = ConfigReader.LOOTITEM.get(lootKey);
itemStack.setAmount(amount);
player.getInventory().addItem(itemStack);
}
}

View File

@@ -0,0 +1,34 @@
package net.momirealms.customfishing.utils;
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 org.bukkit.Location;
import org.bukkit.util.Vector;
import java.util.Optional;
public class MMUtil {
public static void summonMM(Location pLocation, Location bLocation, LootInstance loot){
MobManager mobManager = MythicBukkit.inst().getMobManager();
Optional<MythicMob> mythicMob = mobManager.getMythicMob(loot.getMm());
if (mythicMob.isPresent()) {
//获取MM怪实例
MythicMob theMob = mythicMob.get();
//生成MM怪
Position position = Position.of(bLocation);
AbstractLocation abstractLocation = new AbstractLocation(position);
ActiveMob activeMob = theMob.spawn(abstractLocation, loot.getMmLevel());
VectorUtil vectorUtil = loot.getVectorUtil();
Vector vector = pLocation.subtract(bLocation).toVector().multiply((vectorUtil.getHorizontal())-1);
vector = vector.setY((vector.getY()+0.2)*vectorUtil.getVertical());
activeMob.getEntity().setVelocity(new AbstractVector(vector.getX(),vector.getY(),vector.getZ()));
}
}
}

View File

@@ -0,0 +1,75 @@
package net.momirealms.customfishing.utils;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTItem;
import net.momirealms.customfishing.AdventureManager;
import org.bukkit.inventory.ItemStack;
import java.util.*;
public class NBTUtil {
private final Map<?,?> nbt;
private final NBTItem nbtItem;
public NBTUtil(Map<?,?> nbt, ItemStack itemStack){
this.nbt = nbt;
this.nbtItem = new NBTItem(itemStack);
}
public NBTItem getNBTItem(){
nbt.keySet().forEach(key -> {
if (nbt.get(key) instanceof Map<?,?> map){
nbtItem.addCompound((String) key);
setTags(map, nbtItem.getCompound((String) key));
}else {
setNbt(nbtItem, (String) key, nbt.get(key));
}
});
return this.nbtItem;
}
private void setTags(Map<?,?> map, NBTCompound nbtCompound){
map.keySet().forEach(key -> {
if (map.get(key) instanceof Map map2){
nbtCompound.addCompound((String) key);
setTags(map2, nbtCompound.getCompound((String) key));
}else {
setNbt(nbtCompound, (String) key, map.get(key));
}
});
}
private void setNbt(NBTCompound nbtCompound, String key, Object value){
if (value instanceof String string){
if (string.startsWith("(Int) ")){
nbtCompound.setInteger(key, Integer.valueOf(string.substring(6)));
}else if (string.startsWith("(String) ")){
nbtCompound.setString(key, string.substring(9));
}else if (string.startsWith("(Long) ")){
nbtCompound.setLong(key, Long.valueOf(string.substring(7)));
}else if (string.startsWith("(Float) ")){
nbtCompound.setFloat(key, Float.valueOf(string.substring(8)));
} else if (string.startsWith("(Double) ")){
nbtCompound.setDouble(key, Double.valueOf(string.substring(9)));
}else if (string.startsWith("(Short) ")){
nbtCompound.setShort(key, Short.valueOf(string.substring(8)));
}else if (string.startsWith("(Boolean) ")){
nbtCompound.setBoolean(key, Boolean.valueOf(string.substring(10)));
}else if (string.startsWith("(UUID) ")){
nbtCompound.setUUID(key, UUID.fromString(string.substring(7)));
}else if (string.startsWith("(Byte) ")){
nbtCompound.setByte(key, Byte.valueOf(string.substring(7)));
}else {
nbtCompound.setString(key, string);
}
}else {
try {
nbtCompound.setInteger(key, (Integer) value);
}catch (ClassCastException e){
e.printStackTrace();
AdventureManager.consoleMessage("<red>[CustomFishing] 非Int类型数字必须加上强制转换标识!</red>");
}
}
}
}

View File

@@ -0,0 +1,85 @@
package net.momirealms.customfishing.utils;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTItem;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.momirealms.customfishing.ConfigReader;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.List;
import java.util.Map;
public class UtilInstance {
private final String key;
private final String name;
private List<String> lore;
private Map<?, ?> nbt;
private final String material;
public UtilInstance(String key, String name, String material){
this.key = key;
this.name = name;
this.material = material;
}
public String getKey(){
return this.key;
}
public List<String> getLore(){
return this.lore;
}
public String getName(){
return this.name;
}
public String getMaterial(){
return this.material;
}
public Map<?, ?> getNbt(){
return this.nbt;
}
public void setLore(List<String> lore){
this.lore = lore;
}
public void setNbt(Map<?, ?> nbt){
this.nbt = nbt;
}
/*
将实例转换为缓存中的NBT物品
*/
public static void addUtil2cache(String utilKey){
//从缓存中请求物品Item
UtilInstance util = ConfigReader.UTIL.get(utilKey);
ItemStack itemStack = new ItemStack(Material.valueOf(util.material.toUpperCase()));
NBTItem nbtItem = new NBTItem(itemStack);
//设置Name和Lore
NBTCompound display = nbtItem.addCompound("display");
display.setString("Name", GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize("<italic:false>"+util.name)));
if (util.lore != null){
List<String> lores = display.getStringList("Lore");
util.lore.forEach(lore -> lores.add(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize("<italic:false>"+lore))));
}
//设置NBT
//添加物品进入缓存
if (util.nbt != null){
NBTUtil nbtUtil = new NBTUtil(util.nbt, nbtItem.getItem());
ConfigReader.UTILITEM.put(utilKey, nbtUtil.getNBTItem().getItem());
}else {
ConfigReader.UTILITEM.put(utilKey, nbtItem.getItem());
}
}
/*
给予玩家某NBT物品
*/
public static void givePlayerUtil(Player player, String UtilKey, int amount){
ItemStack itemStack = ConfigReader.UTILITEM.get(UtilKey);
itemStack.setAmount(amount);
player.getInventory().addItem(itemStack);
}
}

View File

@@ -0,0 +1,15 @@
package net.momirealms.customfishing.utils;
public class VectorUtil {
private final double horizontal;
private final double vertical;
public VectorUtil(double horizontal, double vertical){
this.horizontal = horizontal;
this.vertical = vertical;
}
public double getHorizontal(){return this.horizontal;}
public double getVertical(){return this.vertical;}
}