From d18c7f24a71cc58180eb6ed139267b44036d3b8d Mon Sep 17 00:00:00 2001 From: 13527698822 <43772379+13527698822@users.noreply.github.com> Date: Tue, 25 Jun 2019 18:50:22 +0800 Subject: [PATCH] Initial commit --- .gitattributes | 2 + config.yml | 554 ++++++++++++++ craft.yml | 19 + message.yml | 31 + plugin.yml | 35 + src/me/ram/kungfu/KungFu.java | 208 ++++++ src/me/ram/kungfu/KungFuType.java | 5 + src/me/ram/kungfu/command/Commands.java | 308 ++++++++ src/me/ram/kungfu/config/Config.java | 322 ++++++++ src/me/ram/kungfu/data/PlayerData.java | 125 ++++ src/me/ram/kungfu/database/MySQL.java | 75 ++ src/me/ram/kungfu/database/TypeField.java | 20 + src/me/ram/kungfu/gui/Menu.java | 175 +++++ src/me/ram/kungfu/gui/MenuType.java | 5 + src/me/ram/kungfu/kungfu/Boxing.java | 42 ++ src/me/ram/kungfu/kungfu/Dart.java | 70 ++ src/me/ram/kungfu/kungfu/Dodge.java | 40 + src/me/ram/kungfu/kungfu/IronHead.java | 39 + src/me/ram/kungfu/kungfu/OverWall.java | 109 +++ src/me/ram/kungfu/kungfu/Stick.java | 122 +++ src/me/ram/kungfu/kungfu/Sword.java | 41 ++ src/me/ram/kungfu/kungfu/WaterWalk.java | 52 ++ src/me/ram/kungfu/listener/EventListener.java | 201 +++++ src/me/ram/kungfu/network/UpdateCheck.java | 73 ++ .../ram/kungfu/placeholderapi/PAPIHook.java | 22 + src/me/ram/kungfu/storage/PlayerStorage.java | 64 ++ src/me/ram/kungfu/utils/ColorUtil.java | 30 + src/me/ram/kungfu/utils/SQLUtil.java | 181 +++++ src/me/ram/kungfu/utils/SoundUtil.java | 22 + src/me/ram/kungfu/utils/URLUtil.java | 29 + src/me/ram/kungfu/utils/UnicodeUtil.java | 48 ++ src/org/bstats/metrics/Metrics.java | 695 ++++++++++++++++++ 32 files changed, 3764 insertions(+) create mode 100644 .gitattributes create mode 100644 config.yml create mode 100644 craft.yml create mode 100644 message.yml create mode 100644 plugin.yml create mode 100644 src/me/ram/kungfu/KungFu.java create mode 100644 src/me/ram/kungfu/KungFuType.java create mode 100644 src/me/ram/kungfu/command/Commands.java create mode 100644 src/me/ram/kungfu/config/Config.java create mode 100644 src/me/ram/kungfu/data/PlayerData.java create mode 100644 src/me/ram/kungfu/database/MySQL.java create mode 100644 src/me/ram/kungfu/database/TypeField.java create mode 100644 src/me/ram/kungfu/gui/Menu.java create mode 100644 src/me/ram/kungfu/gui/MenuType.java create mode 100644 src/me/ram/kungfu/kungfu/Boxing.java create mode 100644 src/me/ram/kungfu/kungfu/Dart.java create mode 100644 src/me/ram/kungfu/kungfu/Dodge.java create mode 100644 src/me/ram/kungfu/kungfu/IronHead.java create mode 100644 src/me/ram/kungfu/kungfu/OverWall.java create mode 100644 src/me/ram/kungfu/kungfu/Stick.java create mode 100644 src/me/ram/kungfu/kungfu/Sword.java create mode 100644 src/me/ram/kungfu/kungfu/WaterWalk.java create mode 100644 src/me/ram/kungfu/listener/EventListener.java create mode 100644 src/me/ram/kungfu/network/UpdateCheck.java create mode 100644 src/me/ram/kungfu/placeholderapi/PAPIHook.java create mode 100644 src/me/ram/kungfu/storage/PlayerStorage.java create mode 100644 src/me/ram/kungfu/utils/ColorUtil.java create mode 100644 src/me/ram/kungfu/utils/SQLUtil.java create mode 100644 src/me/ram/kungfu/utils/SoundUtil.java create mode 100644 src/me/ram/kungfu/utils/URLUtil.java create mode 100644 src/me/ram/kungfu/utils/UnicodeUtil.java create mode 100644 src/org/bstats/metrics/Metrics.java diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/config.yml b/config.yml new file mode 100644 index 0000000..cb38f93 --- /dev/null +++ b/config.yml @@ -0,0 +1,554 @@ +#检查更新 +update_check: true + +#数据库 +mysql: + + #启用 + enabled: false + + #地址 + host: '127.0.0.1' + + #端口 + port: '3306' + + #数据库 + database: 'KungFu' + + #用户名 + user: 'root' + + #密码 + password: 'root' + + #表 + table: "kungfu" + +#功夫宝典 +book: + + #加入游戏时给予 + join_give: true + + #允许合成 + craft: true + + #物品属性 + item: + + #物品ID + id: 340 + + #物品损坏值 + damage: 0 + + #物品名称 + name: "&a功夫宝典 &7(右键点击)" + + #物品Lore + lore: [] + +#菜单 +menu: + + #菜单标题 + title: "功夫宝典" + + #信息物品 + info_item: + + #物品ID + id: 397 + + #物品损坏值 + damage: 3 + + #物品名称 + name: "&a{player}" + + #物品Lore + lore: + - "" + - "&f银子: &a{coin}" + - "" + - "&ewww.minecraft.net" + + #关闭按钮 + close_item: + + #物品ID + id: 166 + + #物品损坏值 + damage: 0 + + #物品名称 + name: "&c关闭" + + #物品Lore + lore: [] + + #管理按钮 + manage_item: + + #物品ID + id: 404 + + #物品损坏值 + damage: 0 + + #物品名称 + name: "&a管理" + + #物品Lore + lore: [] + + #返回按钮 + back_item: + + #物品ID + id: 262 + + #物品损坏值 + damage: 0 + + #物品名称 + name: "&f返回" + + #物品Lore + lore: [] + + #物品状态 + item_state: + + #学习 + study: "&e点击学习!" + + #进阶升级 + advancement: "&e点击进阶!" + + #学成 + complete: "&a已学成!" + + #启用 + enabled: "&a启用" + + #禁用 + disable: "&c禁用" + + #管理物品Lore + manage_lore: + - "&f状态: {state}" + - "" + - "&e点击切换!" + +#功夫 +kungfu: + + #拳法 + Boxing: + + #启用 + enabled: true + + #功夫名称 + name: "拳法" + + #菜单物品 + item: + #物品ID + id: 377 + #物品损坏值 + damage: 0 + #物品名称 + name: "&a拳法" + #物品Lore + lore: + - "&7当空拳攻击生物或玩家时" + - "&7将增加 {value}% 的攻击伤害!" + - "" + - "&f当前等级: &a{level}&f/&a{fulllevel}" + - "" + - "&f学费: &a{cost} 银子" + - "" + - "{state}" + + #等级属性 + level: + + #等级1 + 1: + #升到该级所需银子 + cost: 100 + #伤害增加(百分数) + value: 50 + + #等级2 + 2: + #升到该级所需银子 + cost: 200 + #伤害增加(百分数) + value: 75 + + #等级3 + 3: + #升到该级所需银子 + cost: 500 + #伤害增加(百分数) + value: 100 + #飞镖 + Dart: + + #启用 + enabled: true + + #功夫名称 + name: "飞镖" + + #菜单物品 + item: + #物品ID + id: 261 + #物品损坏值 + damage: 0 + #物品名称 + name: "&a飞镖" + #物品Lore + lore: + - "&7手持箭并右键连续发射箭矢!" + - "&7箭矢发射速度 {value}" + - "" + - "&f当前等级: &a{level}&f/&a{fulllevel}" + - "" + - "&f学费: &a{cost} 银子" + - "" + - "{state}" + + #等级属性 + level: + + #等级1 + 1: + #升到该级所需银子 + cost: 100 + #箭矢发射速度 + value: 1 + + #等级2 + 2: + #升到该级所需银子 + cost: 200 + #箭矢发射速度 + value: 2 + + #等级3 + 3: + #升到该级所需银子 + cost: 300 + #箭矢发射速度 + value: 3 + + #轻功 + Dodge: + + #启用 + enabled: true + + #功夫名称 + name: "轻功" + + #菜单物品 + item: + #物品ID + id: 288 + #物品损坏值 + damage: 0 + #物品名称 + name: "&a轻功" + #物品Lore + lore: + - "&7从高处摔落时减少 {value}% 的掉落伤害!" + - "" + - "&f当前等级: &a{level}&f/&a{fulllevel}" + - "" + - "&f学费: &a{cost} 银子" + - "" + - "{state}" + + #等级属性 + level: + + #等级1 + 1: + #升到该级所需银子 + cost: 50 + #减少伤害(百分数) + value: 10 + + #等级2 + 2: + #升到该级所需银子 + cost: 100 + #减少伤害(百分数) + value: 30 + + #等级3 + 3: + #升到该级所需银子 + cost: 200 + #减少伤害(百分数) + value: 50 + + #铁头功 + IronHead: + + #启用 + enabled: true + + #功夫名称 + name: "铁头功" + + #菜单物品 + item: + #物品ID + id: 399 + #物品损坏值 + damage: 0 + #物品名称 + name: "&a铁头功" + #物品Lore + lore: + - "&7减少受到伤害的 {value}% !" + - "" + - "&f当前等级: &a{level}&f/&a{fulllevel}" + - "" + - "&f学费: &a{cost} 银子" + - "" + - "{state}" + + #等级属性 + level: + + #等级1 + 1: + #升到该级所需银子 + cost: 50 + #减少伤害(百分数) + value: 5 + + #等级2 + 2: + #升到该级所需银子 + cost: 100 + #减少伤害(百分数) + value: 10 + + #等级3 + 3: + #升到该级所需银子 + cost: 200 + #减少伤害(百分数) + value: 20 + + #翻墙术 + OverWall: + + #启用 + enabled: true + + #功夫名称 + name: "翻墙术" + + #菜单物品 + item: + #物品ID + id: 309 + #物品损坏值 + damage: 0 + #物品名称 + name: "&a翻墙术" + #物品Lore + lore: + - "&7面对墙壁双击 Shift 开始翻墙" + - "&7连续翻墙 {value} 次!" + - "" + - "&f当前等级: &a{level}&f/&a{fulllevel}" + - "" + - "&f学费: &a{cost} 银子" + - "" + - "{state}" + + #等级属性 + level: + + #等级1 + 1: + #升到该级所需银子 + cost: 200 + #翻墙次数 + value: 1 + + #等级2 + 2: + #升到该级所需银子 + cost: 500 + #翻墙次数 + value: 2 + + #棍法 + Stick: + + #启用 + enabled: true + + #功夫名称 + name: "棍法" + + #菜单物品 + item: + #物品ID + id: 369 + #物品损坏值 + damage: 0 + #物品名称 + name: "&a棍法" + #物品Lore + lore: + - "&7手持木棍攻击时" + - "&7将横扫面前 {value} 度内的所有目标" + - "&7并对目标造成 {damage} 点伤害!" + - "" + - "&f当前等级: &a{level}&f/&a{fulllevel}" + - "" + - "&f学费: &a{cost} 银子" + - "" + - "{state}" + + #等级属性 + level: + + #等级1 + 1: + #升到该级所需银子 + cost: 100 + #攻击角度 + value: 90 + #攻击伤害 + damage: 1 + + #等级2 + 2: + #升到该级所需银子 + cost: 200 + #攻击角度 + value: 135 + #攻击伤害 + damage: 2 + + #等级3 + 3: + #升到该级所需银子 + cost: 500 + #攻击角度 + value: 180 + #攻击伤害 + damage: 3 + + #剑法 + Sword: + + #启用 + enabled: true + + #功夫名称 + name: "剑法" + + #菜单物品 + item: + #物品ID + id: 267 + #物品损坏值 + damage: 0 + #物品名称 + name: "&a剑法" + #物品Lore + lore: + - "&7手持剑攻击时" + - "&7将增加 {value}% 的攻击伤害!" + - "" + - "&f当前等级: &a{level}&f/&a{fulllevel}" + - "" + - "&f学费: &a{cost} 银子" + - "" + - "{state}" + + #等级属性 + level: + + #等级1 + 1: + #升到该级所需银子 + cost: 150 + #伤害增加(百分数) + value: 50 + + #等级2 + 2: + #升到该级所需银子 + cost: 300 + #伤害增加(百分数) + value: 75 + + #等级3 + 3: + #升到该级所需银子 + cost: 600 + #伤害增加(百分数) + value: 100 + + #水上漂 + WaterWalk: + + #启用 + enabled: true + + #功夫名称 + name: "水上漂" + + #菜单物品 + item: + #物品ID + id: 326 + #物品损坏值 + damage: 0 + #物品名称 + name: "&a水上漂" + #物品Lore + lore: + - "&7在水面上按下 Ctrl 键开启疾跑" + - "&7即可开始水上漂!" + - "&7移动速度 {value}" + - "" + - "&f当前等级: &a{level}&f/&a{fulllevel}" + - "" + - "&f学费: &a{cost} 银子" + - "" + - "{state}" + + #等级属性 + level: + + #等级1 + 1: + #升到该级所需银子 + cost: 100 + #伤害增加(百分数) + value: 1 + + #等级2 + 2: + #升到该级所需银子 + cost: 300 + #伤害增加(百分数) + value: 2 diff --git a/craft.yml b/craft.yml new file mode 100644 index 0000000..3014323 --- /dev/null +++ b/craft.yml @@ -0,0 +1,19 @@ +book: + A: + - type: DIAMOND + B: + - type: DIAMOND + C: + - type: DIAMOND + D: + - type: EMERALD + E: + - type: BOOK + F: + - type: EMERALD + G: + - type: DIAMOND + H: + - type: DIAMOND + I: + - type: DIAMOND diff --git a/message.yml b/message.yml new file mode 100644 index 0000000..20570d0 --- /dev/null +++ b/message.yml @@ -0,0 +1,31 @@ +studied: "&b&lKungFu &f>> &e你学习了 &a{kungfu} 等级{level} &e!" +no_coin: "&b&lKungFu &f>> &c你没有足够的银子!" +look_coin: "&b&lKungFu &f>> &e玩家&f {player} &e拥有&f {coin} &e个银子!" +set_coin: "&b&lKungFu &f>> &e已将&f {player}&e 的银子设置为&f {coin}&e 个!" +give_coin: "&b&lKungFu &f>> &e已将&f {coin}&e 个银子给予&f {player}&e !" +take_coin: "&b&lKungFu &f>> &e已从&f {player}&e 的账户中扣除&f {coin}&e 个银子!" +look_kungfu: "&b&lKungFu &f>> &e玩家&f {player}&e 功夫等级为&f {level} &e级!" +set_kungfu: "&b&lKungFu &f>> &e已将&f {player}&e 的功夫等级设置为&f {level}&e 级!" +toggle_kungfu: "&b&lKungFu &f>> &e已将&f {player}&e 的功夫状态切换至&f {state}" +edit_craft: "&b&lKungFu &f>> &e合成表编辑成功,重启服务器即可生效!" +help_prefix: "&b&lKungFu &f>>" +help_main: "&e /kf &f- 显示插件信息" +help_menu: "&e /kf menu &f- 打开菜单" +help_guide: "&e /kf guide &f- 获取菜单" +help_craft: "&e /kf craft &f- 编辑合成表" +help_help: "&e /kf help &f- 显示帮助菜单" +help_reload: "&e /kf reload &f- 重载配置文件" +help_coin: "&e /kf coin &f- 玩家银子管理" +help_coin_look: "&e /kf coin look <玩家> &f- 查询玩家银子" +help_coin_set: "&e /kf coin set <玩家> <数量> &f- 设置玩家银子" +help_coin_give: "&e /kf coin give <玩家> <数量> &f- 给予玩家银子" +help_coin_take: "&e /kf coin take <玩家> <数量> &f- 扣除玩家银子" +help_kungfu: "&e /kf kungfu &f- 玩家功夫管理" +help_kungfu_look: "&e /kf kungfu look <玩家> <功夫> &f- 查看玩家功夫等级" +help_kungfu_set: "&e /kf kungfu set <玩家> <功夫> <等级> &f- 设置玩家功夫等级" +help_kungfu_toggle: "&e /kf kungfu toggle <玩家> <功夫> &f- 切换玩家功夫启用状态" +unknown_kungfu: "&b&lKungFu &f>> &f未知功夫名称! 功夫名称列表: {kungfu}" +unknown_command: "&b&lKungFu &f>> &f未知指令! 使用 &e/kf help &f显示帮助菜单." +no_permission: "&b&lKungFu &f>> &c你没有执行此命令的权限!" +invalid_integer: "&b&lKungFu &f>> &c请输入有效数值!" +reload: "&b&lKungFu &f>> &e配置文件重载完成!" diff --git a/plugin.yml b/plugin.yml new file mode 100644 index 0000000..4627c8f --- /dev/null +++ b/plugin.yml @@ -0,0 +1,35 @@ +name: KungFu +main: me.ram.kungfu.KungFu +version: 1.0.0 +author: Ram +softdepend: [PlaceholderAPI] + +commands: + kungfu: + aliases: [kf] + +permissions: + kungfu.menu: + default: op + kungfu.guide: + default: op + kungfu.craft: + default: op + kungfu.reload: + default: op + kungfu.coin.look: + default: op + kungfu.coin.set: + default: op + kungfu.coin.give: + default: op + kungfu.coin.take: + default: op + kungfu.kungfu.look: + default: op + kungfu.kungfu.set: + default: op + kungfu.kungfu.toggle: + default: op + kungfu.updatecheck: + default: op diff --git a/src/me/ram/kungfu/KungFu.java b/src/me/ram/kungfu/KungFu.java new file mode 100644 index 0000000..f61e31c --- /dev/null +++ b/src/me/ram/kungfu/KungFu.java @@ -0,0 +1,208 @@ +package me.ram.kungfu; + +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.bstats.metrics.Metrics; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; + +import me.ram.kungfu.command.Commands; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.data.PlayerData; +import me.ram.kungfu.gui.Menu; +import me.ram.kungfu.kungfu.Boxing; +import me.ram.kungfu.kungfu.Dart; +import me.ram.kungfu.kungfu.Dodge; +import me.ram.kungfu.kungfu.IronHead; +import me.ram.kungfu.kungfu.OverWall; +import me.ram.kungfu.kungfu.Stick; +import me.ram.kungfu.kungfu.Sword; +import me.ram.kungfu.kungfu.WaterWalk; +import me.ram.kungfu.listener.EventListener; +import me.ram.kungfu.network.UpdateCheck; +import me.ram.kungfu.placeholderapi.PAPIHook; + +public class KungFu extends JavaPlugin { + + private static KungFu instance; + private static Menu menu; + private static PlayerData playerdata; + private static UpdateCheck updatecheck; + + public void onEnable() { + instance = this; + Bukkit.getConsoleSender().sendMessage("f========================================"); + Bukkit.getConsoleSender().sendMessage("7"); + Bukkit.getConsoleSender().sendMessage(" bKungFu"); + Bukkit.getConsoleSender().sendMessage("7"); + Bukkit.getConsoleSender().sendMessage(" a汾: " + KungFu.getVersion()); + Bukkit.getConsoleSender().sendMessage("7"); + Bukkit.getConsoleSender().sendMessage(" a: Ram"); + Bukkit.getConsoleSender().sendMessage("7"); + Bukkit.getConsoleSender().sendMessage("f========================================"); + init(); + menu = new Menu(); + playerdata = new PlayerData(); + playerdata.loadData(); + } + + private void init() { + String prefix = "[" + this.getDescription().getName() + "] "; + Bukkit.getConsoleSender().sendMessage(prefix + "fʼز..."); + try { + Config.loadConfig(); + } catch (Exception e) { + Bukkit.getConsoleSender().sendMessage(prefix + "c: fļʧܣ"); + Bukkit.getConsoleSender().sendMessage(prefix + "cʧܣ"); + Bukkit.getPluginManager().disablePlugin(instance); + return; + } + try { + Bukkit.getConsoleSender().sendMessage(prefix + "fע..."); + registerEvents(); + Bukkit.getConsoleSender().sendMessage(prefix + "aעɹ"); + } catch (Exception e) { + Bukkit.getConsoleSender().sendMessage(prefix + "c: fעʧܣ"); + Bukkit.getConsoleSender().sendMessage(prefix + "cʧܣ"); + Bukkit.getPluginManager().disablePlugin(instance); + return; + } + try { + Bukkit.getConsoleSender().sendMessage(prefix + "fעָ..."); + Bukkit.getPluginCommand("kungfu").setExecutor(new Commands()); + Bukkit.getConsoleSender().sendMessage(prefix + "aָעɹ"); + } catch (Exception e) { + Bukkit.getConsoleSender().sendMessage(prefix + "c: fָעʧܣ"); + Bukkit.getConsoleSender().sendMessage(prefix + "cʧܣ"); + Bukkit.getPluginManager().disablePlugin(instance); + return; + } + Bukkit.getConsoleSender().sendMessage(prefix + "aسɹ"); + try { + new Metrics(this); + }catch (Exception e) {} + updatecheck = new UpdateCheck(); + updatecheck.check(); + if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { + new PAPIHook(this).hook(); + } + } + + private void registerEvents() { + Bukkit.getPluginManager().registerEvents(new EventListener(), this); + Bukkit.getPluginManager().registerEvents(new Boxing(), this); + Bukkit.getPluginManager().registerEvents(new Dart(), this); + Bukkit.getPluginManager().registerEvents(new Dodge(), this); + Bukkit.getPluginManager().registerEvents(new IronHead(), this); + Bukkit.getPluginManager().registerEvents(new OverWall(), this); + Bukkit.getPluginManager().registerEvents(new Stick(), this); + Bukkit.getPluginManager().registerEvents(new Sword(), this); + Bukkit.getPluginManager().registerEvents(new WaterWalk(), this); + } + + public static KungFu getInstance() { + return instance; + } + + public static String getVersion() { + return "1.0.0"; + } + + public Menu getMenu() { + return menu; + } + + public PlayerData getPlayerData() { + return playerdata; + } + + public UpdateCheck getUpdateCheck() { + return updatecheck; + } + + public String getServerVersion() { + String name = Bukkit.getServer().getClass().getPackage().getName(); + return name.substring(name.lastIndexOf(46) + 1); + } + + public boolean isItemInHand(Player player, Material type) { + if (getServerVersion().startsWith("v1_8")) { + return player.getInventory().getItemInHand().getType().equals(type); + }else if (player.getInventory().getItemInMainHand().getType().equals(type)) { + return true; + }else if (player.getInventory().getItemInOffHand().getType().equals(type)) { + return true; + } + return false; + } + + public boolean isItemInHand(Player player, String type) { + if (getServerVersion().startsWith("v1_8")) { + return player.getInventory().getItemInHand().getType().name().contains(type); + }else if (player.getInventory().getItemInMainHand().getType().name().contains(type)) { + return true; + }else if (player.getInventory().getItemInOffHand().getType().name().contains(type)) { + return true; + } + return false; + } + + public boolean hasItem(Player player, ItemStack item) { + for (ItemStack itemStack : player.getInventory().getContents()) { + if (itemStack != null && itemStack.isSimilar(item)) { + return true; + } + } + return false; + } + + public Material getMaterial(int id) { + if (getServerVersion().startsWith("v1_13") || getServerVersion().startsWith("v1_14")) { + for (Material type : Material.values()) { + if (type.getId() == id) { + return type; + } + } + }else { + try { + return Material.getMaterial(id); + }catch (Exception e) { + return Material.AIR; + } + } + return Material.AIR; + } + + + public KungFuType getKungFuType(String name) { + try { + return KungFuType.valueOf(name); + } catch (Exception e) { + return null; + } + } + + public boolean isInteger(String string){ + Matcher matcher = Pattern.compile("^[+-]?[0-9]+$").matcher(string); + return matcher.find(); + } + + public Map getFullLevel() { + Map fulllevel = new HashMap(); + fulllevel.put(KungFuType.Boxing, 3); + fulllevel.put(KungFuType.Dart, 3); + fulllevel.put(KungFuType.Dodge, 3); + fulllevel.put(KungFuType.IronHead, 3); + fulllevel.put(KungFuType.OverWall, 2); + fulllevel.put(KungFuType.Stick, 3); + fulllevel.put(KungFuType.Sword, 3); + fulllevel.put(KungFuType.WaterWalk, 2); + return fulllevel; + } +} diff --git a/src/me/ram/kungfu/KungFuType.java b/src/me/ram/kungfu/KungFuType.java new file mode 100644 index 0000000..07f3fe8 --- /dev/null +++ b/src/me/ram/kungfu/KungFuType.java @@ -0,0 +1,5 @@ +package me.ram.kungfu; + +public enum KungFuType { + Boxing, Dart, Dodge, IronHead, OverWall, Stick, Sword, WaterWalk +} diff --git a/src/me/ram/kungfu/command/Commands.java b/src/me/ram/kungfu/command/Commands.java new file mode 100644 index 0000000..4d80a7c --- /dev/null +++ b/src/me/ram/kungfu/command/Commands.java @@ -0,0 +1,308 @@ +package me.ram.kungfu.command; + +import java.util.List; +import java.util.Map; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; + +public class Commands implements CommandExecutor { + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { + if (cmd.getName().equalsIgnoreCase("kungfu")) { + if (args.length == 0) { + sender.sendMessage("f=========================================================="); + sender.sendMessage(""); + sender.sendMessage(" bKungFu"); + sender.sendMessage(""); + sender.sendMessage("f 汾: a" + KungFu.getVersion()); + sender.sendMessage(""); + sender.sendMessage("f : aRam"); + sender.sendMessage(""); + sender.sendMessage("f=========================================================="); + return true; + } + if (args[0].equalsIgnoreCase("help")) { + sender.sendMessage("f==========================================================="); + sender.sendMessage(""); + sender.sendMessage("bl KungFu fv" + KungFu.getVersion() + " 7by Ram"); + sender.sendMessage(""); + sender.sendMessage(Config.message_help_main); + sender.sendMessage(Config.message_help_menu); + sender.sendMessage(Config.message_help_guide); + sender.sendMessage(Config.message_help_help); + sender.sendMessage(Config.message_help_craft); + sender.sendMessage(Config.message_help_coin); + sender.sendMessage(Config.message_help_kungfu); + sender.sendMessage(Config.message_help_reload); + sender.sendMessage(""); + sender.sendMessage("f==========================================================="); + return true; + } + if (args[0].equalsIgnoreCase("menu")) { + if (!(sender instanceof Player)) { + return true; + } + if (sender.hasPermission("kungfu.menu")) { + KungFu.getInstance().getMenu().openMenu((Player) sender); + }else { + sender.sendMessage(Config.message_no_permission); + } + return true; + } + if (args[0].equalsIgnoreCase("guide")) { + if (!(sender instanceof Player)) { + return true; + } + if (sender.hasPermission("kungfu.guide")) { + ((Player) sender).getInventory().addItem(Config.book_item); + }else { + sender.sendMessage(Config.message_no_permission); + } + return true; + } + if (args[0].equalsIgnoreCase("reload")) { + if (sender.hasPermission("kungfu.reload")) { + Config.loadConfig(); + KungFu.getInstance().getPlayerData().loadData(); + sender.sendMessage(Config.message_reload); + }else { + sender.sendMessage(Config.message_no_permission); + } + return true; + } + if (args[0].equalsIgnoreCase("craft")) { + if (sender.hasPermission("kungfu.craft")) { + if (!(sender instanceof Player)) { + return true; + } + Player player = (Player) sender; + KungFu.getInstance().getMenu().openCraftMenu(player); + return true; + }else { + sender.sendMessage(Config.message_no_permission); + return true; + } + } + if (args[0].equalsIgnoreCase("coin")) { + if (args.length == 1) { + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_look); + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_set); + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_give); + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_take); + return true; + } + if (args[1].equalsIgnoreCase("look")) { + if (sender.hasPermission("kungfu.coin.look")) { + if (args.length == 3) { + sender.sendMessage(Config.message_look_coin.replace("{player}", args[2]).replace("{coin}", KungFu.getInstance().getPlayerData().getPlayerCoin(args[2]) + "")); + return true; + }else { + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_look); + return true; + } + }else { + sender.sendMessage(Config.message_no_permission); + return true; + } + } + if (args[1].equalsIgnoreCase("set")) { + if (sender.hasPermission("kungfu.coin.set")) { + if (args.length == 4) { + try { + Integer.valueOf(args[3]); + } catch (Exception e) { + sender.sendMessage(Config.message_invalid_integer); + return true; + } + KungFu.getInstance().getPlayerData().setPlayerCoin(args[2], Integer.valueOf(args[3])); + sender.sendMessage(Config.message_set_coin.replace("{player}", args[2]).replace("{coin}", args[3])); + return true; + }else { + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_set); + return true; + } + }else { + sender.sendMessage(Config.message_no_permission); + return true; + } + } + if (args[1].equalsIgnoreCase("give")) { + if (sender.hasPermission("kungfu.coin.give")) { + if (args.length == 4) { + try { + Integer.valueOf(args[3]); + } catch (Exception e) { + sender.sendMessage(Config.message_invalid_integer); + return true; + } + KungFu.getInstance().getPlayerData().setPlayerCoin(args[2], KungFu.getInstance().getPlayerData().getPlayerCoin(args[2]) + Integer.valueOf(args[3])); + sender.sendMessage(Config.message_give_coin.replace("{player}", args[2]).replace("{coin}", args[3])); + return true; + }else { + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_give); + return true; + } + }else { + sender.sendMessage(Config.message_no_permission); + return true; + } + } + if (args[1].equalsIgnoreCase("take")) { + if (sender.hasPermission("kungfu.coin.take")) { + if (args.length == 4) { + try { + Integer.valueOf(args[3]); + } catch (Exception e) { + sender.sendMessage(Config.message_invalid_integer); + return true; + } + int i = KungFu.getInstance().getPlayerData().getPlayerCoin(args[2]) - Integer.valueOf(args[3]); + if (i < 0) { + i = 0; + } + KungFu.getInstance().getPlayerData().setPlayerCoin(args[2], i); + sender.sendMessage(Config.message_take_coin.replace("{player}", args[2]).replace("{coin}", args[3])); + return true; + }else { + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_take); + return true; + } + }else { + sender.sendMessage(Config.message_no_permission); + return true; + } + } + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_look); + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_set); + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_give); + sender.sendMessage(Config.message_help_prefix + Config.message_help_coin_take); + return true; + } + if (args[0].equalsIgnoreCase("kungfu")) { + if (args.length == 1) { + sender.sendMessage(Config.message_help_prefix + Config.message_help_kungfu_look); + sender.sendMessage(Config.message_help_prefix + Config.message_help_kungfu_set); + sender.sendMessage(Config.message_help_prefix + Config.message_help_kungfu_toggle); + return true; + } + if (args[1].equalsIgnoreCase("look")) { + if (sender.hasPermission("kungfu.kungfu.look")) { + if (args.length == 4) { + KungFuType type = KungFu.getInstance().getKungFuType(args[3]); + if (type == null) { + String kfs = ""; + for (KungFuType kf : KungFuType.values()) { + kfs = kfs + (kfs.length() > 0 ? ", " : "") + kf.toString(); + } + sender.sendMessage(Config.message_unknown_kungfu.replace("{kungfu}", kfs)); + return true; + }else { + String level = KungFu.getInstance().getPlayerData().getPlayerLevel(args[2]).get(type.toString()) + ""; + if (level.equals("null")) { + level = "0"; + } + sender.sendMessage(Config.message_look_kungfu.replace("{level}", level).replace("{player}", args[2])); + return true; + } + }else { + sender.sendMessage(Config.message_help_prefix + Config.message_help_kungfu_look); + return true; + } + }else { + sender.sendMessage(Config.message_no_permission); + return true; + } + } + if (args[1].equalsIgnoreCase("set")) { + if (sender.hasPermission("kungfu.kungfu.set")) { + if (args.length == 5) { + KungFuType type = KungFu.getInstance().getKungFuType(args[3]); + if (type == null) { + String kfs = ""; + for (KungFuType kf : KungFuType.values()) { + kfs = kfs + (kfs.length() > 0 ? ", " : "") + kf.toString(); + } + sender.sendMessage(Config.message_unknown_kungfu.replace("{kungfu}", kfs)); + return true; + }else { + try { + Integer.valueOf(args[4]); + } catch (Exception e) { + sender.sendMessage(Config.message_invalid_integer); + return true; + } + int level = Integer.valueOf(args[4]); + if (level < 0 || level > KungFu.getInstance().getFullLevel().get(type)) { + sender.sendMessage(Config.message_invalid_integer); + return true; + } + Map kflevel = KungFu.getInstance().getPlayerData().getPlayerLevel(args[2]); + kflevel.put(type.toString(), level); + String str = ""; + for (String kf : kflevel.keySet()) { + str = str + (str.length() > 0 ? ", " : "") + kf + ":" + kflevel.get(kf).toString(); + } + KungFu.getInstance().getPlayerData().setPlayerLevel(args[2], str); + sender.sendMessage(Config.message_set_kungfu.replace("{level}", level + "").replace("{player}", args[2])); + return true; + } + }else { + sender.sendMessage(Config.message_help_prefix + Config.message_help_kungfu_set); + return true; + } + }else { + sender.sendMessage(Config.message_no_permission); + return true; + } + } + if (args[1].equalsIgnoreCase("toggle")) { + if (sender.hasPermission("kungfu.kungfu.toggle")) { + if (args.length == 4) { + KungFuType type = KungFu.getInstance().getKungFuType(args[3]); + if (type == null) { + String kfs = ""; + for (KungFuType kf : KungFuType.values()) { + kfs = kfs + (kfs.length() > 0 ? ", " : "") + kf.toString(); + } + sender.sendMessage(Config.message_unknown_kungfu.replace("{kungfu}", kfs)); + return true; + }else { + List list = KungFu.getInstance().getPlayerData().getPlayerDisable(args[2]); + if (list.contains(type.toString())) { + list.remove(type.toString()); + }else { + list.add(type.toString()); + } + KungFu.getInstance().getPlayerData().setPlayerDdisable(args[2], list); + String state = list.contains(type.toString()) ? Config.menu_item_state_disable : Config.menu_item_state_enabled; + sender.sendMessage(Config.message_toggle_kungfu.replace("{player}", args[2]).replace("{state}", state)); + return true; + } + }else { + sender.sendMessage(Config.message_help_prefix + Config.message_help_kungfu_toggle); + return true; + } + }else { + sender.sendMessage(Config.message_no_permission); + return true; + } + } + sender.sendMessage(Config.message_help_prefix + Config.message_help_kungfu_look); + sender.sendMessage(Config.message_help_prefix + Config.message_help_kungfu_set); + sender.sendMessage(Config.message_help_prefix + Config.message_help_kungfu_toggle); + return true; + } + sender.sendMessage(Config.message_unknown_command); + return true; + } + return false; + } +} diff --git a/src/me/ram/kungfu/config/Config.java b/src/me/ram/kungfu/config/Config.java new file mode 100644 index 0000000..4b11104 --- /dev/null +++ b/src/me/ram/kungfu/config/Config.java @@ -0,0 +1,322 @@ +package me.ram.kungfu.config; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.meta.ItemMeta; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.storage.PlayerStorage; +import me.ram.kungfu.utils.ColorUtil; + +public class Config { + + public static boolean update_check; + public static boolean mysql_enabled; + public static String mysql_host; + public static String mysql_port; + public static String mysql_database; + public static String mysql_user; + public static String mysql_password; + public static String mysql_table; + public static ItemStack book_item; + public static boolean book_join_give; + public static boolean book_craft; + public static String menu_title; + public static Integer menu_info_item_id; + public static Integer menu_info_item_damage; + public static String menu_info_item_name; + public static List menu_info_item_lore; + public static ItemStack menu_close_item; + public static ItemStack menu_manage_item; + public static ItemStack menu_back_item; + public static String menu_item_state_study; + public static String menu_item_state_advancement; + public static String menu_item_state_complete; + public static String menu_item_state_enabled; + public static String menu_item_state_disable; + public static List menu_manage_lore; + public static List kungfu_enableds; + public static Map kungfu_names; + public static Map kungfu_items; + public static Map> kungfu_lore; + public static Map> kungfu_level_cost; + public static Map> kungfu_level_value; + public static Map kungfu_stick_level_damage; + public static String message_studied; + public static String message_no_coin; + public static String message_look_coin; + public static String message_set_coin; + public static String message_give_coin; + public static String message_take_coin; + public static String message_look_kungfu; + public static String message_set_kungfu; + public static String message_toggle_kungfu; + public static String message_edit_craft; + public static String message_help_prefix; + public static String message_help_main; + public static String message_help_menu; + public static String message_help_guide; + public static String message_help_help; + public static String message_help_reload; + public static String message_help_craft; + public static String message_help_coin; + public static String message_help_coin_look; + public static String message_help_coin_set; + public static String message_help_coin_give; + public static String message_help_coin_take; + public static String message_help_kungfu; + public static String message_help_kungfu_look; + public static String message_help_kungfu_set; + public static String message_help_kungfu_toggle; + public static String message_unknown_command; + public static String message_unknown_kungfu; + public static String message_no_permission; + public static String message_invalid_integer; + public static String message_reload; + + public static void loadConfig() { + String prefix = "[" + KungFu.getInstance().getDescription().getName() + "] "; + Bukkit.getConsoleSender().sendMessage(prefix + "fڼļ..."); + KungFu.getInstance().saveDefaultConfig(); + KungFu.getInstance().reloadConfig(); + Bukkit.getConsoleSender().sendMessage(prefix + "aĬļѱ棡"); + FileConfiguration config = KungFu.getInstance().getConfig(); + update_check = config.getBoolean("update_check"); + mysql_enabled = config.getBoolean("mysql.enabled"); + mysql_host = config.getString("mysql.host"); + mysql_port = config.getString("mysql.port"); + mysql_database = config.getString("mysql.database"); + mysql_user = config.getString("mysql.user"); + mysql_password = config.getString("mysql.password"); + mysql_table = config.getString("mysql.table"); + book_join_give = config.getBoolean("book.join_give"); + book_join_give = config.getBoolean("book.craft"); + book_item = toItemStack(config.getInt("book.item.id"), config.getInt("book.item.damage"), ColorUtil.color(config.getString("book.item.name")), ColorUtil.listcolor(config.getStringList("book.item.lore"))); + menu_title = ColorUtil.color(config.getString("menu.title")) + "kfmenu"; + menu_info_item_id = config.getInt("menu.info_item.id"); + menu_info_item_damage = config.getInt("menu.info_item.damage"); + menu_info_item_name = ColorUtil.color(config.getString("menu.info_item.name")); + menu_info_item_lore = ColorUtil.listcolor(config.getStringList("menu.info_item.lore")); + menu_close_item = toItemStack(config.getInt("menu.close_item.id"), config.getInt("menu.close_item.damage"), ColorUtil.color(config.getString("menu.close_item.name")), ColorUtil.listcolor(config.getStringList("menu.close_item.lore"))); + menu_manage_item = toItemStack(config.getInt("menu.manage_item.id"), config.getInt("menu.manage_item.damage"), ColorUtil.color(config.getString("menu.manage_item.name")), ColorUtil.listcolor(config.getStringList("menu.manage_item.lore"))); + menu_back_item = toItemStack(config.getInt("menu.back_item.id"), config.getInt("menu.back_item.damage"), ColorUtil.color(config.getString("menu.back_item.name")), ColorUtil.listcolor(config.getStringList("menu.back_item.lore"))); + menu_item_state_study = ColorUtil.color(config.getString("menu.item_state.study")); + menu_item_state_advancement = ColorUtil.color(config.getString("menu.item_state.advancement")); + menu_item_state_complete = ColorUtil.color(config.getString("menu.item_state.complete")); + menu_item_state_enabled = ColorUtil.color(config.getString("menu.item_state.enabled")); + menu_item_state_disable = ColorUtil.color(config.getString("menu.item_state.disable")); + menu_manage_lore = ColorUtil.listcolor(config.getStringList("menu.manage_lore")); + kungfu_enableds = new ArrayList(); + kungfu_names = new HashMap(); + kungfu_items = new HashMap(); + kungfu_lore = new HashMap>(); + kungfu_level_cost = new HashMap>(); + kungfu_level_value = new HashMap>(); + for (KungFuType type : KungFuType.values()) { + if (config.getBoolean("kungfu." + type.toString() + ".enabled")) { + kungfu_enableds.add(type); + kungfu_names.put(type, ColorUtil.color(config.getString("kungfu." + type.toString() + ".name"))); + kungfu_items.put(type, toItemStack(config.getInt("kungfu." + type.toString() + ".item.id"), config.getInt("kungfu." + type.toString() + ".item.damage"), ColorUtil.color(config.getString("kungfu." + type.toString() + ".item.name")), type.toString())); + kungfu_lore.put(type, ColorUtil.listcolor(config.getStringList("kungfu." + type.toString() + ".item.lore"))); + kungfu_level_cost.put(type, new HashMap()); + kungfu_level_value.put(type, new HashMap()); + int i = 1; + for (;;) { + if (config.get("kungfu." + type.toString() + ".level." + i) != null) { + kungfu_level_cost.get(type).put(i, config.getInt("kungfu." + type.toString() + ".level." + i + ".cost")); + kungfu_level_value.get(type).put(i, config.getInt("kungfu." + type.toString() + ".level." + i + ".value")); + i++; + }else { + break; + } + } + if (type.equals(KungFuType.Stick)) { + kungfu_stick_level_damage = new HashMap(); + for (int d = 1; d < 4; d ++) { + kungfu_stick_level_damage.put(d, config.getDouble("kungfu." + type.toString() + ".level." + d + ".damage")); + } + } + } + } + loadMessage(); + loadCraft(); + Bukkit.getConsoleSender().sendMessage(prefix + "aļسɹ"); + PlayerStorage.update(); + } + + public static void setPlayerData(String player, String path, Object data) { + File folder = new File(KungFu.getInstance().getDataFolder(),"/players"); + if (!folder.exists()) { + folder.mkdirs(); + } + File file = new File(folder.getAbsolutePath() + "/" + player + ".yml"); + if (file.exists()) { + try { + file.createNewFile(); + } catch (IOException e) {} + } + FileConfiguration config = YamlConfiguration.loadConfiguration(file); + config.set(path, data); + try { + config.save(file); + } catch (IOException e) {} + } + + public static Object getPlayerData(String player, String path) { + File folder = new File(KungFu.getInstance().getDataFolder(),"/players"); + if (!folder.exists()) { + folder.mkdirs(); + } + File file = new File(folder.getAbsolutePath() + "/" + player + ".yml"); + FileConfiguration config = YamlConfiguration.loadConfiguration(file); + return config.get(path); + } + + private static void loadMessage() { + File folder = new File(KungFu.getInstance().getDataFolder(),"/"); + if (!folder.exists()) { + folder.mkdirs(); + } + File file = new File(folder.getAbsolutePath() + "/message.yml"); + if (!file.exists()) { + KungFu.getInstance().saveResource("message.yml", false); + } + FileConfiguration config = YamlConfiguration.loadConfiguration(file); + message_studied = ColorUtil.color(config.getString("studied")); + message_no_coin = ColorUtil.color(config.getString("no_coin")); + message_look_coin = ColorUtil.color(config.getString("look_coin")); + message_set_coin = ColorUtil.color(config.getString("set_coin")); + message_give_coin = ColorUtil.color(config.getString("give_coin")); + message_take_coin = ColorUtil.color(config.getString("take_coin")); + message_look_kungfu = ColorUtil.color(config.getString("look_kungfu")); + message_set_kungfu = ColorUtil.color(config.getString("set_kungfu")); + message_toggle_kungfu = ColorUtil.color(config.getString("toggle_kungfu")); + message_edit_craft = ColorUtil.color(config.getString("edit_craft")); + message_help_prefix = ColorUtil.color(config.getString("help_prefix")); + message_help_main = ColorUtil.color(config.getString("help_main")); + message_help_menu = ColorUtil.color(config.getString("help_menu")); + message_help_guide = ColorUtil.color(config.getString("help_guide")); + message_help_help = ColorUtil.color(config.getString("help_help")); + message_help_reload = ColorUtil.color(config.getString("help_reload")); + message_help_craft = ColorUtil.color(config.getString("help_craft")); + message_help_coin = ColorUtil.color(config.getString("help_coin")); + message_help_coin_look = ColorUtil.color(config.getString("help_coin_look")); + message_help_coin_set = ColorUtil.color(config.getString("help_coin_set")); + message_help_coin_give = ColorUtil.color(config.getString("help_coin_give")); + message_help_coin_take = ColorUtil.color(config.getString("help_coin_take")); + message_help_kungfu = ColorUtil.color(config.getString("help_kungfu")); + message_help_kungfu_look = ColorUtil.color(config.getString("help_kungfu_look")); + message_help_kungfu_set = ColorUtil.color(config.getString("help_kungfu_set")); + message_help_kungfu_toggle = ColorUtil.color(config.getString("help_kungfu_toggle")); + message_unknown_command = ColorUtil.color(config.getString("unknown_command")); + message_unknown_kungfu = ColorUtil.color(config.getString("unknown_kungfu")); + message_no_permission = ColorUtil.color(config.getString("no_permission")); + message_invalid_integer = ColorUtil.color(config.getString("invalid_integer")); + message_reload = ColorUtil.color(config.getString("reload")); + } + + private static void loadCraft() { + if (KungFu.getInstance().getServer().getRecipesFor(Config.book_item).size() > 1) { + return; + } + File folder = new File(KungFu.getInstance().getDataFolder(),"/"); + if (!folder.exists()) { + folder.mkdirs(); + } + File file = new File(folder.getAbsolutePath() + "/craft.yml"); + if (!file.exists()) { + KungFu.getInstance().saveResource("craft.yml", false); + } + FileConfiguration config = YamlConfiguration.loadConfiguration(file); + if (config.getKeys(false).contains("book")) { + ShapedRecipe shapedRecipe = new ShapedRecipe(Config.book_item); + shapedRecipe.shape(new String[] { "ABC", "DEF", "GHI" }); + String[] string = new String[] {"A", "B", "C", "D", "E", "F", "G", "H", "I"}; + int i = 0; + Set set = config.getConfigurationSection("book").getKeys(false); + for (String str : string) { + if (set.contains(str)) { + shapedRecipe.setIngredient("ABCDEFGHI".charAt(i), ItemStack.deserialize((Map) config.getList("book." + str).get(0)).getData()); + } + i++; + } + KungFu.getInstance().getServer().addRecipe(shapedRecipe); + } + } + + public static void setCraft(String path, Object object) { + File folder = new File(KungFu.getInstance().getDataFolder(),"/"); + if (!folder.exists()) { + folder.mkdirs(); + } + File file = new File(folder.getAbsolutePath() + "/craft.yml"); + if (!file.exists()) { + KungFu.getInstance().saveResource("craft.yml", false); + } + FileConfiguration filec = YamlConfiguration.loadConfiguration(file); + filec.set(path, object); + try { + filec.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static FileConfiguration getCraftConfig() { + File folder = new File(KungFu.getInstance().getDataFolder(),"/"); + if (!folder.exists()) { + folder.mkdirs(); + } + File file = new File(folder.getAbsolutePath() + "/craft.yml"); + if (!file.exists()) { + KungFu.getInstance().saveResource("craft.yml", false); + } + return YamlConfiguration.loadConfiguration(file); + } + + private static ItemStack toItemStack(int id, int damage, String name, String type) { + try { + ItemStack itemStack = new ItemStack(KungFu.getInstance().getMaterial(id), 1, (short) damage); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(name); + String l = type; + l = "" + l.replaceAll ("(.{1})", "$1"); + l = l.substring(0,l.length() - 1); + itemMeta.setLore(Arrays.asList(l)); + itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + itemStack.setItemMeta(itemMeta); + return itemStack; + }catch (Exception e) { + return new ItemStack(Material.AIR); + } + } + + private static ItemStack toItemStack(int id, int damage, String name, List lore) { + try { + ItemStack itemStack = new ItemStack(KungFu.getInstance().getMaterial(id), 1, (short) damage); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(name); + itemMeta.setLore(lore); + itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + itemStack.setItemMeta(itemMeta); + return itemStack; + }catch (Exception e) { + return new ItemStack(Material.AIR); + } + } +} diff --git a/src/me/ram/kungfu/data/PlayerData.java b/src/me/ram/kungfu/data/PlayerData.java new file mode 100644 index 0000000..9bcbbae --- /dev/null +++ b/src/me/ram/kungfu/data/PlayerData.java @@ -0,0 +1,125 @@ +package me.ram.kungfu.data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.bukkit.Bukkit; + +import me.ram.kungfu.config.Config; +import me.ram.kungfu.database.MySQL; +import me.ram.kungfu.storage.PlayerStorage; + +public class PlayerData { + + private MySQL mysql; + + public void loadData() { + if (Config.mysql_enabled) { + mysql = new MySQL(); + mysql.mysql_host = Config.mysql_host; + mysql.mysql_port = Config.mysql_port; + mysql.mysql_database = Config.mysql_database; + mysql.mysql_user = Config.mysql_user; + mysql.mysql_password = Config.mysql_password; + mysql.mysql_table = Config.mysql_table; + mysql.connectSQL(); + } + } + + public Integer getPlayerCoin(String player) { + int coin = 0; + if (Config.mysql_enabled) { + coin = mysql.getPlayerCoin(player); + }else { + Object object = Config.getPlayerData(player, "coin"); + if (object != null) { + coin = (int) object; + } + } + return coin; + } + + public Map getPlayerLevel(String player) { + Map map = new HashMap(); + Object object = null; + if (Config.mysql_enabled) { + object = mysql.getPlayerLevel(player); + }else { + object = Config.getPlayerData(player, "level"); + } + String str = ""; + if (object != null) { + str = (String) object; + } + try { + for (String kungfu : str.split(", ")) { + try { + String[] args = kungfu.split(":"); + map.put(args[0], Integer.valueOf(args[1])); + } catch (Exception e) {} + } + } catch (Exception e) {} + return map; + } + + public List getPlayerDisable(String player) { + List list = new ArrayList(); + Object object = null; + if (Config.mysql_enabled) { + object = mysql.getPlayerDisable(player); + }else { + object = Config.getPlayerData(player, "disable"); + } + String str = ""; + if (object != null) { + str = (String) object; + } + try { + for (String kungfu : str.split(", ")) { + list.add(kungfu); + } + } catch (Exception e) {} + return list; + } + + public void setPlayerCoin(String player, Integer i) { + if (Config.mysql_enabled) { + mysql.setPlayerCoin(player, i); + }else { + Config.setPlayerData(player, "coin", i); + } + } + + public void setPlayerLevel(String player, String data) { + if (Config.mysql_enabled) { + mysql.setPlayerLevel(player, data); + }else { + Config.setPlayerData(player, "level", data); + } + Map map = new HashMap(); + try { + for (String kungfu : data.split(", ")) { + try { + String[] args = kungfu.split(":"); + map.put(args[0], Integer.valueOf(args[1])); + } catch (Exception e) {} + } + } catch (Exception e) {} + PlayerStorage.setLevel(Bukkit.getPlayer(player), map); + } + + public void setPlayerDdisable(String player, List data) { + String str = ""; + for (String l : data) { + str = str + (str.length() > 0 ? ", " : "") + l; + } + if (Config.mysql_enabled) { + mysql.setPlayerDisable(player, str); + }else { + Config.setPlayerData(player, "disable", str); + } + PlayerStorage.setDisable(Bukkit.getPlayer(player), data); + } +} diff --git a/src/me/ram/kungfu/database/MySQL.java b/src/me/ram/kungfu/database/MySQL.java new file mode 100644 index 0000000..09eade8 --- /dev/null +++ b/src/me/ram/kungfu/database/MySQL.java @@ -0,0 +1,75 @@ +package me.ram.kungfu.database; + +import org.bukkit.Bukkit; + +import me.ram.kungfu.KungFu; +import me.ram.kungfu.utils.SQLUtil; + +public class MySQL { + public SQLUtil mysql; + + public String mysql_host; + public String mysql_port; + public String mysql_database; + public String mysql_user; + public String mysql_password; + public String mysql_table; + + public void connectSQL() { + String prefix = "[" + KungFu.getInstance().getDescription().getName() + "] "; + Bukkit.getConsoleSender().sendMessage(prefix + "fݿ..."); + mysql = new SQLUtil(new TypeField("name", "TEXT"), new TypeField("coin", "INTEGER"), new TypeField("level", "TEXT"), new TypeField("disable", "TEXT")); + mysql.init(mysql_host, mysql_port, mysql_database, mysql_user, mysql_password); + if (mysql.connect()) { + Bukkit.getConsoleSender().sendMessage(prefix + "aݿӳɹ"); + mysql.createTable("kungfu"); + }else { + Bukkit.getConsoleSender().sendMessage(prefix + "cݿʧܣ"); + } + } + + public void setPlayerCoin(String player, int i) { + if (mysql.isExist("name", player)) { + mysql.setData("name", player, "coin", i); + }else { + mysql.addData("name", player, i, "", ""); + } + } + + public void setPlayerLevel(String player, String level) { + if (mysql.isExist("name", player)) { + mysql.setData("name", player, "level", level); + }else { + mysql.addData("name", player, 0, level, ""); + } + } + + public void setPlayerDisable(String player, String disable) { + if (mysql.isExist("name", player)) { + mysql.setData("name", player, "disable", disable); + }else { + mysql.addData("name", player, 0, "", disable); + } + } + + public Integer getPlayerCoin(String player) { + if (mysql.isExist("name", player)) { + return (Integer) mysql.getData("name", player, "coin"); + } + return 0; + } + + public String getPlayerLevel(String player) { + if (mysql.isExist("name", player)) { + return (String) mysql.getData("name", player, "level"); + } + return ""; + } + + public String getPlayerDisable(String player) { + if (mysql.isExist("name", player)) { + return (String) mysql.getData("name", player, "disable"); + } + return ""; + } +} diff --git a/src/me/ram/kungfu/database/TypeField.java b/src/me/ram/kungfu/database/TypeField.java new file mode 100644 index 0000000..18da5ae --- /dev/null +++ b/src/me/ram/kungfu/database/TypeField.java @@ -0,0 +1,20 @@ +package me.ram.kungfu.database; + +public class TypeField { + + private String field; + private String type; + + public TypeField(String field, String type) { + this.field = field; + this.type = type; + } + + public String getField() { + return field; + } + + public String getType() { + return type; + } +} diff --git a/src/me/ram/kungfu/gui/Menu.java b/src/me/ram/kungfu/gui/Menu.java new file mode 100644 index 0000000..b2c1587 --- /dev/null +++ b/src/me/ram/kungfu/gui/Menu.java @@ -0,0 +1,175 @@ +package me.ram.kungfu.gui; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.storage.PlayerStorage; + +public class Menu { + + private Map omplayers = new HashMap(); + + public void openMenu(Player player) { + if (!isOpenMenu(player, MenuType.Main) && !isOpenMenu(player, MenuType.Manage)) { + player.closeInventory(); + } + Inventory inventory = Bukkit.createInventory(null, 54, Config.menu_title); + setMainItem(player, inventory); + player.openInventory(inventory); + omplayers.put(player.getUniqueId(), MenuType.Main); + } + + public void openManageMenu(Player player) { + if (isOpenMenu(player, MenuType.Main)) { + Inventory inventory = Bukkit.createInventory(null, 54, Config.menu_title); + setManageItem(player, inventory); + player.openInventory(inventory); + omplayers.put(player.getUniqueId(), MenuType.Manage); + } + } + + public void openCraftMenu(Player player) { + FileConfiguration config = Config.getCraftConfig(); + Inventory inventory = Bukkit.createInventory(null, InventoryType.WORKBENCH); + if (config.getKeys(false).contains("book")) { + String[] string = new String[] {"A", "B", "C", "D", "E", "F", "G", "H", "I"}; + int i = 1; + Set set = config.getConfigurationSection("book").getKeys(false); + for (String str : string) { + if (set.contains(str)) { + inventory.setItem(i, ItemStack.deserialize((Map) config.getList("book." + str).get(0))); + } + i++; + } + } + inventory.setItem(0, Config.book_item); + player.closeInventory(); + player.openInventory(inventory); + omplayers.put(player.getUniqueId(), MenuType.Craft); + player.updateInventory(); + } + + public void setMainItem(Player player, Inventory inventory) { + ItemStack infoitem = new ItemStack(KungFu.getInstance().getMaterial(Config.menu_info_item_id), 1, Short.valueOf(Config.menu_info_item_damage.toString())); + ItemMeta infometa = infoitem.getItemMeta(); + String playername = player.getDisplayName(); + if (playername == null) { + playername = player.getName(); + } + Integer coin = KungFu.getInstance().getPlayerData().getPlayerCoin(player.getName()); + infometa.setDisplayName(Config.menu_info_item_name.replace("{player}", playername).replace("{coin}", coin.toString())); + List infolore = new ArrayList(); + for (String l : Config.menu_info_item_lore) { + infolore.add(l.replace("{player}", playername).replace("{coin}", coin.toString())); + } + infometa.setLore(infolore); + infoitem.setItemMeta(infometa); + inventory.setItem(4, infoitem); + inventory.setItem(49, Config.menu_close_item); + inventory.setItem(53, Config.menu_manage_item); + Map fulllevel = KungFu.getInstance().getFullLevel(); + int i = 20; + for (KungFuType type : Config.kungfu_enableds) { + if (i == 25) { + i = 29; + } + ItemStack kungfuitem = Config.kungfu_items.get(type).clone(); + ItemMeta kungfumeta = kungfuitem.getItemMeta(); + List lore = kungfumeta.getLore(); + int level = PlayerStorage.getLevel(player, type); + String state = Config.menu_item_state_study; + if (level >= fulllevel.get(type)) { + state = Config.menu_item_state_complete; + }else if (level > 0) { + state = Config.menu_item_state_advancement; + } + String kflevel = level + ""; + if (level < 1) { + level = 1; + }else if (level > fulllevel.get(type)) { + level = fulllevel.get(type); + } + String value = Config.kungfu_level_value.get(type).get(level).toString(); + String cost = Config.kungfu_level_cost.get(type).get(level).toString(); + String damage = ""; + if (type.equals(KungFuType.Stick)) { + damage = Config.kungfu_stick_level_damage.get(level).toString(); + } + for (String l : Config.kungfu_lore.get(type)) { + lore.add(l.replace("{cost}", cost).replace("{value}", value).replace("{state}", state).replace("{damage}", damage).replace("{level}", kflevel).replace("{fulllevel}", fulllevel.get(type).toString())); + } + kungfumeta.setLore(lore); + kungfuitem.setItemMeta(kungfumeta); + inventory.setItem(i, kungfuitem); + i++; + } + } + + public void setManageItem(Player player, Inventory inventory) { + inventory.clear(); + ItemStack infoitem = new ItemStack(KungFu.getInstance().getMaterial(Config.menu_info_item_id), 1, Short.valueOf(Config.menu_info_item_damage.toString())); + ItemMeta infometa = infoitem.getItemMeta(); + String playername = player.getDisplayName(); + if (playername == null) { + playername = player.getName(); + } + Integer coin = KungFu.getInstance().getPlayerData().getPlayerCoin(player.getName()); + infometa.setDisplayName(Config.menu_info_item_name.replace("{player}", playername).replace("{coin}", coin.toString())); + List infolore = new ArrayList(); + for (String l : Config.menu_info_item_lore) { + infolore.add(l.replace("{player}", playername).replace("{coin}", coin.toString())); + } + infometa.setLore(infolore); + infoitem.setItemMeta(infometa); + inventory.setItem(4, infoitem); + inventory.setItem(49, Config.menu_back_item); + int i = 20; + for (KungFuType type : Config.kungfu_enableds) { + if (i == 25) { + i = 29; + } + ItemStack kungfuitem = Config.kungfu_items.get(type).clone(); + ItemMeta kungfumeta = kungfuitem.getItemMeta(); + List lore = kungfumeta.getLore(); + String state = Config.menu_item_state_enabled; + if (PlayerStorage.isDisable(player, type)) { + state = Config.menu_item_state_disable; + } + for (String l : Config.menu_manage_lore) { + lore.add(l.replace("{state}", state)); + } + kungfumeta.setLore(lore); + kungfuitem.setItemMeta(kungfumeta); + inventory.setItem(i, kungfuitem); + i++; + } + } + + public boolean isOpenMenu(Player player, MenuType type) { + if (omplayers.containsKey(player.getUniqueId())) { + return omplayers.get(player.getUniqueId()).equals(type); + } + return false; + } + + public void removePlayer(Player player) { + if (omplayers.containsKey(player.getUniqueId())) { + omplayers.remove(player.getUniqueId()); + } + } +} diff --git a/src/me/ram/kungfu/gui/MenuType.java b/src/me/ram/kungfu/gui/MenuType.java new file mode 100644 index 0000000..0356a48 --- /dev/null +++ b/src/me/ram/kungfu/gui/MenuType.java @@ -0,0 +1,5 @@ +package me.ram.kungfu.gui; + +public enum MenuType { + Main, Manage, Craft +} diff --git a/src/me/ram/kungfu/kungfu/Boxing.java b/src/me/ram/kungfu/kungfu/Boxing.java new file mode 100644 index 0000000..8fef2ec --- /dev/null +++ b/src/me/ram/kungfu/kungfu/Boxing.java @@ -0,0 +1,42 @@ +package me.ram.kungfu.kungfu; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.storage.PlayerStorage; + +public class Boxing implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDamageByEntity(EntityDamageByEntityEvent e) { + if (e.isCancelled()) { + return; + } + if (!(e.getDamager() instanceof Player)) { + return; + } + Player player = (Player) e.getDamager(); + KungFuType type = KungFuType.Boxing; + if (PlayerStorage.isDisable(player, type)) { + return; + } + int level = PlayerStorage.getLevel(player, type); + if (level < 1) { + return; + } + if (level > KungFu.getInstance().getFullLevel().get(type)) { + level = KungFu.getInstance().getFullLevel().get(type); + } + if (KungFu.getInstance().isItemInHand(player, Material.AIR)) { + double multiple = (Double.valueOf((int) Config.kungfu_level_value.get(type).get(level)) / 100) + 1.0; + e.setDamage(e.getDamage() * multiple); + } + } +} diff --git a/src/me/ram/kungfu/kungfu/Dart.java b/src/me/ram/kungfu/kungfu/Dart.java new file mode 100644 index 0000000..e56d1ab --- /dev/null +++ b/src/me/ram/kungfu/kungfu/Dart.java @@ -0,0 +1,70 @@ +package me.ram.kungfu.kungfu; + +import org.bukkit.Material; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.storage.PlayerStorage; + +public class Dart implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onInteract(PlayerInteractEvent e) { + Player player = (Player) e.getPlayer(); + if (!(e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) || !KungFu.getInstance().isItemInHand(player, Material.ARROW)) { + return; + } + KungFuType type = KungFuType.Dart; + if (PlayerStorage.isDisable(player, type)) { + return; + } + int level = PlayerStorage.getLevel(player, type); + if (level < 1) { + return; + } + if (level > KungFu.getInstance().getFullLevel().get(type)) { + level = KungFu.getInstance().getFullLevel().get(type); + } + e.setCancelled(true); + if (takeItem(player, Material.ARROW, 1)) { + Arrow arrow = player.launchProjectile(Arrow.class); + arrow.setShooter(player); + arrow.setVelocity(player.getLocation().getDirection().multiply((int) Config.kungfu_level_value.get(type).get(level))); + } + } + + private boolean takeItem(Player player, Material type, int amount) { + String version = KungFu.getInstance().getServerVersion(); + if (version.startsWith("v1_8")) { + ItemStack itemStack = player.getInventory().getItemInHand(); + if (itemStack != null && itemStack.getType().equals(type) && itemStack.getAmount() >= amount) { + itemStack.setAmount(itemStack.getAmount() - amount); + player.getInventory().setItemInHand(itemStack); + return true; + } + }else { + ItemStack itemStack = player.getInventory().getItemInMainHand(); + if (itemStack != null && itemStack.getType().equals(type) && itemStack.getAmount() >= amount) { + itemStack.setAmount(itemStack.getAmount() - amount); + player.getInventory().setItemInMainHand(itemStack); + return true; + } + itemStack = player.getInventory().getItemInOffHand(); + if (itemStack != null && itemStack.getType().equals(type) && itemStack.getAmount() >= amount) { + itemStack.setAmount(itemStack.getAmount() - amount); + player.getInventory().setItemInOffHand(itemStack); + return true; + } + } + return false; + } +} diff --git a/src/me/ram/kungfu/kungfu/Dodge.java b/src/me/ram/kungfu/kungfu/Dodge.java new file mode 100644 index 0000000..515f3c4 --- /dev/null +++ b/src/me/ram/kungfu/kungfu/Dodge.java @@ -0,0 +1,40 @@ +package me.ram.kungfu.kungfu; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.storage.PlayerStorage; + +public class Dodge implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDamageByEntity(EntityDamageEvent e) { + if (e.isCancelled()) { + return; + } + if (!(e.getEntity() instanceof Player) || !e.getCause().equals(DamageCause.FALL)) { + return; + } + Player player = (Player) e.getEntity(); + KungFuType type = KungFuType.Dodge; + if (PlayerStorage.isDisable(player, type)) { + return; + } + int level = PlayerStorage.getLevel(player, type); + if (level < 1) { + return; + } + if (level > KungFu.getInstance().getFullLevel().get(type)) { + level = KungFu.getInstance().getFullLevel().get(type); + } + double multiple = 1.0 - Double.valueOf((int) Config.kungfu_level_value.get(type).get(level)) / 100; + e.setDamage(e.getDamage() * multiple); + } +} diff --git a/src/me/ram/kungfu/kungfu/IronHead.java b/src/me/ram/kungfu/kungfu/IronHead.java new file mode 100644 index 0000000..c661e39 --- /dev/null +++ b/src/me/ram/kungfu/kungfu/IronHead.java @@ -0,0 +1,39 @@ +package me.ram.kungfu.kungfu; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.storage.PlayerStorage; + +public class IronHead implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDamage(EntityDamageEvent e) { + if (e.isCancelled()) { + return; + } + if (!(e.getEntity() instanceof Player)) { + return; + } + Player player = (Player) e.getEntity(); + KungFuType type = KungFuType.IronHead; + if (PlayerStorage.isDisable(player, type)) { + return; + } + int level = PlayerStorage.getLevel(player, type); + if (level < 1) { + return; + } + if (level > KungFu.getInstance().getFullLevel().get(type)) { + level = KungFu.getInstance().getFullLevel().get(type); + } + double multiple = 1.0 - Double.valueOf((int) Config.kungfu_level_value.get(type).get(level)) / 100; + e.setDamage(e.getDamage() * multiple); + } +} diff --git a/src/me/ram/kungfu/kungfu/OverWall.java b/src/me/ram/kungfu/kungfu/OverWall.java new file mode 100644 index 0000000..68a1630 --- /dev/null +++ b/src/me/ram/kungfu/kungfu/OverWall.java @@ -0,0 +1,109 @@ +package me.ram.kungfu.kungfu; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.PlayerToggleSneakEvent; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.storage.PlayerStorage; + +public class OverWall implements Listener { + + private Map sneakinterval = new HashMap(); + private Map players = new HashMap(); + + @EventHandler(priority = EventPriority.HIGHEST) + public void onToggleSneak(PlayerToggleSneakEvent e) { + Player player = e.getPlayer(); + if (!player.isSneaking()) { + return; + } + KungFuType type = KungFuType.OverWall; + if (PlayerStorage.isDisable(player, type)) { + return; + } + int level = PlayerStorage.getLevel(player, type); + if (level < 1) { + return; + } + if (level > KungFu.getInstance().getFullLevel().get(type)) { + level = KungFu.getInstance().getFullLevel().get(type); + } + if ((System.currentTimeMillis() - sneakinterval.getOrDefault(player.getUniqueId(), (long) 0)) < 500) { + Location location = player.getLocation(); + Block block = player.getTargetBlock((Set)null, 1); + Block block2 = location.clone().add(0, -1, 0).getBlock(); + if (block2 != null && !block2.getType().equals(Material.AIR) && block != null && !block.getType().equals(Material.AIR) && block.getY() > location.getBlockY() && block.getX() != location.getX() && block.getZ() != location.getZ()) { + overWall(player, (int) Config.kungfu_level_value.get(type).get(level)); + } + }else { + sneakinterval.put(player.getUniqueId(), System.currentTimeMillis()); + } + } + + @EventHandler + public void onChangedWorld(PlayerChangedWorldEvent e) { + Player player = e.getPlayer(); + if (players.containsKey(player.getUniqueId())) { + players.get(player.getUniqueId()).cancel(); + players.remove(player.getUniqueId()); + } + } + + @EventHandler + public void onTeleport(PlayerTeleportEvent e) { + Player player = e.getPlayer(); + if (players.containsKey(player.getUniqueId())) { + players.get(player.getUniqueId()).cancel(); + players.remove(player.getUniqueId()); + } + } + + @EventHandler + public void onQuit(PlayerQuitEvent e) { + Player player = e.getPlayer(); + if (players.containsKey(player.getUniqueId())) { + players.get(player.getUniqueId()).cancel(); + players.remove(player.getUniqueId()); + } + } + + private void overWall(Player player, int a) { + players.put(player.getUniqueId(), new BukkitRunnable() { + int i = 0; + @Override + public void run() { + if (i >= a) { + cancel(); + players.remove(player.getUniqueId()); + } + Location location = player.getLocation(); + Block block = player.getTargetBlock((Set)null, 1); + if (player.isOnline() && !player.isDead() && block != null && !block.getType().equals(Material.AIR) && block.getX() != location.getX() && block.getZ() != location.getZ()) { + player.setVelocity(player.getLocation().getDirection().multiply(0.5).setY(0.65)); + i++; + }else { + cancel(); + players.remove(player.getUniqueId()); + } + } + }.runTaskTimer(KungFu.getInstance(), 0L, 5L)); + } +} diff --git a/src/me/ram/kungfu/kungfu/Stick.java b/src/me/ram/kungfu/kungfu/Stick.java new file mode 100644 index 0000000..8b6a384 --- /dev/null +++ b/src/me/ram/kungfu/kungfu/Stick.java @@ -0,0 +1,122 @@ +package me.ram.kungfu.kungfu; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.util.BlockIterator; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.storage.PlayerStorage; + +public class Stick implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDamageByEntity(EntityDamageByEntityEvent e) { + if (!(e.getDamager() instanceof Player)) { + return; + } + Player player = (Player) e.getDamager(); + Entity entity = e.getEntity(); + if (entity.hasMetadata("KungFu-Stick")) { + entity.removeMetadata("KungFu-Stick", KungFu.getInstance()); + return; + } + if (!KungFu.getInstance().isItemInHand(player, Material.STICK) || !entity.getWorld().equals(player.getWorld()) || entity.getLocation().distance(player.getLocation()) > 4) { + return; + } + stick(player, entity, e.getDamage()); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onInteract(PlayerInteractEvent e) { + Player player = e.getPlayer(); + if (KungFu.getInstance().isItemInHand(player, Material.STICK) && (e.getAction().equals(Action.LEFT_CLICK_AIR) || e.getAction().equals(Action.LEFT_CLICK_BLOCK))) { + stick(player, null, 0); + } + } + + private Double stick(Player player, Entity entity, double d) { + KungFuType type = KungFuType.Stick; + if (PlayerStorage.isDisable(player, type)) { + return d; + } + int level = PlayerStorage.getLevel(player, type); + if (level < 1) { + return d; + } + if (level > KungFu.getInstance().getFullLevel().get(type)) { + level = KungFu.getInstance().getFullLevel().get(type); + } + for (Entity ent : player.getNearbyEntities(2.5, 2, 2.5)) { + if (player.getEntityId() != ent.getEntityId() && ent instanceof LivingEntity && (entity == null || entity.getEntityId() != ent.getEntityId())) { + Location playerloc = player.getLocation().clone().add(0, 1, 0); + Location entityloc = ent.getLocation().clone(); + double yaw = Math.toDegrees(Math.atan((playerloc.getX() - entityloc.getX()) / (playerloc.getZ() - entityloc.getZ()))); + yaw = playerloc.getZ() < entityloc.getZ() ? -yaw : (-yaw + 180); + double pyaw = playerloc.getYaw(); + playerloc.setYaw((float) yaw); + yaw = yaw - pyaw; + yaw = yaw > 180 ? yaw - 360 : yaw; + yaw = yaw < -180 ? yaw + 360 : yaw; + yaw = yaw > 0 ? yaw : -yaw; + double xd = playerloc.getX() > entityloc.getX() ? (playerloc.getX() - entityloc.getX()) : (entityloc.getX() - playerloc.getX()); + double zd = playerloc.getZ() > entityloc.getZ() ? (playerloc.getZ() - entityloc.getZ()) : (entityloc.getZ() - playerloc.getZ()); + double pitch = 0; + if (xd > zd) { + pitch = Math.toDegrees(Math.atan((playerloc.getY() - entityloc.getY()) / (playerloc.getX() - entityloc.getX()))); + }else { + pitch = Math.toDegrees(Math.atan((playerloc.getY() - entityloc.getY()) / (playerloc.getZ() - entityloc.getZ()))); + } + pitch = playerloc.getY() > entityloc.getY() ? (pitch < 0 ? -pitch : pitch) : (pitch > 0 ? -pitch : pitch); + playerloc.setPitch((float) pitch); + if (yaw <= ((int) Config.kungfu_level_value.get(type).get(level) / 2)) { + try { + List list = getLineOfSight(playerloc, (int) playerloc.distance(entityloc)); + boolean damage = true; + for (Block block : list) { + if (!block.getType().equals(Material.AIR)) { + damage = false; + break; + } + } + if (damage) { + ent.setMetadata("KungFu-Stick", new FixedMetadataValue(KungFu.getInstance(), System.currentTimeMillis())); + LivingEntity livingEntity = (LivingEntity) ent; + livingEntity.damage(Config.kungfu_stick_level_damage.get(level), player); + } + }catch (Exception e) {} + } + } + } + return d + Double.valueOf(Config.kungfu_stick_level_damage.get(level)); + } + + private List getLineOfSight(Location location, int max) { + List blocks = new ArrayList(); + Iterator iterator = new BlockIterator(location, 1, max); + while (iterator.hasNext()) { + Block block = iterator.next(); + blocks.add(block); + if (!block.getType().equals(Material.AIR)) { + break; + } + } + return blocks; + } +} diff --git a/src/me/ram/kungfu/kungfu/Sword.java b/src/me/ram/kungfu/kungfu/Sword.java new file mode 100644 index 0000000..62a37a6 --- /dev/null +++ b/src/me/ram/kungfu/kungfu/Sword.java @@ -0,0 +1,41 @@ +package me.ram.kungfu.kungfu; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.storage.PlayerStorage; + +public class Sword implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDamageByEntity(EntityDamageByEntityEvent e) { + if (e.isCancelled()) { + return; + } + if (!(e.getDamager() instanceof Player)) { + return; + } + Player player = (Player) e.getDamager(); + KungFuType type = KungFuType.Sword; + if (PlayerStorage.isDisable(player, type)) { + return; + } + int level = PlayerStorage.getLevel(player, type); + if (level < 1) { + return; + } + if (level > KungFu.getInstance().getFullLevel().get(type)) { + level = KungFu.getInstance().getFullLevel().get(type); + } + if (KungFu.getInstance().isItemInHand(player, "_SWORD")) { + double multiple = (Double.valueOf((int) Config.kungfu_level_value.get(type).get(level)) / 100) + 1.0; + e.setDamage(e.getDamage() * multiple); + } + } +} diff --git a/src/me/ram/kungfu/kungfu/WaterWalk.java b/src/me/ram/kungfu/kungfu/WaterWalk.java new file mode 100644 index 0000000..c411ab8 --- /dev/null +++ b/src/me/ram/kungfu/kungfu/WaterWalk.java @@ -0,0 +1,52 @@ +package me.ram.kungfu.kungfu; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.GameMode; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerMoveEvent; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.storage.PlayerStorage; + +public class WaterWalk implements Listener { + + private Map moveinterval = new HashMap(); + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerMove(PlayerMoveEvent e) { + Player player = e.getPlayer(); + if (e.isCancelled() || !player.isSprinting()) { + return; + } + if ((System.currentTimeMillis() - moveinterval.getOrDefault(player.getUniqueId(), (long) 0)) < 100) { + return; + } + moveinterval.put(player.getUniqueId(), System.currentTimeMillis()); + Block block = player.getLocation().clone().getBlock(); + Block block2 = player.getLocation().clone().add(0, -1, 0).getBlock(); + Block block3 = player.getLocation().clone().add(0, 1, 0).getBlock(); + if ((player.getGameMode() == GameMode.SPECTATOR || (block != null && block.getType().name().contains("WATER")) || (block2 != null && block2.getType().name().contains("WATER"))) && (block3 == null || !block3.getType().name().contains("WATER"))) { + KungFuType type = KungFuType.WaterWalk; + if (PlayerStorage.isDisable(player, type)) { + return; + } + int level = PlayerStorage.getLevel(player, type); + if (level < 1) { + return; + } + if (level > KungFu.getInstance().getFullLevel().get(type)) { + level = KungFu.getInstance().getFullLevel().get(type); + } + player.setVelocity(player.getLocation().getDirection().multiply(0.3).multiply(((int) Config.kungfu_level_value.get(type).get(level))).setY(0.2)); + } + } +} diff --git a/src/me/ram/kungfu/listener/EventListener.java b/src/me/ram/kungfu/listener/EventListener.java new file mode 100644 index 0000000..6f2fd0f --- /dev/null +++ b/src/me/ram/kungfu/listener/EventListener.java @@ -0,0 +1,201 @@ +package me.ram.kungfu.listener; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.scheduler.BukkitRunnable; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.gui.MenuType; +import me.ram.kungfu.storage.PlayerStorage; +import me.ram.kungfu.utils.SoundUtil; + +public class EventListener implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onClick(InventoryClickEvent e) { + Player player = (Player) e.getWhoClicked(); + Inventory inventory = e.getInventory(); + int slot = e.getRawSlot(); + if (KungFu.getInstance().getMenu().isOpenMenu(player, MenuType.Craft)) { + if (slot == 0) { + e.setCancelled(true); + } + if (e.isShiftClick()) { + e.setCancelled(true); + } + new BukkitRunnable() { + @Override + public void run() { + player.updateInventory(); + } + }.runTaskLater(KungFu.getInstance(), 3L); + } else if (KungFu.getInstance().getMenu().isOpenMenu(player, MenuType.Main)) { + e.setCancelled(true); + if (!e.isLeftClick()) { + return; + } + if (slot == 49) { + player.playSound(player.getLocation(), SoundUtil.getSound("CLICK", "UI_BUTTON_CLICK"), 0.35f, 1f); + player.closeInventory(); + return; + } + if (slot == 53) { + player.playSound(player.getLocation(), SoundUtil.getSound("CLICK", "UI_BUTTON_CLICK"), 0.35f, 1f); + KungFu.getInstance().getMenu().openManageMenu(player); + return; + } + ItemStack itemStack = e.getCurrentItem(); + if (itemStack != null && !itemStack.getType().equals(Material.AIR)) { + ItemMeta itemMeta = itemStack.getItemMeta(); + if (itemMeta.hasLore()) { + KungFuType type = KungFu.getInstance().getKungFuType(itemMeta.getLore().get(0).replace("", "")); + if (type != null) { + int level = PlayerStorage.getLevel(player, type); + int coin = KungFu.getInstance().getPlayerData().getPlayerCoin(player.getName()); + if (level < KungFu.getInstance().getFullLevel().get(type)) { + if (level < 1) { + level = 1; + } + int cost = Config.kungfu_level_cost.get(type).get(level); + if (coin >= cost) { + Map kflevel = PlayerStorage.getLevel(player); + kflevel.put(type.toString(), kflevel.getOrDefault(type.toString(), 0) + 1); + String str = ""; + for (String kf : kflevel.keySet()) { + str = str + (str.length() > 0 ? ", " : "") + kf + ":" + kflevel.get(kf).toString(); + } + KungFu.getInstance().getPlayerData().setPlayerCoin(player.getName(), coin - cost); + KungFu.getInstance().getPlayerData().setPlayerLevel(player.getName(), str); + player.closeInventory(); + player.sendMessage(Config.message_studied.replace("{kungfu}", Config.kungfu_names.get(type)).replace("{level}", kflevel.get(type.toString()).toString())); + player.playSound(player.getLocation(), SoundUtil.getSound("ORB_PICKUP", "ENTITY_EXPERIENCE_ORB_PICKUP"), 1f, 1f); + }else { + player.playSound(player.getLocation(), SoundUtil.getSound("ENDERMAN_TELEPORT", "ENTITY_ENDERMEN_TELEPORT"), 1f, 0.5f); + player.sendMessage(Config.message_no_coin); + } + } + } + } + } + }else if (KungFu.getInstance().getMenu().isOpenMenu(player, MenuType.Manage)) { + e.setCancelled(true); + if (!e.isLeftClick()) { + return; + } + if (slot == 49) { + player.playSound(player.getLocation(), SoundUtil.getSound("CLICK", "UI_BUTTON_CLICK"), 0.35f, 1f); + KungFu.getInstance().getMenu().openMenu(player); + return; + } + ItemStack itemStack = e.getCurrentItem(); + if (itemStack != null && !itemStack.getType().equals(Material.AIR)) { + ItemMeta itemMeta = itemStack.getItemMeta(); + if (itemMeta.hasLore()) { + KungFuType type = KungFu.getInstance().getKungFuType(itemMeta.getLore().get(0).replace("", "")); + if (type != null) { + List list = new ArrayList(); + list.addAll(PlayerStorage.getDisable(player)); + if (list.contains(type.toString())) { + list.remove(type.toString()); + }else { + list.add(type.toString()); + } + KungFu.getInstance().getPlayerData().setPlayerDdisable(player.getName(), list); + KungFu.getInstance().getMenu().setManageItem(player, inventory); + player.playSound(player.getLocation(), SoundUtil.getSound("CLICK", "UI_BUTTON_CLICK"), 0.35f, 1f); + } + } + } + } + } + + @EventHandler + public void onJoin(PlayerJoinEvent e) { + Player player = e.getPlayer(); + new BukkitRunnable() { + @Override + public void run() { + if (player.isOnline()) { + PlayerStorage.setLevel(player, KungFu.getInstance().getPlayerData().getPlayerLevel(player.getName())); + } + } + }.runTaskLater(KungFu.getInstance(), 1L); + if (Config.book_join_give) { + new BukkitRunnable() { + @Override + public void run() { + if (player.isOnline() && !KungFu.getInstance().hasItem(player, Config.book_item)) { + player.getInventory().addItem(Config.book_item); + } + } + }.runTaskLater(KungFu.getInstance(), 1L); + } + new BukkitRunnable() { + @Override + public void run() { + KungFu.getInstance().getUpdateCheck().playerJoin(player); + } + }.runTaskLater(KungFu.getInstance(), 5L); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onInteract(PlayerInteractEvent e) { + Player player = e.getPlayer(); + ItemStack itemStack = e.getItem(); + if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) && itemStack != null && itemStack.isSimilar(Config.book_item)) { + e.setCancelled(true); + KungFu.getInstance().getMenu().openMenu(player); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onClose(InventoryCloseEvent e) { + Inventory inventory = e.getInventory(); + Player player = (Player) e.getPlayer(); + if (KungFu.getInstance().getMenu().isOpenMenu(player, MenuType.Craft)) { + String[] iid = new String[] {"A", "B", "C", "D", "E", "F", "G", "H", "I"}; + int i = 1; + for (String id : iid) { + ItemStack itemStack = inventory.getItem(i); + if (itemStack != null && !itemStack.getType().equals(Material.AIR)) { + List list = new ArrayList(); + list.add(itemStack.serialize()); + Config.setCraft("book." + id, list); + }else { + Config.setCraft("book." + id, null); + } + i++; + } + player.sendMessage(Config.message_edit_craft); + return; + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onCloseHighest(InventoryCloseEvent e) { + KungFu.getInstance().getMenu().removePlayer((Player) e.getPlayer()); + } + + @EventHandler + public void onQuit(PlayerQuitEvent e) { + KungFu.getInstance().getMenu().removePlayer(e.getPlayer()); + } +} diff --git a/src/me/ram/kungfu/network/UpdateCheck.java b/src/me/ram/kungfu/network/UpdateCheck.java new file mode 100644 index 0000000..de0f8cb --- /dev/null +++ b/src/me/ram/kungfu/network/UpdateCheck.java @@ -0,0 +1,73 @@ +package me.ram.kungfu.network; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import me.ram.kungfu.KungFu; +import me.ram.kungfu.config.Config; +import me.ram.kungfu.utils.URLUtil; +import me.ram.kungfu.utils.UnicodeUtil; + +public class UpdateCheck { + + private String version; + private String post; + private String[] update; + + public void check() { + if (Config.update_check) { + new BukkitRunnable() { + @Override + public void run() { + String document = URLUtil.getDocumentAt("https://raw.githubusercontent.com/13527698822/UpdateCheck/master/KungFu.yml"); + if (document != null && !document.equals("")) { + String[] info = document.split(","); + version = info[0]; + post = info[1]; + update = info[2].split(";"); + if (!version.equals(KungFu.getVersion())) { + sendInfo(Bukkit.getConsoleSender()); + } + } + } + }.runTaskLaterAsynchronously(KungFu.getInstance(), 5L); + new BukkitRunnable() { + @Override + public void run() { + String document = URLUtil.getDocumentAt("https://raw.githubusercontent.com/13527698822/UpdateCheck/master/KungFu.yml"); + if (document != null && !document.equals("")) { + String[] info = document.split(","); + version = info[0]; + post = info[1]; + update = info[2].split(";"); + } + } + }.runTaskTimerAsynchronously(KungFu.getInstance(), 72000L, 72000L); + } + } + public void playerJoin(Player player) { + if (Config.update_check && version != null && post != null && update != null) { + if (player.hasPermission("kungfu.updatecheck") && !version.equals(KungFu.getVersion())) { + sendInfo(player); + } + } + } + private void sendInfo(CommandSender sender) { + new BukkitRunnable() { + @Override + public void run() { + sender.sendMessage(""); + sender.sendMessage("blKungFu f>> f⵽һõİ汾£"); + sender.sendMessage(" fǰ汾: a" + KungFu.getVersion()); + sender.sendMessage(" f°汾: a" + version); + sender.sendMessage(" f: "); + for (int i = 0; i < update.length; i++) { + sender.sendMessage(" f" + (i + 1) + ".e" + UnicodeUtil.unicodeToCn(update[i])); + } + sender.sendMessage(" fµַ: bn" + post); + } + }.runTaskLaterAsynchronously(KungFu.getInstance(), 5L); + } +} diff --git a/src/me/ram/kungfu/placeholderapi/PAPIHook.java b/src/me/ram/kungfu/placeholderapi/PAPIHook.java new file mode 100644 index 0000000..c040fea --- /dev/null +++ b/src/me/ram/kungfu/placeholderapi/PAPIHook.java @@ -0,0 +1,22 @@ +package me.ram.kungfu.placeholderapi; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import me.clip.placeholderapi.external.EZPlaceholderHook; +import me.ram.kungfu.KungFu; + +public class PAPIHook extends EZPlaceholderHook { + + public PAPIHook(Plugin plugin) { + super(plugin, "kungfu"); + } + + public String onPlaceholderRequest(Player player, String arg) { + if (player != null && arg.equalsIgnoreCase("coin")) { + return String.valueOf(KungFu.getInstance().getPlayerData().getPlayerCoin(player.getName())); + } + return "null"; + } + +} diff --git a/src/me/ram/kungfu/storage/PlayerStorage.java b/src/me/ram/kungfu/storage/PlayerStorage.java new file mode 100644 index 0000000..935ce19 --- /dev/null +++ b/src/me/ram/kungfu/storage/PlayerStorage.java @@ -0,0 +1,64 @@ +package me.ram.kungfu.storage; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import me.ram.kungfu.KungFuType; +import me.ram.kungfu.KungFu; + +public class PlayerStorage { + + private static Map> level = new HashMap>(); + private static Map> disable = new HashMap>(); + + public static Map getLevel(Player player) { + return level.getOrDefault(player.getUniqueId(), new HashMap()); + } + + public static Integer getLevel(Player player, KungFuType type) { + return level.getOrDefault(player.getUniqueId(), new HashMap()).getOrDefault(type.toString(), 0); + } + + public static void setLevel(Player player, Map level) { + Map map = new HashMap(); + for (String kungfu : level.keySet()) { + map.put(kungfu, level.get(kungfu)); + } + PlayerStorage.level.put(player.getUniqueId(), map); + } + + public static boolean isDisable(Player player, KungFuType type) { + return disable.getOrDefault(player.getUniqueId(), new ArrayList()).contains(type.toString()); + } + + public static List getDisable(Player player) { + return disable.getOrDefault(player.getUniqueId(), new ArrayList()); + } + + public static void setDisable(Player player, List disable) { + PlayerStorage.disable.put(player.getUniqueId(), disable); + } + + public static void update() { + level = new HashMap>(); + disable = new HashMap>(); + for (Player player : Bukkit.getOnlinePlayers()) { + new BukkitRunnable() { + @Override + public void run() { + if (player.isOnline()) { + PlayerStorage.setLevel(player, KungFu.getInstance().getPlayerData().getPlayerLevel(player.getName())); + PlayerStorage.setDisable(player, KungFu.getInstance().getPlayerData().getPlayerDisable(player.getName())); + } + } + }.runTaskLater(KungFu.getInstance(), 1L); + } + } +} diff --git a/src/me/ram/kungfu/utils/ColorUtil.java b/src/me/ram/kungfu/utils/ColorUtil.java new file mode 100644 index 0000000..09d004b --- /dev/null +++ b/src/me/ram/kungfu/utils/ColorUtil.java @@ -0,0 +1,30 @@ +package me.ram.kungfu.utils; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.ChatColor; + +public class ColorUtil { + + public static String color(String s) { + return ChatColor.translateAlternateColorCodes('&', s); + } + public static List listcolor(List list) { + List clist = new ArrayList(); + for (String l : list) { + clist.add(ChatColor.translateAlternateColorCodes('&', l)); + } + return clist; + } + public static String remcolor(String s) { + return ChatColor.stripColor(s); + } + public static List remlistcolor(List list) { + List clist = new ArrayList(); + for (String l : list) { + clist.add(ChatColor.stripColor(l)); + } + return clist; + } +} diff --git a/src/me/ram/kungfu/utils/SQLUtil.java b/src/me/ram/kungfu/utils/SQLUtil.java new file mode 100644 index 0000000..2a17d0a --- /dev/null +++ b/src/me/ram/kungfu/utils/SQLUtil.java @@ -0,0 +1,181 @@ +package me.ram.kungfu.utils; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import me.ram.kungfu.database.TypeField; + +public class SQLUtil { + + private String host; + private String port; + private String database; + private String user; + private String password; + private String table; + private Connection connection; + private Statement statement; + private TypeField[] fields; + + public SQLUtil (TypeField... fields) { + this.fields = fields; + } + + public void init(String host, String port, String database, String user, String password) { + this.host = host; + this.port = port; + this.database = database; + this.user = user; + this.password = password; + } + + public boolean connect() { + if (connection != null) { + close(); + } + String url = "jdbc:mysql://" + host + ":" + port + "/" + database + "?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true"; + try { + connection = DriverManager.getConnection(url, user, password); + statement = connection.createStatement(); + } catch (SQLException e) { + return false; + } + return true; + } + + public void close() { + if (connection != null) { + try { + connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + + public void createTable(String table) { + this.table = table; + try { + connection.prepareStatement("create table if not exists " + table + "(" + getFields() + ")").executeUpdate(); + connection.prepareStatement("alter table " + table + " convert to character set utf8"); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public boolean isExist(String key, String keydata) { + try { + return statement.executeQuery("select 1 from " + table + " where " + key + "='" + keydata + "'").next(); + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + } + + public void deleteData(String key, String keyData) { + try { + PreparedStatement preparedstatement = connection.prepareStatement("delete from " + table + " where " + key + "=?"); + preparedstatement.setString(1, keyData); + preparedstatement.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public Object getData(String key, String keydata, String value) { + try { + ResultSet resultSet = statement.executeQuery("select " + value + " from " + table + " where " + key + "='" + keydata + "'"); + if (resultSet.next()) { + Object data = resultSet.getObject(1); + return data; + } + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + + public void addData(String key, Object... data) { + try { + PreparedStatement preparedstatement = connection.prepareStatement("select * from " + table + " where " + key + "=?"); + preparedstatement.setObject(1, data[0]); + ResultSet resultSet = preparedstatement.executeQuery(); + if (resultSet.next()) { + preparedstatement = connection.prepareStatement("update " + table + " " + getSettingSentence(data) + " where " + key + "=?"); + preparedstatement.setObject(1, data[0]); + preparedstatement.executeUpdate(); + } else { + connection.prepareStatement("insert into " + table + " values(" + getInsertSentence(data) + ")").executeUpdate(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public void setData(String key, String keydata, String value, Object data) { + try { + ResultSet resultSet = statement.executeQuery("select 1 from " + table + " where " + key + "='" + keydata + "'"); + if (!resultSet.next()) { + statement.executeUpdate("insert into " + table + " values('" + keydata + "','" + data + "')"); + } else { + resultSet = statement.executeQuery("select " + value + " from " + table + " where " + key + "='" + keydata + "'"); + statement.executeUpdate("update " + table + " set " + value + "='" + data + "' where " + key + "='" + keydata + "'"); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + private String getFields() { + String str = ""; + for (TypeField field : fields) { + str = str + ((str.length() > 0 ? "," : "") + field.getField() + " " + field.getType()); + } + return str; + } + + private String getSettingSentence(Object... data) { + String str = ""; + for (int i = 0; i < fields.length; ++i) { + str = str + (str.length() > 0 ? " , " : "" ) + "set " + fields[i].getField() + "='" + data[i] + "'"; + } + return str; + } + + private String getInsertSentence(Object... data) { + String str = ""; + for (int i = 0; i < data.length; ++i) { + str = str + (str.length() > 0 ? "," : "" ) + "'" + data[i] + "'"; + } + return str; + } + + public String getTable() { + return table; + } + + public void setTable(String table) { + this.table = table; + } + + public Connection getConnection() { + return connection; + } + + public Statement getStatement() { + return statement; + } + + public ResultSet executeQuery(String sql) { + try { + return statement.executeQuery(sql); + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/src/me/ram/kungfu/utils/SoundUtil.java b/src/me/ram/kungfu/utils/SoundUtil.java new file mode 100644 index 0000000..6b88e0c --- /dev/null +++ b/src/me/ram/kungfu/utils/SoundUtil.java @@ -0,0 +1,22 @@ +package me.ram.kungfu.utils; + +import org.bukkit.Bukkit; +import org.bukkit.Sound; + +public class SoundUtil { + + public static Sound getSound(String oldsound, String newsound) { + String name = Bukkit.getServer().getClass().getPackage().getName(); + name = name.substring(name.lastIndexOf(46) + 1); + try { + if (name.startsWith("v1_8") || name.startsWith("v1_7")) { + return Sound.valueOf(oldsound); + }else { + return Sound.valueOf(newsound); + } + } catch (Exception ex) { + return null; + } + } + +} diff --git a/src/me/ram/kungfu/utils/URLUtil.java b/src/me/ram/kungfu/utils/URLUtil.java new file mode 100644 index 0000000..5bba060 --- /dev/null +++ b/src/me/ram/kungfu/utils/URLUtil.java @@ -0,0 +1,29 @@ +package me.ram.kungfu.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; + +public class URLUtil { + public static String getDocumentAt(String urlString) { + StringBuffer document = new StringBuffer(""); + try { + URL url = new URL(urlString); + URLConnection conn = url.openConnection(); + BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line = null; + while ( (line = reader.readLine()) != null) { + document.append(line + " "); + } + reader.close(); + } catch (MalformedURLException e) { + return null; + } catch (IOException e) { + return null; + } + return document.toString(); + } +} diff --git a/src/me/ram/kungfu/utils/UnicodeUtil.java b/src/me/ram/kungfu/utils/UnicodeUtil.java new file mode 100644 index 0000000..d85670d --- /dev/null +++ b/src/me/ram/kungfu/utils/UnicodeUtil.java @@ -0,0 +1,48 @@ +package me.ram.kungfu.utils; + +import java.util.regex.Pattern; + +public class UnicodeUtil { + + private static String ustartToCn(String str) { + StringBuilder sb = new StringBuilder().append("0x") + .append(str.substring(2, 6)); + Integer codeInteger = Integer.decode(sb.toString()); + int code = codeInteger.intValue(); + char c = (char)code; + return String.valueOf(c); + } + + private static boolean isStartWithUnicode(String str) { + if (null == str || str.length() == 0) { + return false; + } + if (!str.startsWith("\\u")) { + return false; + } + if (str.length() < 6) { + return false; + } + String content = str.substring(2, 6); + String singlePattern = "[0-9|a-f|A-F]"; + String pattern = singlePattern + singlePattern + singlePattern + singlePattern; + boolean isMatch = Pattern.matches(pattern, content); + return isMatch; + } + + public static String unicodeToCn(String str) { + StringBuilder sb = new StringBuilder(); + int length = str.length(); + for (int i = 0; i < length;) { + String tmpStr = str.substring(i); + if (isStartWithUnicode(tmpStr)) { + sb.append(ustartToCn(tmpStr)); + i += 6; + } else { + sb.append(str.substring(i, i + 1)); + i++; + } + } + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/org/bstats/metrics/Metrics.java b/src/org/bstats/metrics/Metrics.java new file mode 100644 index 0000000..a1a28a8 --- /dev/null +++ b/src/org/bstats/metrics/Metrics.java @@ -0,0 +1,695 @@ +package org.bstats.metrics; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) +public class Metrics { + + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); + final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Is bStats enabled on this server? + private boolean enabled; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final Plugin plugin; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + */ + public Metrics(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" + ).copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { } + } + + // Load the data + enabled = true; + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JSONObject getPluginData() { + JSONObject data = new JSONObject(); + + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); + + data.put("pluginName", pluginName); // Append the name of the plugin + data.put("pluginVersion", pluginVersion); // Append the version of the plugin + JSONArray customCharts = new JSONArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JSONObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.put("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JSONObject getServerData() { + // Minecraft specific data + int playerAmount; + try { + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JSONObject data = new JSONObject(); + + data.put("serverUUID", serverUUID); + + data.put("playerAmount", playerAmount); + data.put("onlineMode", onlineMode); + data.put("bukkitVersion", bukkitVersion); + + data.put("javaVersion", javaVersion); + data.put("osName", osName); + data.put("osArch", osArch); + data.put("osVersion", osVersion); + data.put("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JSONObject data = getServerData(); + + JSONArray pluginData = new JSONArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider())); + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } + } catch (NoSuchFieldException ignored) { } + } + + data.put("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(new Runnable() { + @Override + public void run() { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); + } + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JSONObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data.toString()); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); + outputStream.write(compressedData); + outputStream.flush(); + outputStream.close(); + + InputStream inputStream = connection.getInputStream(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + + StringBuilder builder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + bufferedReader.close(); + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + gzip.close(); + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JSONObject getRequestJsonObject() { + JSONObject chart = new JSONObject(); + chart.put("chartId", chartId); + try { + JSONObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.put("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JSONObject getChartData() throws Exception; + + } + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JSONObject value = new JSONObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.put(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.put(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JSONArray categoryValues = new JSONArray(); + categoryValues.add(entry.getValue()); + values.put(entry.getKey(), categoryValues); + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JSONArray categoryValues = new JSONArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(categoryValue); + } + values.put(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + +} \ No newline at end of file