From 6a9a20b2d7a4223297023dd908b4389df86a8d32 Mon Sep 17 00:00:00 2001 From: xhgit <1+xhgit@noreply.git.xhmcl.com> Date: Fri, 13 Nov 2026 22:30:40 +0800 Subject: [PATCH] Import ItxiaohuiServerAdvancements 1.2.0 source --- .gitattributes | 1 + .gitignore | 30 + FUN_ACHIEVEMENTS.md | 170 ++ README.md | 177 +- build.gradle | 91 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43764 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 251 ++ gradlew.bat | 94 + settings.gradle | 8 + .../audit/AuditSupport.java | 30 + .../audit/AutomaticConditionsAuditTest.java | 150 ++ .../audit/BundledCatalogAuditTest.java | 150 ++ .../audit/ConfigurationAuditTest.java | 112 + .../audit/DatabaseAuditTest.java | 149 ++ .../audit/LogicSecurityAuditTest.java | 165 ++ .../audit/StatisticsAuditTest.java | 93 + .../ItxiaohuiServerAdvancements.java | 151 ++ .../advancement/AdvancementManager.java | 193 ++ .../command/IsaCommand.java | 242 ++ .../condition/AutomaticConditions.java | 133 ++ .../condition/ConditionEngine.java | 168 ++ .../config/BundledCatalogInstaller.java | 94 + .../config/ConfigurationManager.java | 241 ++ .../config/MessageService.java | 54 + .../serveradvancements/config/StrictYaml.java | 38 + .../config/ValidationResult.java | 7 + .../database/BundledSqliteDriver.java | 30 + .../database/DatabaseManager.java | 290 +++ .../serveradvancements/gui/AdminGui.java | 128 ++ .../listener/PlayerActivityListener.java | 158 ++ .../model/AchievementDefinition.java | 10 + .../model/AdvancementFrame.java | 11 + .../model/ConditionDefinition.java | 62 + .../model/ConditionType.java | 14 + .../model/RewardDefinition.java | 8 + .../reward/RewardService.java | 124 + .../statistics/StatisticsService.java | 150 ++ src/main/resources/advancements.yml | 218 ++ src/main/resources/config.yml | 24 + src/main/resources/fun-advancements-v1.yml | 1122 +++++++++ src/main/resources/fun-advancements.yml | 2025 +++++++++++++++++ src/main/resources/messages.yml | 17 + src/main/resources/plugin.yml | 29 + .../model/ConditionDefinitionTest.java | 28 + 45 files changed, 7446 insertions(+), 1 deletion(-) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 FUN_ACHIEVEMENTS.md create mode 100644 build.gradle create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 src/audit/java/top/itxiaohui/serveradvancements/audit/AuditSupport.java create mode 100644 src/audit/java/top/itxiaohui/serveradvancements/audit/AutomaticConditionsAuditTest.java create mode 100644 src/audit/java/top/itxiaohui/serveradvancements/audit/BundledCatalogAuditTest.java create mode 100644 src/audit/java/top/itxiaohui/serveradvancements/audit/ConfigurationAuditTest.java create mode 100644 src/audit/java/top/itxiaohui/serveradvancements/audit/DatabaseAuditTest.java create mode 100644 src/audit/java/top/itxiaohui/serveradvancements/audit/LogicSecurityAuditTest.java create mode 100644 src/audit/java/top/itxiaohui/serveradvancements/audit/StatisticsAuditTest.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/ItxiaohuiServerAdvancements.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/advancement/AdvancementManager.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/command/IsaCommand.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/condition/AutomaticConditions.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/condition/ConditionEngine.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/config/BundledCatalogInstaller.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/config/ConfigurationManager.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/config/MessageService.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/config/StrictYaml.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/config/ValidationResult.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/database/BundledSqliteDriver.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/database/DatabaseManager.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/gui/AdminGui.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/listener/PlayerActivityListener.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/model/AchievementDefinition.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/model/AdvancementFrame.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/model/ConditionDefinition.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/model/ConditionType.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/model/RewardDefinition.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/reward/RewardService.java create mode 100644 src/main/java/top/itxiaohui/serveradvancements/statistics/StatisticsService.java create mode 100644 src/main/resources/advancements.yml create mode 100644 src/main/resources/config.yml create mode 100644 src/main/resources/fun-advancements-v1.yml create mode 100644 src/main/resources/fun-advancements.yml create mode 100644 src/main/resources/messages.yml create mode 100644 src/main/resources/plugin.yml create mode 100644 src/test/java/top/itxiaohui/serveradvancements/model/ConditionDefinitionTest.java diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d4aaa68 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +/gradlew text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..891f068 --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +.gradle/ +build/ +test-server/ +test-client/node_modules/ +.idea/ +*.iml +*.log + +# Local test and production deployment material, not part of the public source. +/audit-results/ +/deployment/ +/test-client/ +/src/probe/ +/AUTOMATION_REPORT.md +/DEPLOYMENT_REPORT.md +/FEATURE_REPORT.md +/FIX_REPORT.md +/FULL_AUDIT_REPORT.md +/TEST_REPORT.md + +# Local credentials and data. +.env +.env.* +*.pem +*.key +*.jks +*.p12 +*.db +*.db-wal +*.db-shm diff --git a/FUN_ACHIEVEMENTS.md b/FUN_ACHIEVEMENTS.md new file mode 100644 index 0000000..24c80e6 --- /dev/null +++ b/FUN_ACHIEVEMENTS.md @@ -0,0 +1,170 @@ +# 自动优先成就目录(1.2.0) + +默认开启 **129 个自动普通成就 + 1 个根进度**:原有 17 个自动成就,加上趣味目录中的 112 个自动成就。另保留 22 个默认关闭的可选人工项目;不启用它们也不影响自动路线。 + +本次将原趣味目录中的 34 项人工条件改成可测量规则,并新增 60 个自动成就。部分名称保留、目标描述调整:例如铁路按放置铁轨计数,住宅按建材清单计数,不冒充审美、连通性或公共贡献鉴定。 + +## 不需要 AI 或管理员日常审核 + +- 原版统计:任意颜色床的合成、航行、骑乘、游泳、交易、附魔、钓鱼等,读取玩家原版累计统计,可能包含安装前历史。 +- 原版进度:图腾、远距离狙击、恶魂火球反弹等,核对真正完成的原版 Advancement。 +- 真实事件:进食、从烹饪设备取出食物、驯服、成功钓获和方块放置;记录新版安装后的成功事件,取消事件不计。 +- 背包收藏:检查随身物品栏(含装备和副手),按不同物品种类与数量判断,不统计箱子里或背包内部容器中的物品。 +- 生物群系和结构:约每 10 秒在玩家当前位置采样;结构按天然生成结构的包围盒及小幅邻接余量判断,并按世界、类型和结构位置去重。不是搜索全世界,也不代表完整探索所有房间。 +- 这版插件没有 AI 接口、API Key、调用费或把聊天/截图送交 AI 的流程。建筑审美、原创性和社交贡献不交给模型直接决定发奖。 + +## 升级、编辑与可选项目 + +首次启动先备份 advancements.yml,安装标记升级为 bundled-fun-catalog-version: 2。1.1.0 中与原模板完全相同的 74 项会升级,额外补入 60 项。管理员修改过的同名定义、禁用状态以及主动删除的旧条目保留,不强制覆盖。因此有自定义配置的服务器,实际启用数量可能与默认不同。 + +只编辑运行目录的 advancements.yml。JAR 内 fun-advancements.yml 是新版模板,fun-advancements-v1.yml 只用于识别未修改的旧模板。修改后正常停服重启,不使用 Bukkit /reload。数据库和玩家原版进度不用清空,原有奖励防重记录继续有效。 + +默认关闭的 22 项适合已有活动运营的服务器,可手工设置 enabled: true 后正常重启,再使用 /isa give <在线玩家> 授予;自动路线没有依赖这些人工节点。自定义地标也可以改用现有 reach_location 条件并填写真实坐标。 + +新目录奖励仅 10–100 经验点、禁止重复领取,不发货币或强力装备。拾取和放置统计允许重复拿放,不是不可刷的经济凭证。 + +## 112 个自动项目 + +| 名称 | ID | 自动目标 | +|---|---|---| +| 先富带动后富 | `fun_diamond_64` | 累计从地面拾取 64 个钻石 | +| 小区保安 | `fun_neighborhood_guard` | 击杀 30 只僵尸、20 只骷髅和 10 只苦力怕 | +| 这不是流水线 | `fun_bread_factory` | 累计合成 1024 个面包 | +| 禁止随地大小牧 | `fun_responsible_rancher` | 成功繁殖动物 50 次 | +| 差一点就附魔了 | `fun_level_30` | 历史达到 30 级经验 | +| 这里居然还有人住 | `fun_remote_village` | 进入一处天然生成的村庄范围(不要求偏远) | +| 服务器考古学家 | `fun_server_archaeologist` | 探索三处不同的天然遗迹:神殿或海底废墟;按结构位置去重 | +| 高处不胜寒 | `fun_lonely_peak` | 历史到达 Y≥200 的高处;不限定服主自建山顶 | +| 腿是自己的,路是服主的 | `fun_walk_10km` | 累计移动 10000 格;不计单次至少 100 格的跳变 | +| 下界出差申请已批准 | `fun_nether_business` | 首次进入下界,解锁探索分支 | +| 不是终点,是新起点 | `fun_new_beginning` | 进入末地并亲手击杀末影龙 | +| 什么都懂一点 | `fun_jack_of_trades` | 完成钻石收集、面包合成、社区防卫和长途探索四项成就 | +| 服里的老熟人 | `fun_old_friend` | 完成综合入门、繁殖、经验等级、首次合成床;不再依赖人工考古审核 | +| 今晚终于有床了 | `fun_first_bed` | 亲手合成第一张床,任意颜色均可 | +| 拒绝吃生的 | `fun_cooked_food` | 从熔炉、烟熏炉等取出累计 64 份已烹饪食物 | +| 背包里有个动物园 | `fun_pocket_zoo` | 同时持有清单中五种动物相关物品:蛋、羽毛、骨头、线、皮革、墨囊、蜂蜜、鳕鱼 | +| 吃点好的 | `fun_varied_diet` | 安装新版后实际吃下十种不同食物 | +| 保命的钱不能省 | `fun_totem_saved` | 达成原版进度:使用不死图腾逃过一劫 | +| 出门在外靠自己 | `fun_self_made_iron` | 背包或身穿同时攒齐铁头盔、胸甲、护腿和靴子;不限制物资来源 | +| 今天不想走路 | `fun_boat_3km` | 原版统计累计乘船航行 3000 格(300000 厘米) | +| 沙漠里也有惊喜 | `fun_desert_temple` | 进入一座天然沙漠神殿的结构范围 | +| 小心脚下 | `fun_jungle_temple` | 进入一座天然丛林神庙的结构范围 | +| 船长已经下班 | `fun_three_shipwrecks` | 进入三艘位置不同的天然沉船范围 | +| X 标记的地方 | `fun_buried_treasure` | 到达一处天然埋藏宝藏位置;不验证是否使用藏宝图 | +| 海底不包呼吸 | `fun_ocean_monument` | 进入一座天然海底神殿的结构范围 | +| 安静,现在很危险 | `fun_ancient_city` | 进入一座天然远古城市的结构范围;不要求往返 | +| 这房子比我家大 | `fun_woodland_mansion` | 进入一座天然林地府邸的结构范围 | +| 冰箱门忘关了 | `fun_ice_spikes` | 被环境采样记录到达冰刺平原 | +| 蘑菇比树还像树 | `fun_mushroom_fields` | 被环境采样记录到达蘑菇岛 | +| 一粒种子的野心 | `fun_wheat_1000` | 累计从地面收集 1000 个小麦;收获后拾取也计入 | +| 土豆不是货币 | `fun_potato_512` | 累计从地面收集 512 个马铃薯 | +| 西瓜批发市场 | `fun_melon_1024` | 累计从地面收集 1024 片西瓜 | +| 蜂蜜自由 | `fun_honey_64` | 同时在随身物品栏持有 64 瓶蜂蜜,不限制获取方式 | +| 羊毛色卡 | `fun_rainbow_wool` | 同时在随身物品栏持有全部 16 色羊毛 | +| 猫说这里归它了 | `fun_three_cats` | 安装新版后亲自驯服三只猫 | +| 出门带保镖 | `fun_five_wolves` | 安装新版后亲自驯服五只狼 | +| 鱼没钓到,家当不少 | `fun_fishing_variety` | 安装新版后通过成功钓获获得五种不同物品 | +| 从火柴盒开始 | `fun_first_home` | 完成开荒建材清单:合成床,放置 64 块木板、1 扇木门和 4 支火把;不鉴定房屋外形 | +| 窗户不是装饰 | `fun_windows_20` | 安装新版后累计放置 20 个玻璃方块或玻璃板,不要求属于住宅 | +| 铁路不是摆设 | `fun_railway_500` | 安装新版后累计放置 500 个铁轨类方块;不验证线路连通 | +| 整理,是一种修行 | `fun_organized_storage` | 亲手合成 16 个箱子及 8 块告示牌,准备分类仓储;不评价整理效果 | +| 唱片不负责打怪 | `fun_six_records` | 同时持有内置唱片清单中六张不同唱片 | +| 花里胡哨才是家 | `fun_flower_garden` | 安装新版后实际种下十种清单内不同的花;不要求位于同一花园 | +| 蜘蛛不是室友 | `fun_spiders_50` | 累计亲手击杀 50 只蜘蛛 | +| 今晚不做梦 | `fun_phantoms_10` | 累计亲手击杀 10 只幻翼 | +| 隔壁的弓箭更准 | `fun_sniper_skeleton` | 达成原版狙击手进度:从至少 50 格外射杀骷髅 | +| 盾牌不是锅盖 | `fun_shield_10` | 原版盾牌格挡伤害统计达到 100(原版十分之一伤害点计量) | +| 让它自己冷静一下 | `fun_return_to_sender` | 达成原版见鬼去吧进度:反弹恶魂火球并击杀它 | +| 烈焰人事部 | `fun_blaze_rods_32` | 累计从地面拾取 32 根烈焰棒 | +| 海底清洁工 | `fun_elder_guardian` | 亲手击败一只远古守卫者 | +| 三个头也得排队 | `fun_wither_boss` | 亲手击败一只凋灵 | +| 箭有自己的想法 | `fun_piercing_arrow` | 达成原版一箭双雕进度:用穿透弩一箭击杀两只幻翼 | +| 膝盖还好吗 | `auto_jumps` | 累计跳跃 1000 次 | +| 风一样的方块人 | `auto_sprint` | 累计疾跑 10 公里 | +| 悄悄地进村 | `auto_crouch` | 累计潜行移动 500 格 | +| 泳池已经装不下你 | `auto_swim` | 累计游泳 1000 格 | +| 下一站没有终点 | `auto_minecart` | 累计乘矿车移动 3000 格 | +| 这匹马有编制 | `auto_horse` | 累计骑马移动 2000 格 | +| 今天也不走正门 | `auto_elytra` | 累计鞘翅飞行 10 公里 | +| 楼梯对你没有吸引力 | `auto_climb` | 累计攀爬 500 格 | +| 岩浆专线乘客 | `auto_strider` | 累计骑炽足兽移动 1000 格 | +| 愿者上钩一百次 | `auto_fish100` | 原版成功钓鱼统计达到 100 | +| 村民看见你就上班 | `auto_trade50` | 与村民成功交易 50 次 | +| 附魔台的常客 | `auto_enchant10` | 完成 10 次物品附魔 | +| 全村都知道你来了 | `auto_bells` | 敲钟 100 次 | +| 音乐可能不是你的错 | `auto_notes` | 演奏音符盒 100 次 | +| 点歌台营业中 | `auto_records` | 播放唱片 10 次 | +| 床才是终极装备 | `auto_sleep` | 原版入睡统计达到 10 次 | +| 铁砧正在申请工伤 | `auto_anvil` | 与铁砧交互 20 次 | +| 阳台承包商 | `auto_potted` | 向花盆种入植物 16 次 | +| 本村荣誉保安 | `auto_raid` | 原版袭击胜利统计达到 1 | +| 炼药室的新员工 | `auto_brewing` | 与酿造台交互 10 次;不冒充酿出药水次数 | +| 下界也有房地产 | `auto_fortress` | 进入原版进度认可的下界要塞 | +| 古代人的零花钱 | `auto_debris` | 获得远古残骸并达成对应原版进度 | +| 黑曜石也会哭 | `auto_crying` | 获得哭泣的黑曜石并达成对应原版进度 | +| 村民今天有折扣 | `auto_hero` | 达成原版村庄英雄进度 | +| 它好像认得你 | `auto_tame` | 达成原版驯服动物进度 | +| 明天的饭有着落了 | `auto_seed` | 达成原版种下种子的进度 | +| 这把锄头有点贵 | `auto_hoe` | 达成原版下界合金锄进度 | +| 快递员正式上岗 | `auto_wings` | 达成原版获得鞘翅进度 | +| 电梯维修中 | `auto_levitate` | 达成原版在末地漂浮挑战进度 | +| 看清楚再打 | `auto_spyglass` | 用望远镜观察末影龙并达成对应原版进度 | +| 木匠的色卡 | `auto_wood_palette` | 同时携带八种不同木板 | +| 口袋里有半座矿山 | `auto_miner_pockets` | 同时持有铁铜金粗矿、红石、青金石、煤、钻石、绿宝石和石英 | +| 书里真的有力量 | `auto_enchanted_book` | 随身持有一本附魔书 | +| 骑乘业务扩张中 | `auto_saddles` | 随身持有三个鞍 | +| 叮叮当当一整组 | `auto_amethyst` | 随身持有 64 个紫水晶碎片 | +| 地底寄来的回声 | `auto_echo` | 随身持有 8 个回响碎片 | +| 海螺里的声音 | `auto_nautilus` | 随身持有 8 个鹦鹉螺壳 | +| 海王的备用餐具 | `auto_trident` | 随身持有三叉戟 | +| 移动仓库开张 | `auto_shulkers` | 随身持有 16 个潜影壳 | +| 盔甲也要穿搭 | `auto_trims` | 同时持有哨兵、沙丘、监守和尖塔四种锻造模板 | +| 红土不用滤镜 | `auto_badlands` | 环境采样记录到达 badlands 生物群系 | +| 樱花开到你面前 | `auto_cherry_grove` | 环境采样记录到达 cherry_grove 生物群系 | +| 声音请调到最小 | `auto_deep_dark` | 环境采样记录到达 deep_dark 生物群系 | +| 树根比路还多 | `auto_mangrove_swamp` | 环境采样记录到达 mangrove_swamp 生物群系 | +| 地底居然有花园 | `auto_lush_caves` | 环境采样记录到达 lush_caves 生物群系 | +| 天花板有点尖 | `auto_dripstone_caves` | 环境采样记录到达 dripstone_caves 生物群系 | +| 雪山慢递 | `auto_snowy_slopes` | 环境采样记录到达 snowy_slopes 生物群系 | +| 蓝色森林不卖奶茶 | `auto_warped_forest` | 环境采样记录到达 warped_forest 生物群系 | +| 红色森林不卖草莓 | `auto_crimson_forest` | 环境采样记录到达 crimson_forest 生物群系 | +| 鞋底快熟了 | `auto_basalt_deltas` | 环境采样记录到达 basalt_deltas 生物群系 | +| 干饭也算正经事 | `auto_eat64` | 安装新版后实际吃下 64 份食物 | +| 菜单已经翻到第二页 | `auto_eat20` | 安装新版后实际吃下 20 种不同食物 | +| 食堂今天我值班 | `auto_cook256` | 安装新版后从烹饪设备取出 256 份食物 | +| 火候各有讲究 | `auto_cook5` | 安装新版后取出五种不同的烹饪食物 | +| 鱼塘股东 | `auto_fish256` | 安装新版后成功钓获累计 256 个物品 | +| 水底杂货铺 | `auto_fish10` | 安装新版后成功钓获十种不同物品 | +| 朋友圈开始长毛 | `auto_tame10` | 安装新版后亲自成功驯服十只动物 | +| 一块一块垒起来 | `auto_place1000` | 安装新版后实际放置 1000 个方块;拆后重放也计数 | +| 采光优先 | `auto_glass100` | 安装新版后实际放置 100 块透明玻璃 | +| 花店终于进齐货 | `auto_flowers16` | 安装新版后实际种下清单中 16 种不同的花 | + +## 22 个可选人工项目(默认关闭) + +| 名称 | ID | 可选验收目标 | +|---|---|---| +| 地图边缘的咖啡馆 | `fun_distant_cafe` | 找到服主设置在远方的小屋或咖啡馆 | +| 自由落体体验券 | `fun_water_landing` | 从挑战高台落入指定水池并存活;由服主设置安全场地 | +| 这水有点烫 | `fun_lava_escape` | 进入岩浆后成功脱险,提供过程证据 | +| 我的床有自己的想法 | `fun_forgot_bed` | 设置重生点后远行,发现忘带床并记录这次冒险 | +| 此处禁止施工 | `fun_secret_room` | 找到服主藏在地图里的秘密房间;无需破坏建筑 | +| 南瓜董事长 | `fun_pumpkin_farm` | 建成至少有 100 个南瓜的农场 | +| 给动物一点体面 | `fun_humane_ranch` | 建成有照明、遮雨与分区的牧场 | +| 夜里终于看得见了 | `fun_public_lighting` | 完成一段公共道路的照明;先取得道路管理者同意 | +| 桥归桥,路归路 | `fun_river_bridge` | 建造一座安全、可通行的跨河桥 | +| 地下也要有生活 | `fun_underground_home` | 建造含卧室、仓库和种植区的地下基地 | +| 请勿拆除,具有历史价值 | `fun_preserved_hut` | 保留自己的第一间小屋,并设置纪念牌 | +| 装备差,胆子大 | `fun_light_gear_challenge` | 不穿钻石及以上护甲,完成服主指定挑战副本 | +| 新人接待处 | `fun_welcome_newcomer` | 自愿帮助一位新人完成安家,经对方确认 | +| 借你一把镐 | `fun_lend_a_pickaxe` | 向新人赠送一套实用工具,经对方确认;不索要回报 | +| 这条路大家都能走 | `fun_public_road` | 参与修建一条公共道路,获得负责人确认 | +| 免费,但不是垃圾桶 | `fun_community_donation` | 向公共物资站捐赠一组指定实用物资 | +| 我家大门常打开 | `fun_open_house` | 举办一次自愿参加的玩家参观活动 | +| 合影请看这里 | `fun_group_photo` | 与五名其他玩家在指定地标合影;尊重参与意愿 | +| 差一点就是冠军 | `fun_event_participant` | 完整参加一次服务器活动,不要求获胜 | +| 建筑工地有我一份 | `fun_community_builder` | 参与一次公共建筑项目,经负责人确认 | +| 今天由我来讲故事 | `fun_original_story` | 为服务器图书馆写一本原创游戏故事 | +| 多年以后还能找到这里 | `fun_time_capsule` | 在纪念馆留下自己的书、署名和加入日期 | + +构建、测试和使用限制见 [README](README.md)。 diff --git a/README.md b/README.md index 2d05ef1..d1c47d0 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,178 @@ # ItxiaohuiServerAdvancements -ItxiaohuiServerAdvancements 是一款面向 Paper 1.21.8 的 Minecraft 服务端成就插件。通过原版进度界面展示独立的服务器成就树,默认启用 129 个自动成就,涵盖探索、战斗、种田、烹饪、驯养与收藏。无需客户端模组、AI 接口或管理员逐项审核。 \ No newline at end of file +ItxiaohuiServerAdvancements 是一款面向 Paper 1.21.8 的 Minecraft 服务端成就插件。通过原版进度界面展示独立的服务器成就树,默认启用 129 个自动成就,涵盖探索、战斗、种田、烹饪、驯养与收藏。无需客户端模组、AI 接口或管理员逐项审核。 + +当前版本为 **1.2.0**,构建需要 Java 21。默认包含 **129 个自动普通成就 + 根进度**,另保留 22 个默认关闭的可选人工项目。见[完整目录与管理说明](FUN_ACHIEVEMENTS.md)。 + +## 安装 + +1. 使用 Java 21 启动 Paper 1.21.8。 +2. 将 `build/libs/ItxiaohuiServerAdvancements.jar` 放入服务端 `plugins/`。 +3. 正常启动服务端。插件会自动创建: + - `plugins/ItxiaohuiServerAdvancements/config.yml` + - `plugins/ItxiaohuiServerAdvancements/advancements.yml` + - `plugins/ItxiaohuiServerAdvancements/messages.yml` + - `plugins/ItxiaohuiServerAdvancements/data/advancements.db` +4. 玩家加入后约 1 秒自动获得无弹窗、无广播、无奖励的根进度;按 `L` 打开原版进度界面。 + +1.2.0 首次启动会先备份原 `advancements.yml`,安装/升级自动优先目录:与旧模板完全一致的定义自动更新,自定义条目、管理员禁用状态和已删除旧项保留。后续启动不会反复安装,不清库。少量主观或服务器专属项目默认关闭,不影响自动路线。模板不生成世界建筑,也不虚构地点坐标。 + +不要使用 Bukkit `/reload`。修改 Advancement 的 ID、父级、图标、标题、描述、显示选项或增删节点后,请用 `stop` 正常关闭服务器再启动。Paper 1.21.8 的动态移除接口不会在当前进程中立即清除注册表,因此插件故意拒绝危险的热替换。 + +## 构建 + +```powershell +.\gradlew.bat clean test shadowJar +``` + +产物固定为 `build/libs/ItxiaohuiServerAdvancements.jar`。SQLite JDBC 3.50.3.0 已打包并通过隔离类加载器加载,避免选中 Paper 内置的其他版本;JNI 包名保持原样。不需要另装数据库或驱动。 + +Linux/macOS 可执行 `./gradlew clean test shadowJar`。 + +## 配置 + +全局选项位于 `config.yml`。`root` 控制独立页签的根节点,根 ID 不能作为普通成就删除;`statistics.flush-interval-seconds` 控制内存统计批量写入周期。全局配置或节点定义修改后需要正常重启,消息文件可用 `/isa reload` 重载。 + +普通成就位于 `advancements.yml`: + +```yaml +achievements: + first_diamond: + name: "钻石收藏家" + description: "累计从地面拾取 64 个钻石" + icon: "minecraft:diamond" + frame: goal # task / goal / challenge + parent: root + display: { x: 2, y: 0 } # 排序提示;原版客户端负责最终坐标 + hidden: false + show-toast: true + announce-chat: false + enabled: true + conditions: + - { type: collect_item, item: "minecraft:diamond", amount: 64 } + rewards: + experience: 100 + allow-reclaim: false + items: + - { item: "minecraft:emerald", amount: 3 } + commands: + - "say {player} 完成了钻石收藏家" +``` + +一个成就的多个条件采用 AND 关系。配置加载时会检查非法 ID、图标、材料、未知条件、缺失父级、依赖缺失和父级循环。单个坏定义会被隔离并写入明确日志;`/isa validate` 可提前检查。 + +### 条件类型与统计口径 + +| 类型 | 必要参数 | 统计口径 | +|---|---|---| +| `first_join` | 无 | Bukkit 判定的首次加入 | +| `online_time` | `amount`, `unit` | 登录会话累计;单位为 seconds/minutes/hours | +| `mine_block` | `block`, `amount` | 未取消的方块破坏事件 | +| `collect_item` | `item`, `amount` | 从世界物品实体拾取的数量;不含交易、容器转移、管理员命令等来源 | +| `obtain_item` | `item`, `amount` | 插件能确认的新获得数量:当前包括地面拾取和玩家合成产出;不含交易、容器转移或命令来源 | +| `kill_mob` | `entity`, `amount` | 玩家作为直接 Bukkit killer 的击杀;`entity: "*"` 表示任意实体 | +| `visit_dimension` | `dimension` | 加入时所在维度或切换后进入的维度 | +| `move_distance` | `amount` | 同一世界内实际移动距离;单次大于等于 100 格的跳变不计,避免传送灌水 | +| `reach_location` | `world`, `x`, `y`, `z`, `radius`, 可选 `id` | 进入指定球形区域 | +| `craft_item` | `item`, `amount` | 原版 CRAFT_ITEM 成功统计的增量;包括普通和 Shift 合成,不统计无产出点击 | +| `breed_mob` | `entity`, `amount` | 玩家作为繁殖者的成功繁殖;支持 `*` | +| `experience_level` | `amount` | 历史达到的最高经验等级 | +| `complete_achievement` | `achievement` | 指定服务器成就的原版完成状态 | +| `manual` | 无 | 只能由管理员授予 | +| `player_statistic` | `statistic`, `amount`,按统计类型可需 `materials` 或 `entity` | 读取原版累计统计;距离单位为厘米,可能包含安装前历史 | +| `vanilla_advancement` | `advancement` | 指定 minecraft 原版进度已完成 | +| `inventory_set` | `items`, `amount`,可选 `each` | 随身物品中至少指定数量的不同种类,每种满足数量要求 | +| `visit_biome` | `biome` | 周期采样记录到达该生物群系 | +| `visit_structure` | `structures`, `amount` | 周期记录进入不同的天然结构位置,重复进入同一处不累加 | +| `altitude` | `amount` | 环境采样记录历史到达的最高正 Y 坐标 | +| `event_count` | `event`, `amount`,可选 `subjects` | 新版安装后的进食、取出烹饪食物、驯服、成功钓获或放置方块数量 | +| `event_distinct` | 同上 | 对上述事件记录的不同对象种类计数,不把重复吃同一种食物当新品种 | + +统计值是历史累计值,不会因物品被丢弃、存箱或成就被撤销而清零。节点 `x/y` 不是原版 Advancement JSON 字段;插件将其用于稳定排序,最终位置由原版客户端按父子树自动布局。 + +### 奖励 + +- `experience`:经验点(不是经验等级)。 +- `items`:原版物品 ID 与数量;背包放不下时掉落在玩家位置。 +- `commands`:由控制台执行,支持受控占位符 `{player}` 和 `{uuid}`。 +- `allow-reclaim`:撤销后再次完成是否允许再次发奖,默认 `false`。 +- `completion-message`:可选的个人完成消息。 + +后台队列先将奖励预约为 `RESERVED`,再持久化 `PENDING` 执行意图,之后才在主线程授予原版进度、发经验/物品和执行命令。成功落库为 `CLAIMED`;部分失败为 `FAILED`。 + +`RESERVED` 表示尚未执行,可以安全恢复;`PENDING` 与 `FAILED` 都不自动重放,即使 `allow-reclaim=true` 也一样。管理员应先备份数据库,查询 `reward_claims` 中的 `status`、`attempts`、`detail` 与日志,核查实际经验/物品/命令是否已执行,再人工补发欠缺部分。不要直接删除未决记录后重跑整份奖励。数据库事务不能与外部游戏命令形成绝对原子事务。 + +若数据库预约失败,玩家的原版节点不会提前完成,可以在数据库恢复后重试。管理命令异步返回实际完成结果。 + +## 命令与权限 + +主命令为 `/isa`,别名 `/itxiaohuiadvancements`。 + +| 命令 | 用途 | +|---|---| +| `/isa help` | 帮助 | +| `/isa list` / `/isa info ` | 查看定义 | +| `/isa editor` | 打开管理容器 GUI | +| `/isa give <在线玩家> ` | 手动完成并发奖 | +| `/isa revoke <在线玩家> ` | 撤销原版完成状态,不清统计 | +| `/isa progress <在线玩家>` | 查看完成数和内存统计 | +| `/isa create ` | 创建一个默认禁用的 YAML 骨架 | +| `/isa delete confirm` | 检查子节点后删除定义;不清历史数据 | +| `/isa validate` | 校验磁盘配置 | +| `/isa reload` | 重载消息并校验;定义有变化时要求正常重启 | +| `/isa backup` | 刷盘、WAL checkpoint 并备份数据库 | + +权限: + +- `itxiaohui.serveradvancements.admin`:默认 OP,包含全部子权限。 +- `itxiaohui.serveradvancements.give` +- `itxiaohui.serveradvancements.revoke` +- `itxiaohui.serveradvancements.view` + +管理 GUI 的点击事件会再次执行服务端权限检查。复杂条件和奖励仍以 YAML 为准,GUI 提供浏览、详情、启停、给自己授予/撤销、重载和操作提示。 + +## SQLite 备份与恢复 + +数据库启用 WAL、FULL 同步、外键、busy timeout 和结构版本迁移。运行时 JDBC 操作统一走后台单线程队列。高频统计使用版本快照批量 UPSERT,读取失败时不以空缓存覆盖历史数据;未保存的重登缓存会被保留。离线且已保存的缓存会被淘汰。 + +退出、备份和正常停服会主动刷盘。进程在最近一次批量保存后被强杀,仍可能丢失尚在内存中的统计;周期可调低到 5 秒,但不能宣称任何崩溃都不丢数据。 + +备份:执行 `/isa backup`,后台先刷盘,再使用 SQLite `VACUUM INTO` 制作包含已提交 WAL 页的一致快照。每次创建独立目录,包含 `advancements.db` 以及三份 YAML;连续同秒请求不会覆盖或冲突。刷盘失败不会报备份成功。 + +恢复: + +1. 使用 `stop` 正常关闭服务端。 +2. 额外复制保存当前 `data/advancements.db` 及同目录的 `-wal`/`-shm`(若存在)。 +3. 将选定备份复制为 `data/advancements.db`。 +4. 确保没有遗留的旧 `advancements.db-wal`、`advancements.db-shm` 与新主库混用。 +5. 启动服务端并检查完整性与插件日志。 + +不要在服务器运行时直接覆盖数据库。 + +## 架构 + +- `advancement`:不稳定动态注册 API 的唯一隔离层、原版进度授予/撤销。 +- `config` / `model`:YAML 解析、校验、成就模型。 +- `condition` / `listener`:行为统计和 AND 条件求值。 +- `statistics` / `database`:内存缓存、异步批量持久化、迁移、奖励状态和审计。 +- `reward`:防重复奖励执行。 +- `command` / `gui`:权限受控的管理入口。 + +## 已知限制 + +1. `UnsafeValues.loadAdvancement/removeAdvancement` 在 Paper 1.21.8 已标记为不稳定/弃用;相关代码已集中隔离。定义更新采用正常重启流程。 +2. 原版客户端决定节点坐标与未解锁深层节点的可见范围,插件不能通过标准 Advancement JSON 强制绝对 `x/y`。 +3. `collect_item` 只统计地面拾取;不会虚假宣称覆盖交易、箱子、漏斗或命令来源。 +4. 当前管理命令修改原版玩家进度只支持在线玩家;离线玩家统计仍保存在 SQLite,玩家下次进入后继续累计。 +5. `/isa revoke` 不清累计统计;若玩家条件仍满足,后续求值会再次完成该成就。默认奖励防重仍会阻止重复发奖。 +6. 条件依赖和父级关系一起做迭代环检测,树深度上限为 256;每个节点最多 64 条条件,物品奖励单项 1–4096 个、经验奖励 0–1000000,避免误配置耗尽资源。 + +从 1.0.0 升级:备份数据目录,使用 `stop` 正常关闭后替换 JAR 并启动;无需清空 SQLite 或玩家原版进度文件。旧的 PENDING/FAILED 记录会继续保留,按上面的核查流程处理,不会自动重复发放。 + +## 测试 + +使用 `./gradlew test securityAudit`(Windows 使用 `.\gradlew.bat test securityAudit`)运行单元和审计测试,报告位于 `build/reports/tests/`。 + +## 许可证 + +本项目按 [GNU GPL v3](LICENSE) 发布。随 JAR 分发的 SQLite JDBC 仍按其原有许可证发布,许可证声明位于 JAR 内的 `META-INF/maven/org.xerial/sqlite-jdbc/`。 diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..1a8ca8b --- /dev/null +++ b/build.gradle @@ -0,0 +1,91 @@ +plugins { + id 'java' + id 'jacoco' + id 'com.gradleup.shadow' version '8.3.6' +} + +group = 'top.itxiaohui.serveradvancements' +version = '1.2.0' + +repositories { + mavenCentral() + maven { url = 'https://repo.papermc.io/repository/maven-public/' } +} + +dependencies { + compileOnly 'io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT' + implementation 'org.xerial:sqlite-jdbc:3.50.3.0' + + testImplementation platform('org.junit:junit-bom:5.13.4') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testImplementation 'io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT' + testImplementation 'org.mockito:mockito-core:5.18.0' +} + +sourceSets { + audit { + java.srcDir 'src/audit/java' + compileClasspath += sourceSets.main.output + configurations.testCompileClasspath + configurations.testRuntimeClasspath + runtimeClasspath += output + compileClasspath + } + probe { + java.srcDir 'src/probe/java' + resources.setSrcDirs(['src/probe/resources']) + compileClasspath += sourceSets.main.output + configurations.compileClasspath + } +} + +tasks.register('securityAudit', Test) { + description = 'Security, robustness, persistence and abuse audit; failures identify unmet invariants.' + testClassesDirs = sourceSets.audit.output.classesDirs + classpath = sourceSets.audit.runtimeClasspath + useJUnitPlatform() + maxHeapSize = '1g' + testLogging { events 'passed', 'failed', 'skipped'; exceptionFormat 'short'; showStandardStreams = true } + finalizedBy 'auditCoverage' +} + +jacoco { toolVersion = '0.8.13' } +tasks.register('auditCoverage', JacocoReport) { + executionData layout.buildDirectory.file('jacoco/securityAudit.exec') + sourceSets sourceSets.main + reports { xml.required = true; html.required = true } +} + +tasks.register('probeJar', Jar) { + description = 'Isolated-server test probe only; never install on production.' + archiveFileName = 'ISA-AuditProbe.jar' + destinationDirectory = layout.buildDirectory.dir('audit-tools') + from sourceSets.probe.output +} + +java { + toolchain.languageVersion = JavaLanguageVersion.of(21) +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.release = 21 +} + +tasks.processResources { + inputs.property('pluginVersion', project.version) + filteringCharset = 'UTF-8' + filesMatching('plugin.yml') { + expand(version: project.version) + } +} + +tasks.test { + useJUnitPlatform() +} + +tasks.shadowJar { + archiveFileName = 'ItxiaohuiServerAdvancements.jar' + // JNI exports reference org.sqlite classes by their original names. + // The runtime loads this bundled driver in a dedicated child-first classloader. +} + +tasks.jar { enabled = false } +tasks.build { dependsOn tasks.shadowJar } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..1b33c55baabb587c669f562ae36f953de2481846 GIT binary patch literal 43764 zcma&OWmKeVvL#I6?i3D%6z=Zs?ofE*?rw#G$eqJB ziT4y8-Y@s9rkH0Tz>ll(^xkcTl)CY?rS&9VNd66Yc)g^6)JcWaY(5$5gt z8gr3SBXUTN;~cBgz&})qX%#!Fxom2Yau_`&8)+6aSN7YY+pS410rRUU*>J}qL0TnJ zRxt*7QeUqTh8j)Q&iavh<}L+$Jqz))<`IfKussVk%%Ah-Ti?Eo0hQH!rK%K=#EAw0 zwq@@~XNUXRnv8$;zv<6rCRJ6fPD^hfrh;0K?n z=p!u^3xOgWZ%f3+?+>H)9+w^$Tn1e;?UpVMJb!!;f)`6f&4|8mr+g)^@x>_rvnL0< zvD0Hu_N>$(Li7|Jgu0mRh&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IOXw7V6ZK(T9RFJJe@ zZS!aC+p)Gf2Ujc=a6hx4!A1Th%YH!Lb^xpI!Eu` zmJO{9rw){B1Ql18d%F%da+Tbu1()?o(zT7StYqK6_w`e+fjXq5L^y(0 z09QA6H4oFj59c2wR~{~>jUoDzDdKz}5#onYPJRwa`SUO)Pd4)?(ENBaFVLJr6Kvz= zhTtXqbx09C1z~~iZt;g^9_2nCZ{};-b4dQJbv8HsWHXPVg^@(*!@xycp#R?a|L!+` zY5w))JWV`Gls(=}shH0#r*;~>_+-P5Qc978+QUd>J%`fyn{*TsiG-dWMiJXNgwBaT zJ=wgYFt+1ACW)XwtNx)Q9tA2LPoB&DkL16P)ERWQlY4%Y`-5aM9mZ{eKPUgI!~J3Z zkMd5A_p&v?V-o-6TUa8BndiX?ooviev(DKw=*bBVOW|=zps9=Yl|-R5@yJe*BPzN}a0mUsLn{4LfjB_oxpv(mwq# zSY*%E{iB)sNvWfzg-B!R!|+x(Q|b@>{-~cFvdDHA{F2sFGA5QGiIWy#3?P2JIpPKg6ncI^)dvqe`_|N=8 '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..d923a8c --- /dev/null +++ b/settings.gradle @@ -0,0 +1,8 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven { url = 'https://repo.papermc.io/repository/maven-public/' } + } +} + +rootProject.name = 'ItxiaohuiServerAdvancements' diff --git a/src/audit/java/top/itxiaohui/serveradvancements/audit/AuditSupport.java b/src/audit/java/top/itxiaohui/serveradvancements/audit/AuditSupport.java new file mode 100644 index 0000000..1ba7d72 --- /dev/null +++ b/src/audit/java/top/itxiaohui/serveradvancements/audit/AuditSupport.java @@ -0,0 +1,30 @@ +package top.itxiaohui.serveradvancements.audit; + +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; +import top.itxiaohui.serveradvancements.model.*; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; +import static org.mockito.Mockito.*; + +final class AuditSupport { + static JavaPlugin plugin(Path directory) { + JavaPlugin plugin = mock(JavaPlugin.class); + when(plugin.getDataFolder()).thenReturn(directory.toFile()); + YamlConfiguration config = new YamlConfiguration(); + config.set("database.busy-timeout-millis", 100); + when(plugin.getConfig()).thenReturn(config); + when(plugin.getLogger()).thenReturn(Logger.getLogger("ISA-Audit")); + return plugin; + } + static AchievementDefinition achievement(String id, ConditionDefinition... conditions) { + return new AchievementDefinition(id, id, "audit", "minecraft:stone", AdvancementFrame.TASK, + "root", 0, 0, List.of(conditions), false, false, false, true, + new RewardDefinition(0, List.of(), List.of(), false, "")); + } + static ConditionDefinition condition(ConditionType type, Map parameters) { + return new ConditionDefinition(type, parameters); + } +} diff --git a/src/audit/java/top/itxiaohui/serveradvancements/audit/AutomaticConditionsAuditTest.java b/src/audit/java/top/itxiaohui/serveradvancements/audit/AutomaticConditionsAuditTest.java new file mode 100644 index 0000000..3cd3ec3 --- /dev/null +++ b/src/audit/java/top/itxiaohui/serveradvancements/audit/AutomaticConditionsAuditTest.java @@ -0,0 +1,150 @@ +package top.itxiaohui.serveradvancements.audit; + +import org.bukkit.*; +import org.bukkit.advancement.Advancement; +import org.bukkit.advancement.AdvancementProgress; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import top.itxiaohui.serveradvancements.condition.AutomaticConditions; +import top.itxiaohui.serveradvancements.condition.ConditionEngine; +import top.itxiaohui.serveradvancements.model.*; +import top.itxiaohui.serveradvancements.statistics.StatisticsService; +import java.nio.file.Path; +import java.util.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class AutomaticConditionsAuditTest { + @TempDir Path directory; + final Player player = mock(Player.class); + final UUID id = UUID.randomUUID(); + final StatisticsService statistics = mock(StatisticsService.class); + + private ConditionDefinition condition(ConditionType type, Map parameters) { + when(player.getUniqueId()).thenReturn(id); + return new ConditionDefinition(type, parameters); + } + + @Test void nativeDistanceKeepsCentimetres() { + when(player.getStatistic(Statistic.BOAT_ONE_CM)).thenReturn(300000); + assertEquals(300000, AutomaticConditions.current(player, condition(ConditionType.PLAYER_STATISTIC, + Map.of("statistic","BOAT_ONE_CM","amount",300000)), statistics)); + } + + @Test void nativeCraftGroupsSumDifferentBedColours() { + when(player.getStatistic(Statistic.CRAFT_ITEM, Material.RED_BED)).thenReturn(1); + when(player.getStatistic(Statistic.CRAFT_ITEM, Material.WHITE_BED)).thenReturn(2); + var c = condition(ConditionType.PLAYER_STATISTIC, Map.of("statistic","CRAFT_ITEM","materials",List.of("minecraft:red_bed","minecraft:white_bed"))); + assertEquals(3, AutomaticConditions.current(player,c,statistics)); + } + + private ItemStack stack(Material material, int amount) { + ItemStack item=mock(ItemStack.class); + Material type=mock(Material.class); + when(type.isAir()).thenReturn(false); + when(type.getKey()).thenReturn(NamespacedKey.minecraft(material.name().toLowerCase(Locale.ROOT))); + when(item.getType()).thenReturn(type);when(item.getAmount()).thenReturn(amount);return item; + } + + @Test void inventoryCountsKindsNotStacksAndRequiresPerKindQuantity() { + var inventory=mock(PlayerInventory.class);when(player.getInventory()).thenReturn(inventory); + ItemStack[] contents={stack(Material.DIAMOND,32),stack(Material.DIAMOND,32),stack(Material.EMERALD,1),null}; + when(inventory.getContents()).thenReturn(contents); + var c=condition(ConditionType.INVENTORY_SET,Map.of("items",List.of("minecraft:diamond","minecraft:emerald"),"each",64,"amount",1)); + assertEquals(1,AutomaticConditions.current(player,c,statistics)); + } + + @Test void inventoryWithoutRequiredItemsDoesNotComplete() { + var inventory=mock(PlayerInventory.class);when(player.getInventory()).thenReturn(inventory); + ItemStack[] contents={stack(Material.STONE,64)}; + when(inventory.getContents()).thenReturn(contents); + var c=condition(ConditionType.INVENTORY_SET,Map.of("items",List.of("minecraft:diamond"))); + assertEquals(0,AutomaticConditions.current(player,c,statistics)); + } + + @Test void distinctFoodCountsDoNotIncreaseForRepeatedSameFood() { + var c=condition(ConditionType.EVENT_DISTINCT,Map.of("event","eat_food","amount",10)); + when(statistics.snapshot(id)).thenReturn(Map.of("event:eat_food:minecraft:apple",100D,"event:eat_food:minecraft:bread",1D,"event:cook_food:minecraft:cooked_beef",30D)); + assertEquals(2,AutomaticConditions.current(player,c,statistics)); + } + + @Test void eventSubjectFilterDoesNotTreatOtherBlocksAsFlowers() { + var c=condition(ConditionType.EVENT_DISTINCT,Map.of("event","place_block","subjects",List.of("minecraft:poppy","minecraft:dandelion"))); + when(statistics.snapshot(id)).thenReturn(Map.of("event:place_block:minecraft:stone",100D,"event:place_block:minecraft:poppy",10D)); + assertEquals(1,AutomaticConditions.current(player,c,statistics)); + } + + @Test void eventCountSumsOnlySelectedAnimals() { + var c=condition(ConditionType.EVENT_COUNT,Map.of("event","tame_animal","subjects",List.of("minecraft:cat"))); + when(statistics.snapshot(id)).thenReturn(Map.of("event:tame_animal:minecraft:cat",3D,"event:tame_animal:minecraft:wolf",10D)); + assertEquals(3,AutomaticConditions.current(player,c,statistics)); + } + + @Test void structuresAreUniqueAndFilteredByStructureType() { + var c=condition(ConditionType.VISIT_STRUCTURE,Map.of("structures",List.of("minecraft:shipwreck","minecraft:shipwreck_beached"))); + when(statistics.snapshot(id)).thenReturn(Map.of("structure:minecraft:shipwreck:world:0,0,0",1D,"structure:minecraft:shipwreck:world:100,0,0",1D,"structure:minecraft:mansion:world:0,0,0",1D)); + assertEquals(2,AutomaticConditions.current(player,c,statistics)); + } + + @Test void nativeAdvancementMustActuallyBeDone() { + var c=condition(ConditionType.VANILLA_ADVANCEMENT,Map.of("advancement","minecraft:adventure/totem_of_undying")); + Advancement advancement=mock(Advancement.class);AdvancementProgress progress=mock(AdvancementProgress.class); + when(player.getAdvancementProgress(advancement)).thenReturn(progress); + try(var bukkit=mockStatic(Bukkit.class)) { + bukkit.when(()->Bukkit.getAdvancement(NamespacedKey.minecraft("adventure/totem_of_undying"))).thenReturn(advancement); + assertEquals(0,AutomaticConditions.current(player,c,statistics)); + when(progress.isDone()).thenReturn(true);assertEquals(1,AutomaticConditions.current(player,c,statistics)); + } + } + + @Test void missingNativeAdvancementDoesNotComplete() { + var c=condition(ConditionType.VANILLA_ADVANCEMENT,Map.of("advancement","minecraft:adventure/missing")); + try(var bukkit=mockStatic(Bukkit.class)) { assertEquals(0,AutomaticConditions.current(player,c,statistics)); } + } + + @Test void customNamespaceCannotCreateCircularNativeDependencies() { + assertFalse(AutomaticConditions.validate(condition(ConditionType.VANILLA_ADVANCEMENT, + Map.of("advancement","itxiaohui_server_advancements:auto_loop"))).isEmpty()); + } + + @Test void unknownStatisticIsRejected() { + assertFalse(AutomaticConditions.validate(condition(ConditionType.PLAYER_STATISTIC,Map.of("statistic","NOT_REAL"))).isEmpty()); + } + + @Test void typedStatisticRequiresMaterialList() { + assertFalse(AutomaticConditions.validate(condition(ConditionType.PLAYER_STATISTIC,Map.of("statistic","CRAFT_ITEM"))).isEmpty()); + } + + @Test void untypedStatisticCannotSilentlyIgnoreMaterialList() { + assertFalse(AutomaticConditions.validate(condition(ConditionType.PLAYER_STATISTIC,Map.of("statistic","JUMP","materials",List.of("minecraft:stone")))).isEmpty()); + } + + @Test void malformedSubjectListCannotBecomeUnfilteredCounter() { + assertFalse(AutomaticConditions.validate(condition(ConditionType.EVENT_COUNT,Map.of("event","place_block","subjects","minecraft:poppy"))).isEmpty()); + } + + @Test void unknownServerEventIsRejected() { + assertFalse(AutomaticConditions.validate(condition(ConditionType.EVENT_COUNT,Map.of("event","not_real"))).isEmpty()); + } + + @Test void invalidStructureNamespaceIsRejected() { + assertFalse(AutomaticConditions.validate(condition(ConditionType.VISIT_STRUCTURE,Map.of("structures",List.of("oops:not_real")))).isEmpty()); + } + + @Test void actionRecorderIgnoresUnknownOrNonPositiveInputs() { + var engine=new ConditionEngine(AuditSupport.plugin(directory),null,statistics,null,null); + engine.event(player,"not_real","minecraft:stone",1); + engine.event(player,"place_block","minecraft:stone",0); + engine.event(player,"place_block","minecraft:stone",-1); + verifyNoInteractions(statistics); + } + + @Test void altitudeAndBiomeUsePersistedObservations() { + var c=condition(ConditionType.VISIT_BIOME,Map.of("biome","minecraft:cherry_grove")); + when(statistics.get(id,"visit_biome:minecraft:cherry_grove")).thenReturn(1D); + assertEquals(1,AutomaticConditions.current(player,c,statistics)); + } +} diff --git a/src/audit/java/top/itxiaohui/serveradvancements/audit/BundledCatalogAuditTest.java b/src/audit/java/top/itxiaohui/serveradvancements/audit/BundledCatalogAuditTest.java new file mode 100644 index 0000000..d2bb586 --- /dev/null +++ b/src/audit/java/top/itxiaohui/serveradvancements/audit/BundledCatalogAuditTest.java @@ -0,0 +1,150 @@ +package top.itxiaohui.serveradvancements.audit; + +import org.bukkit.Material; +import org.bukkit.configuration.file.YamlConfiguration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import top.itxiaohui.serveradvancements.config.BundledCatalogInstaller; +import top.itxiaohui.serveradvancements.config.ConfigurationManager; +import top.itxiaohui.serveradvancements.config.StrictYaml; +import top.itxiaohui.serveradvancements.model.ConditionType; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +class BundledCatalogAuditTest { + @TempDir Path directory; + + private YamlConfiguration resource(String name) throws Exception { + try (var input = getClass().getClassLoader().getResourceAsStream(name)) { + assertNotNull(input, name); + return StrictYaml.parse(new String(input.readAllBytes(), StandardCharsets.UTF_8), true); + } + } + + @Test void automaticFirstCatalogLoadsAlongside17OriginalAchievements() throws Exception { + Path target = directory.resolve("advancements.yml"); + StrictYaml.save(resource("advancements.yml"), target); + byte[] original = Files.readAllBytes(target); + var result = BundledCatalogInstaller.install(target, resource("fun-advancements.yml")); + assertEquals(134, result.added()); + assertArrayEquals(original, Files.readAllBytes(result.backup())); + var plugin = AuditSupport.plugin(directory); + plugin.getConfig().set("root.id", "custom_root"); + Material item = mock(Material.class); + when(item.isItem()).thenReturn(true); + when(item.isBlock()).thenReturn(true); + try (var materials = mockStatic(Material.class)) { + materials.when(() -> Material.matchMaterial(anyString())).thenReturn(item); + var loaded = new ConfigurationManager(plugin).load(); + assertTrue(loaded.validation().valid(), loaded.validation().errors().toString()); + assertEquals(151, loaded.definitions().size()); + var fun = loaded.definitions().values().stream().filter(d -> d.id().startsWith("fun_") || d.id().startsWith("auto_")).toList(); + assertEquals(134, fun.size()); + long manual = fun.stream().filter(d -> d.conditions().stream().anyMatch(c -> c.type() == ConditionType.MANUAL)).count(); + assertEquals(22, manual); + assertEquals(112, fun.size() - manual); + assertTrue(fun.stream().filter(d -> d.conditions().stream().anyMatch(c -> c.type() == ConditionType.MANUAL)) + .allMatch(d -> !d.enabled() && d.description().contains("默认关闭"))); + assertEquals(129, loaded.definitions().values().stream().filter(d -> d.enabled()).count()); + assertTrue(fun.stream().allMatch(d -> !d.rewards().allowReclaim() && d.rewards().items().isEmpty() + && d.rewards().commands().isEmpty() && d.rewards().experience() <= 100)); + assertEquals(fun.size(), fun.stream().map(d -> d.name()).distinct().count()); + } + } + + @Test void existingSameIdAndCustomNodesRemainUnchanged() throws Exception { + var current = StrictYaml.parse(""" + achievements: + fun_diamond_64: + name: 自定义钻石目标 + enabled: false + conditions: [{type: manual}] + my_custom: + name: 管理员自己的成就 + conditions: [{type: manual}] + """, true); + Path target = directory.resolve("advancements.yml"); + StrictYaml.save(current, target); + assertEquals(133, BundledCatalogInstaller.install(target, resource("fun-advancements.yml")).added()); + var saved = StrictYaml.read(target, true).getConfigurationSection("achievements"); + assertEquals("自定义钻石目标", saved.getConfigurationSection("fun_diamond_64").getString("name")); + assertFalse(saved.getConfigurationSection("fun_diamond_64").getBoolean("enabled")); + assertEquals("管理员自己的成就", saved.getConfigurationSection("my_custom").getString("name")); + } + + @Test void subsequentStartupDoesNotRewriteOrReinstallDeletedNodes() throws Exception { + Path target = directory.resolve("advancements.yml"); + var catalog = resource("fun-advancements.yml"); + BundledCatalogInstaller.install(target, catalog); + var current = StrictYaml.read(target, true); + current.getConfigurationSection("achievements").set("fun_diamond_64", null); + StrictYaml.save(current, target); + byte[] before = Files.readAllBytes(target); + var second = BundledCatalogInstaller.install(target, catalog); + assertEquals(0, second.added()); + assertNull(second.backup()); + assertArrayEquals(before, Files.readAllBytes(target)); + } + + @Test void duplicateYamlDoesNotGetOverwritten() throws Exception { + Path target = directory.resolve("advancements.yml"); + String invalid = "achievements:\n duplicate: {}\n duplicate: {}\n"; + Files.writeString(target, invalid); + assertThrows(IOException.class, () -> BundledCatalogInstaller.install(target, resource("fun-advancements.yml"))); + assertEquals(invalid, Files.readString(target)); + } + + @Test void nonSectionAchievementsDoesNotGetOverwritten() throws Exception { + Path target = directory.resolve("advancements.yml"); + String invalid = "achievements: do-not-overwrite\n"; + Files.writeString(target, invalid); + assertThrows(IOException.class, () -> BundledCatalogInstaller.install(target, resource("fun-advancements.yml"))); + assertEquals(invalid, Files.readString(target)); + } + + @Test void packagedCatalogIsInstalledThroughPluginResource() throws Exception { + var plugin = AuditSupport.plugin(directory); + when(plugin.getResource("fun-advancements.yml")).thenAnswer(invocation -> + getClass().getClassLoader().getResourceAsStream("fun-advancements.yml")); + assertEquals(134, BundledCatalogInstaller.install(plugin).added()); + assertEquals(0, BundledCatalogInstaller.install(plugin).added()); + } + + @Test void missingPackagedCatalogFailsWithoutCreatingConfiguration() { + assertThrows(IOException.class, () -> BundledCatalogInstaller.install(AuditSupport.plugin(directory))); + assertFalse(Files.exists(directory.resolve("advancements.yml"))); + } + + @Test void version1UpgradeReplacesOnlyUnmodifiedTemplatesAndPreservesDeletedNodes() throws Exception { + Path target = directory.resolve("advancements.yml"); + var previous = resource("fun-advancements-v1.yml"); + BundledCatalogInstaller.install(target, previous); + var current = StrictYaml.read(target, true); + var achievements = current.getConfigurationSection("achievements"); + achievements.getConfigurationSection("fun_three_cats").set("description", "服主自定义条件说明"); + achievements.getConfigurationSection("fun_five_wolves").set("enabled", false); + achievements.set("fun_ice_spikes", null); + StrictYaml.save(current, target); + byte[] before = Files.readAllBytes(target); + var result = BundledCatalogInstaller.install(target, resource("fun-advancements.yml")); + assertEquals(60, result.added()); + assertEquals(71, result.updated()); + assertArrayEquals(before, Files.readAllBytes(result.backup())); + var saved = StrictYaml.read(target, true); + assertEquals(2, saved.getInt("bundled-fun-catalog-version")); + var nodes = saved.getConfigurationSection("achievements"); + assertEquals("服主自定义条件说明", nodes.getConfigurationSection("fun_three_cats").getString("description")); + assertFalse(nodes.getConfigurationSection("fun_five_wolves").getBoolean("enabled")); + assertFalse(nodes.contains("fun_ice_spikes")); + assertEquals("player_statistic", nodes.getConfigurationSection("fun_first_bed").getMapList("conditions").getFirst().get("type")); + assertFalse(nodes.getConfigurationSection("fun_group_photo").getBoolean("enabled")); + assertEquals(0, BundledCatalogInstaller.install(target, resource("fun-advancements.yml")).updated()); + } +} diff --git a/src/audit/java/top/itxiaohui/serveradvancements/audit/ConfigurationAuditTest.java b/src/audit/java/top/itxiaohui/serveradvancements/audit/ConfigurationAuditTest.java new file mode 100644 index 0000000..a84b8df --- /dev/null +++ b/src/audit/java/top/itxiaohui/serveradvancements/audit/ConfigurationAuditTest.java @@ -0,0 +1,112 @@ +package top.itxiaohui.serveradvancements.audit; + +import org.bukkit.Material; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockedStatic; +import top.itxiaohui.serveradvancements.config.ConfigurationManager; +import java.nio.file.*; +import java.util.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ConfigurationAuditTest { + @TempDir Path directory; + ConfigurationManager configuration; + MockedStatic materials; + @BeforeEach void setup() { + configuration=new ConfigurationManager(AuditSupport.plugin(directory)); + Material item=mock(Material.class); when(item.isItem()).thenReturn(true);when(item.isBlock()).thenReturn(true); + materials=mockStatic(Material.class); + for(String key:List.of("minecraft:stone","minecraft:diamond","minecraft:emerald")) + materials.when(()->Material.matchMaterial(key)).thenReturn(item); + } + @AfterEach void cleanup() { materials.close(); } + ConfigurationManager.LoadResult yaml(String content) throws Exception { + Files.writeString(directory.resolve("advancements.yml"),content); + return configuration.load(); + } + String node(String id,String parent,String condition) { + return " "+id+":\n name: test\n icon: minecraft:stone\n parent: "+parent+"\n conditions:\n - "+condition+"\n"; + } + @Test void invalidIconRejected() throws Exception { + var result=yaml("achievements:\n"+node("safe","root","{type: manual}").replace("minecraft:stone","minecraft:not_real")); + assertFalse(result.validation().valid()); assertTrue(result.definitions().isEmpty()); + } + @Test void unknownConditionRejected() throws Exception { + assertFalse(yaml("achievements:\n"+node("safe","root","{type: typo}")).validation().valid()); + } + @Test void missingParentDetected() throws Exception { + assertFalse(yaml("achievements:\n"+node("safe","missing","{type: manual}")).validation().valid()); + } + @Test void parentCycleDetected() throws Exception { + assertFalse(yaml("achievements:\n"+node("a","b","{type: manual}")+node("b","a","{type: manual}")).validation().valid()); + } + @Test void completionDependencyCycleMustBeDetected() throws Exception { + assertFalse(yaml("achievements:\n"+node("a","root","{type: complete_achievement, achievement: b}")+node("b","root","{type: complete_achievement, achievement: a}")).validation().valid()); + } + @Test void duplicateYamlIdMustBeRejected() throws Exception { + assertFalse(yaml("achievements:\n"+node("same","root","{type: manual}")+node("same","root","{type: first_join}")).validation().valid()); + } + @Test void reservedRootCannotBeOrdinaryAchievement() throws Exception { + assertFalse(yaml("achievements:\n"+node("root","root","{type: first_join}")).validation().valid()); + } + @Test void disabledParentMustNotSilentlyStrandEnabledChild() throws Exception { + assertFalse(yaml("achievements:\n"+node("parent","root","{type: manual}")+" enabled: false\n"+node("child","parent","{type: manual}")).validation().valid()); + } + @Test void nanTargetMustBeRejected() throws Exception { + assertFalse(yaml("achievements:\n"+node("nan","root","{type: collect_item, item: 'minecraft:diamond', amount: .nan}")).validation().valid()); + } + @Test void infinityTargetMustBeRejected() throws Exception { + assertFalse(yaml("achievements:\n"+node("inf","root","{type: online_time, amount: .inf}")).validation().valid()); + } + @Test void unknownOnlineUnitMustBeRejected() throws Exception { + assertFalse(yaml("achievements:\n"+node("time","root","{type: online_time, amount: 10, unit: years_typo}")).validation().valid()); + } + @Test void invalidEntityMustBeRejected() throws Exception { + assertFalse(yaml("achievements:\n"+node("mob","root","{type: kill_mob, entity: 'minecraft:not_real', amount: 1}")).validation().valid()); + } + @Test void malformedNumericTargetMustBeRejected() throws Exception { + assertFalse(yaml("achievements:\n"+node("bad","root","{type: online_time, amount: banana}")).validation().valid()); + } + @Test void regionWithoutCoordinatesMustBeRejected() throws Exception { + assertFalse(yaml("achievements:\n"+node("region","root","{type: reach_location}")).validation().valid()); + } + @Test void negativeRewardMustBeRejected() throws Exception { + assertFalse(yaml("achievements:\n"+node("xp","root","{type: manual}")+" rewards: {experience: -100}\n").validation().valid()); + } + @Test void dottedIdsMustRoundTripThroughCreateAndLoad() throws Exception { + assertTrue(configuration.createSkeleton("branch.one")); + assertTrue(configuration.load().definitions().containsKey("branch.one"),"YAML path separator must not split a legal resource ID"); + } + @Test void rootIdChangeMustBeValidatedAndProtected() throws Exception { + var plugin=AuditSupport.plugin(directory);plugin.getConfig().set("root.id","custom_root"); + var manager=new ConfigurationManager(plugin); + assertFalse(manager.createSkeleton("custom_root"),"Configured root must be reserved, not only the literal root"); + } + @Test void invalidGraphNodesMustBeExcludedAtStartup() throws Exception { + var result=yaml("achievements:\n"+node("a","b","{type: manual}")+node("b","a","{type: manual}")+node("good","root","{type: manual}")); + configuration.applyValidSubset(result); + assertEquals(Set.of("good"),configuration.definitions().keySet()); + } + @Test void validSiblingSurvivesLocallyInvalidNode() throws Exception { + var result=yaml("achievements:\n"+node("bad","root","{type: typo}")+node("good","root","{type: manual}")); + configuration.applyValidSubset(result); assertEquals(Set.of("good"),configuration.definitions().keySet()); + } + @Test void bulkValidDefinitionsParseWithoutCrash() throws Exception { + StringBuilder input=new StringBuilder("achievements:\n"); + for(int i=0;i<1000;i++) input.append(node("node_"+i,"root","{type: manual}")); + long started=System.nanoTime(); var result=yaml(input.toString()); + assertTrue(result.validation().valid());assertEquals(1000,result.definitions().size()); + System.out.printf(Locale.ROOT,"CONFIG_1000_NODES_MS=%.2f%n",(System.nanoTime()-started)/1e6); + } + @Test void deletingParentWithChildIsBlocked() throws Exception { + var result=yaml("achievements:\n"+node("a","root","{type: manual}")+node("b","a","{type: manual}")); + configuration.apply(result); assertFalse(configuration.delete("a").success()); + } + @Test void deepTree10000MustNotOverflowStack() throws Exception { + StringBuilder input=new StringBuilder("achievements:\n"); + for(int i=9999;i>=0;i--)input.append(node("n"+i,i==0?"root":"n"+(i-1),"{type: manual}")); + assertDoesNotThrow(()->yaml(input.toString())); + } +} diff --git a/src/audit/java/top/itxiaohui/serveradvancements/audit/DatabaseAuditTest.java b/src/audit/java/top/itxiaohui/serveradvancements/audit/DatabaseAuditTest.java new file mode 100644 index 0000000..498cd21 --- /dev/null +++ b/src/audit/java/top/itxiaohui/serveradvancements/audit/DatabaseAuditTest.java @@ -0,0 +1,149 @@ +package top.itxiaohui.serveradvancements.audit; + +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import top.itxiaohui.serveradvancements.database.DatabaseManager; +import java.nio.file.*; +import java.sql.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.*; + +class DatabaseAuditTest { + @TempDir Path directory; + DatabaseManager database; + @BeforeEach void open() throws Exception { database = new DatabaseManager(AuditSupport.plugin(directory)); database.open(); } + @AfterEach void close() throws Exception { database.close(); } + + @Test void sqlInjectionRemainsData() throws Exception { + UUID player = UUID.randomUUID(); + String key = "x'); DROP TABLE player_statistics; --"; + database.saveStatistics(Map.of(player, Map.of(key, 123D))); + assertEquals(123D, database.loadStatistics(player).get(key)); + database.audit("actor'", "INJECTION", "target", "'); DROP TABLE reward_claims; --"); + assertEquals(DatabaseManager.RewardStatus.NONE, database.rewardStatus(player, key)); + } + + @Test void oneRewardReservationUnder64ConcurrentCalls() throws Exception { + ExecutorService workers = Executors.newFixedThreadPool(8); + UUID player = UUID.randomUUID(); + AtomicInteger reserved = new AtomicInteger(); + try { + List> tasks = new ArrayList<>(); + for (int i=0;i<64;i++) tasks.add(() -> { if(database.beginReward(player,"one", false)) reserved.incrementAndGet(); return null; }); + for(Future task:workers.invokeAll(tasks)) task.get(); + } finally { workers.shutdownNow(); } + assertEquals(1, reserved.get()); + } + + @Test void claimedRewardSurvivesReopen() throws Exception { + UUID player = UUID.randomUUID(); + assertTrue(database.beginReward(player,"one",false)); + database.finishReward(player,"one",true,"ok"); + database.close(); database.open(); + assertFalse(database.beginReward(player,"one",false)); + assertEquals(DatabaseManager.RewardStatus.CLAIMED,database.rewardStatus(player,"one")); + } + + @Test void pendingRewardMustBlockEvenWhenReclaimEnabled() throws Exception { + UUID player = UUID.randomUUID(); + assertTrue(database.beginReward(player,"crash",true)); + database.close(); database.open(); + assertFalse(database.beginReward(player,"crash",true), "Unresolved PENDING must not be replayed, including allow-reclaim=true"); + } + + @Test void partiallyFailedRewardMustNotAutomaticallyReplayWholeReward() throws Exception { + UUID player = UUID.randomUUID(); + assertTrue(database.beginReward(player,"partial",false)); + database.finishReward(player,"partial",false,"XP delivered, command failed"); + assertFalse(database.beginReward(player,"partial",false), "FAILED may have already delivered XP/items and requires manual reconciliation"); + } + + @Test void writerLockFailsWithoutOverwritingPersistedStatistics() throws Exception { + UUID player = UUID.randomUUID(); + database.saveStatistics(Map.of(player,Map.of("stone",5D))); + try(Connection external=DriverManager.getConnection("jdbc:sqlite:"+database.databasePath()); Statement lock=external.createStatement()) { + lock.execute("BEGIN IMMEDIATE"); + long started=System.nanoTime(); + assertThrows(SQLException.class,()->database.saveStatistics(Map.of(player,Map.of("stone",99D)))); + double millis=(System.nanoTime()-started)/1e6; + System.out.printf(Locale.ROOT,"SQLITE_LOCK_FAILURE_MS=%.2f%n",millis); + lock.execute("ROLLBACK"); + } + assertEquals(5D,database.loadStatistics(player).get("stone")); + } + + @Test void backupContainsCommittedDataAndPassesIntegrityCheck() throws Exception { + UUID player=UUID.randomUUID(); + database.saveStatistics(Map.of(player,Map.of("stat",42D))); + Path backup=database.backup(); + try(Connection copy=DriverManager.getConnection("jdbc:sqlite:"+backup); Statement sql=copy.createStatement()) { + try(ResultSet result=sql.executeQuery("PRAGMA integrity_check")) { assertEquals("ok",result.getString(1)); } + try(ResultSet result=sql.executeQuery("SELECT value FROM player_statistics")) { assertEquals(42D,result.getDouble(1)); } + } + } + + @Test void sameSecondBackupRequestsMustNotCollide() throws Exception { + // Repeated immediate calls are intentional: administrators can double-click or automate backups. + for(int i=0;i<3;i++) assertTrue(Files.exists(database.backup())); + } + + @Test void corruptedDatabaseStopsInitialization() throws Exception { + Path corrupt=directory.resolve("corrupt/data"); Files.createDirectories(corrupt); + Files.writeString(corrupt.resolve("advancements.db"),"THIS IS NOT SQLITE"); + DatabaseManager broken=new DatabaseManager(AuditSupport.plugin(directory.resolve("corrupt"))); + assertThrows(SQLException.class,broken::open); + try { + assertDoesNotThrow(broken::close,"Initialization failure must still release the JDBC file handle"); + } finally { + var field=DatabaseManager.class.getDeclaredField("connection");field.setAccessible(true); + Connection leaked=(Connection)field.get(broken);if(leaked!=null&&!leaked.isClosed())leaked.close(); + } + } + + @Test void futureSchemaRejectedWithoutDeletingExistingData() throws Exception { + database.close(); + try(Connection raw=DriverManager.getConnection("jdbc:sqlite:"+database.databasePath());Statement sql=raw.createStatement()) { + sql.executeUpdate("UPDATE schema_version SET version=99"); + } + assertThrows(SQLException.class,database::open); + } + + @Test void batch100000CountersBenchmark() throws Exception { + Map> batch=new HashMap<>(); + for(int player=0;player<1000;player++) { + Map stats=new HashMap<>(); + for(int key=0;key<100;key++) stats.put("key:"+key,(double)key); + batch.put(UUID.randomUUID(),stats); + } + long started=System.nanoTime();database.saveStatistics(batch); + double millis=(System.nanoTime()-started)/1e6; + try(Connection raw=DriverManager.getConnection("jdbc:sqlite:"+database.databasePath());Statement sql=raw.createStatement();ResultSet result=sql.executeQuery("SELECT count(*) FROM player_statistics")) { + assertEquals(100_000,result.getInt(1)); + } + System.out.printf(Locale.ROOT,"SQLITE_BATCH rows=100000 elapsed_ms=%.2f rows_per_second=%.0f%n",millis,100_000_000D/millis); + } + @Test void unexecutedReservationCanResumeButPendingCannot() throws Exception { + UUID id=UUID.randomUUID(); + assertEquals(DatabaseManager.Reservation.RESERVED,database.reserveReward(id,"resume",false)); + assertEquals(DatabaseManager.Reservation.RESERVED,database.reserveReward(id,"resume",false)); + assertTrue(database.startReward(id,"resume")); + assertEquals(DatabaseManager.Reservation.REVIEW_REQUIRED,database.reserveReward(id,"resume",true)); + database.releaseUnexecutedReward(id,"resume"); + assertEquals(DatabaseManager.Reservation.RESERVED,database.reserveReward(id,"resume",false)); + } + @Test void reclaimOnlyStartsNewAttemptAfterConfirmedClaim() throws Exception { + UUID id=UUID.randomUUID();database.reserveReward(id,"reclaim",false);database.startReward(id,"reclaim");database.finishReward(id,"reclaim",true,"ok"); + assertEquals(DatabaseManager.Reservation.NO_REWARD,database.reserveReward(id,"reclaim",false)); + assertEquals(DatabaseManager.Reservation.RESERVED,database.reserveReward(id,"reclaim",true)); + } + @Test void databaseQueueRunsOnWorkerAndReturnsWithoutBlockingCaller() throws Exception { + CountDownLatch entered=new CountDownLatch(1),release=new CountDownLatch(1);Thread caller=Thread.currentThread(); + try { + var future=database.submit(()->{assertNotSame(caller,Thread.currentThread());entered.countDown();assertTrue(release.await(5,TimeUnit.SECONDS));return 7;}); + assertTrue(entered.await(5,TimeUnit.SECONDS));assertFalse(future.isDone()); + release.countDown();assertEquals(7,future.get(5,TimeUnit.SECONDS)); + } finally {release.countDown();} + } +} diff --git a/src/audit/java/top/itxiaohui/serveradvancements/audit/LogicSecurityAuditTest.java b/src/audit/java/top/itxiaohui/serveradvancements/audit/LogicSecurityAuditTest.java new file mode 100644 index 0000000..fb6c5c5 --- /dev/null +++ b/src/audit/java/top/itxiaohui/serveradvancements/audit/LogicSecurityAuditTest.java @@ -0,0 +1,165 @@ +package top.itxiaohui.serveradvancements.audit; + +import org.bukkit.*; +import org.bukkit.command.*; +import org.bukkit.entity.*; +import org.bukkit.event.inventory.*; +import org.bukkit.inventory.*; +import org.bukkit.plugin.java.JavaPlugin; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.MockedStatic; +import top.itxiaohui.serveradvancements.ItxiaohuiServerAdvancements; +import top.itxiaohui.serveradvancements.advancement.AdvancementManager; +import top.itxiaohui.serveradvancements.command.IsaCommand; +import top.itxiaohui.serveradvancements.condition.ConditionEngine; +import top.itxiaohui.serveradvancements.config.*; +import top.itxiaohui.serveradvancements.database.DatabaseManager; +import top.itxiaohui.serveradvancements.gui.AdminGui; +import top.itxiaohui.serveradvancements.listener.PlayerActivityListener; +import top.itxiaohui.serveradvancements.model.*; +import top.itxiaohui.serveradvancements.reward.RewardService; +import top.itxiaohui.serveradvancements.statistics.StatisticsService; +import java.lang.reflect.*; +import java.nio.file.Path; +import java.util.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class LogicSecurityAuditTest { + @TempDir Path directory; + @ParameterizedTest @ValueSource(strings={"give","revoke","progress","editor","reload","create","delete","validate","backup"}) + void unprivilegedCommandsMustNeverReachPrivilegedServices(String subcommand) { + ItxiaohuiServerAdvancements plugin=mock(ItxiaohuiServerAdvancements.class); + ConfigurationManager configuration=mock(ConfigurationManager.class); + MessageService messages=mock(MessageService.class); + CommandSender sender=mock(CommandSender.class); + new IsaCommand(plugin,configuration,messages).onCommand(sender,mock(Command.class),"isa",new String[]{subcommand,"victim","first_log","confirm"}); + verify(messages).send(sender,"no-permission");verifyNoInteractions(plugin,configuration); + } + @Test void adminTabCompletionMustBePermissionFiltered() { + ItxiaohuiServerAdvancements plugin=mock(ItxiaohuiServerAdvancements.class); + var results=new IsaCommand(plugin,mock(ConfigurationManager.class),mock(MessageService.class)) + .onTabComplete(mock(CommandSender.class),mock(Command.class),"isa",new String[]{""}); + assertFalse(results.contains("backup"),"Unprivileged completion exposes admin commands (information disclosure only)"); + } + @Test void guiRechecksPermissionAfterMenuWasOpened() throws Exception { + JavaPlugin plugin=AuditSupport.plugin(directory); + ConfigurationManager configuration=mock(ConfigurationManager.class); + AdvancementManager advancements=mock(AdvancementManager.class); + ConditionEngine conditions=mock(ConditionEngine.class); + Class holderClass=Class.forName(AdminGui.class.getName()+"$Holder"); + Constructor constructor=holderClass.getDeclaredConstructor(int.class);constructor.setAccessible(true); + InventoryHolder holder=(InventoryHolder)constructor.newInstance(0); + Inventory inventory=mock(Inventory.class);when(inventory.getHolder(false)).thenReturn(holder); + InventoryClickEvent click=mock(InventoryClickEvent.class);when(click.getInventory()).thenReturn(inventory); + Player player=mock(Player.class);when(click.getWhoClicked()).thenReturn(player);when(click.getRawSlot()).thenReturn(0); + new AdminGui(plugin,configuration,advancements,conditions).onClick(click); + verify(click).setCancelled(true);verify(player).closeInventory();verifyNoInteractions(configuration,advancements,conditions); + } + @Test void arbitraryInventoryCannotInvokeAdminActions() { + ConfigurationManager configuration=mock(ConfigurationManager.class); + AdvancementManager advancements=mock(AdvancementManager.class); + ConditionEngine conditions=mock(ConditionEngine.class); + Inventory inventory=mock(Inventory.class);when(inventory.getHolder(false)).thenReturn(mock(InventoryHolder.class)); + InventoryClickEvent click=mock(InventoryClickEvent.class);when(click.getInventory()).thenReturn(inventory); + new AdminGui(AuditSupport.plugin(directory),configuration,advancements,conditions).onClick(click); + verifyNoInteractions(configuration,advancements,conditions); + } + @Test void noOpCraftCannotIncreaseCraftOrObtainCounters() { + ConditionEngine conditions=mock(ConditionEngine.class); + CraftItemEvent craft=mock(CraftItemEvent.class);Player player=mock(Player.class); + ItemStack stack=mock(ItemStack.class);when(stack.getAmount()).thenReturn(4);when(stack.getType()).thenReturn(Material.DIAMOND); + when(craft.getWhoClicked()).thenReturn(player);when(craft.getCurrentItem()).thenReturn(stack);when(craft.getAction()).thenReturn(InventoryAction.NOTHING); + new PlayerActivityListener(AuditSupport.plugin(directory),mock(StatisticsService.class),conditions,mock(AdvancementManager.class)).onCraft(craft); + verifyNoInteractions(conditions); + } + @Test void andConditionsRequireEveryCounter() { + JavaPlugin plugin=AuditSupport.plugin(directory);ConfigurationManager config=mock(ConfigurationManager.class); + StatisticsService stats=mock(StatisticsService.class);AdvancementManager advancements=mock(AdvancementManager.class);RewardService rewards=mock(RewardService.class); + Player player=mock(Player.class);UUID id=UUID.randomUUID();when(player.getUniqueId()).thenReturn(id); + when(stats.isReady(id)).thenReturn(true); + var definition=AuditSupport.achievement("both",AuditSupport.condition(ConditionType.MINE_BLOCK,Map.of("block","minecraft:stone","amount",10)), + AuditSupport.condition(ConditionType.KILL_MOB,Map.of("entity","minecraft:zombie","amount",2))); + when(config.definitions()).thenReturn(Map.of("both",definition));when(stats.get(id,"mine_block:minecraft:stone")).thenReturn(10D); + new ConditionEngine(plugin,config,stats,advancements,rewards).evaluate(player); + verify(advancements,never()).award(any(),anyString());verify(rewards,never()).complete(any(),any(),any(),any()); + } + @Test void nanTargetCannotAutoCompleteWithoutAnyProgress() { + JavaPlugin plugin=AuditSupport.plugin(directory);ConfigurationManager config=mock(ConfigurationManager.class); + StatisticsService stats=mock(StatisticsService.class);AdvancementManager advancements=mock(AdvancementManager.class);RewardService rewards=mock(RewardService.class); + Player player=mock(Player.class);UUID id=UUID.randomUUID();when(player.getUniqueId()).thenReturn(id);when(stats.isReady(id)).thenReturn(true); + var definition=AuditSupport.achievement("nan",AuditSupport.condition(ConditionType.MINE_BLOCK,Map.of("block","minecraft:stone","amount",Double.NaN))); + when(config.definitions()).thenReturn(Map.of("nan",definition)); + new ConditionEngine(plugin,config,stats,advancements,rewards).evaluate(player); + verify(advancements,never()).award(any(),anyString()); + } + @Test void partialRewardFailureMustNotDuplicateExperience() throws Exception { + JavaPlugin plugin=AuditSupport.plugin(directory);DatabaseManager database=new DatabaseManager(plugin);database.open(); + try(MockedStatic bukkit=mockStatic(Bukkit.class)) { + ConsoleCommandSender console=mock(ConsoleCommandSender.class);bukkit.when(Bukkit::getConsoleSender).thenReturn(console); + Player player=mock(Player.class);when(player.getUniqueId()).thenReturn(UUID.randomUUID());when(player.getName()).thenReturn("AuditPlayer");when(player.isOnline()).thenReturn(true); + var reward=new RewardDefinition(100,List.of(),List.of("missing_command"),false,""); + var definition=new AchievementDefinition("partial","partial","","minecraft:stone",AdvancementFrame.TASK,"root",0,0,List.of(),false,false,false,true,reward); + java.util.concurrent.BlockingQueue main=new java.util.concurrent.LinkedBlockingQueue<>(); + RewardService rewards=new RewardService(plugin,database,mock(MessageService.class),main::add); + var first=rewards.grant(player,definition); + Runnable action=main.poll(5,java.util.concurrent.TimeUnit.SECONDS);assertNotNull(action);action.run(); + assertEquals(RewardService.Outcome.REVIEW_REQUIRED,first.get(5,java.util.concurrent.TimeUnit.SECONDS)); + assertEquals(RewardService.Outcome.REVIEW_REQUIRED,rewards.grant(player,definition).get(5,java.util.concurrent.TimeUnit.SECONDS)); + verify(player,times(1)).giveExp(100); + } finally { database.close(); } + } + @Test void rewardCommandRejectsNewlineAndSanitizesPlayerPlaceholder() throws Exception { + RewardService service=new RewardService(AuditSupport.plugin(directory),mock(DatabaseManager.class),mock(MessageService.class)); + Method render=RewardService.class.getDeclaredMethod("renderCommand",String.class,Player.class);render.setAccessible(true); + Player player=mock(Player.class);when(player.getUniqueId()).thenReturn(UUID.randomUUID());when(player.getName()).thenReturn("name\nstop; @a"); + assertEquals("give namestopa minecraft:stone",render.invoke(service,"/give {player} minecraft:stone",player)); + InvocationTargetException thrown=assertThrows(InvocationTargetException.class,()->render.invoke(service,"say hi\nstop",player)); + assertInstanceOf(IllegalArgumentException.class,thrown.getCause()); + } + @Test void subBlockWalkingDistanceMustBeCounted() { + Player player=mock(Player.class);World world=mock(World.class);ConditionEngine conditions=mock(ConditionEngine.class); + var listener=new PlayerActivityListener(AuditSupport.plugin(directory),mock(StatisticsService.class),conditions,mock(AdvancementManager.class)); + listener.onMove(new org.bukkit.event.player.PlayerMoveEvent(player,new Location(world,0.1,64,0.1),new Location(world,0.9,64,0.1))); + verify(conditions).record(eq(player),eq(ConditionType.MOVE_DISTANCE),eq(""),eq(0.8)); + } + @Test void successfulNativeCraftStatisticCountsExactDelta() { + ConditionEngine conditions=mock(ConditionEngine.class);Player player=mock(Player.class); + var listener=new PlayerActivityListener(AuditSupport.plugin(directory),mock(StatisticsService.class),conditions,mock(AdvancementManager.class)); + var event=new org.bukkit.event.player.PlayerStatisticIncrementEvent(player,Statistic.CRAFT_ITEM,20,24,Material.OAK_PLANKS); + listener.onStatistic(event); + verify(conditions).record(player,ConditionType.CRAFT_ITEM,"minecraft:oak_planks",4); + verify(conditions).record(player,ConditionType.OBTAIN_ITEM,"minecraft:oak_planks",4); + } + @Test void reachedRegionRemainsSatisfiedAfterPlayerLeaves() { + JavaPlugin plugin=AuditSupport.plugin(directory);ConfigurationManager config=mock(ConfigurationManager.class); + StatisticsService stats=new StatisticsService(plugin,mock(DatabaseManager.class)); + AdvancementManager advancements=mock(AdvancementManager.class);RewardService rewards=mock(RewardService.class); + Player player=mock(Player.class);UUID id=UUID.randomUUID();when(player.getUniqueId()).thenReturn(id);stats.load(id); + World world=mock(World.class);when(world.getName()).thenReturn("world");when(world.getKey()).thenReturn(NamespacedKey.minecraft("overworld")); + when(player.getLocation()).thenReturn(new Location(world,0,64,0)); + var region=AuditSupport.condition(ConditionType.REACH_LOCATION,Map.of("world","world","x",0,"y",64,"z",0,"radius",2)); + var mine=AuditSupport.condition(ConditionType.MINE_BLOCK,Map.of("block","minecraft:stone","amount",10)); + var definition=AuditSupport.achievement("region",region,mine);when(config.definitions()).thenReturn(Map.of("region",definition)); + var engine=new ConditionEngine(plugin,config,stats,advancements,rewards);engine.evaluate(player); + assertEquals(1D,stats.get(id,region.statisticKey()));verify(rewards,never()).complete(any(),any(),any(),any()); + when(player.getLocation()).thenReturn(new Location(world,100,64,100));stats.increment(id,"mine_block:minecraft:stone",10);engine.evaluate(player); + verify(rewards).complete(eq(player),eq(definition),any(),any()); + } + @Test void reservationFailureNeverAwardsNativeProgressOrRewards() throws Exception { + DatabaseManager database=mock(DatabaseManager.class); + var pending=new java.util.concurrent.CompletableFuture(); + when(database.submit(any())).thenAnswer(invocation->pending); + Player player=mock(Player.class);when(player.getUniqueId()).thenReturn(UUID.randomUUID());when(player.isOnline()).thenReturn(true); + var awarded=new java.util.concurrent.atomic.AtomicBoolean(); + RewardService service=new RewardService(AuditSupport.plugin(directory),database,mock(MessageService.class),Runnable::run); + var request=service.complete(player,AuditSupport.achievement("locked"),()->{awarded.set(true);return true;},()->{}); + assertFalse(awarded.get());assertFalse(request.isDone()); + pending.completeExceptionally(new java.sql.SQLException("database locked")); + assertEquals(RewardService.Outcome.RETRY_LATER,request.get(1,java.util.concurrent.TimeUnit.SECONDS)); + assertFalse(awarded.get());verify(player,never()).giveExp(anyInt()); + } +} diff --git a/src/audit/java/top/itxiaohui/serveradvancements/audit/StatisticsAuditTest.java b/src/audit/java/top/itxiaohui/serveradvancements/audit/StatisticsAuditTest.java new file mode 100644 index 0000000..b083bb0 --- /dev/null +++ b/src/audit/java/top/itxiaohui/serveradvancements/audit/StatisticsAuditTest.java @@ -0,0 +1,93 @@ +package top.itxiaohui.serveradvancements.audit; + +import org.bukkit.entity.Player; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import top.itxiaohui.serveradvancements.database.DatabaseManager; +import top.itxiaohui.serveradvancements.statistics.StatisticsService; +import java.lang.reflect.Method; +import java.nio.file.Path; +import java.sql.SQLException; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class StatisticsAuditTest { + @TempDir Path directory; + void flush(StatisticsService service) throws Exception { + Method flush=StatisticsService.class.getDeclaredMethod("flushAsyncBody");flush.setAccessible(true);flush.invoke(service); + } + @Test void fastRejoinMustPreserveDirtyInMemoryCounters() { + DatabaseManager database=mock(DatabaseManager.class); + StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database); + UUID id=UUID.randomUUID(); stats.load(id);stats.increment(id,"diamond",64);stats.load(id); + assertEquals(64D,stats.get(id,"diamond"),"Rejoin must not overwrite dirty cache with a stale DB snapshot"); + } + @Test void readFailureMustNotCreateWritableZeroBaseline() throws Exception { + DatabaseManager database=mock(DatabaseManager.class);when(database.loadStatistics(any())).thenThrow(new SQLException("database locked")); + StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database); + UUID id=UUID.randomUUID(); stats.load(id);stats.increment(id,"diamond",1);flush(stats); + verify(database,never()).saveStatistics(anyMap()); + } + @Test void failedBatchRemainsDirtyAndIsRetried() throws Exception { + DatabaseManager database=mock(DatabaseManager.class); + doThrow(new SQLException("disk full")).doNothing().when(database).saveStatistics(anyMap()); + StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database); + stats.increment(UUID.randomUUID(),"stone",10);flush(stats);flush(stats); + verify(database,times(2)).saveStatistics(anyMap()); + } + @Test void cacheAcceptsConcurrent80000IncrementsWithoutLostCount() throws Exception { + DatabaseManager database=mock(DatabaseManager.class); + StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database); + UUID id=UUID.randomUUID(); ExecutorService workers=Executors.newFixedThreadPool(8); + try { + List> tasks=new ArrayList<>(); + for(int w=0;w<8;w++) tasks.add(()->{for(int i=0;i<10000;i++)stats.increment(id,"stone",1);return null;}); + for(var task:workers.invokeAll(tasks))task.get(); + } finally { workers.shutdownNow(); } + assertEquals(80_000D,stats.get(id,"stone"));flush(stats); + verify(database).saveStatistics(Map.of(id,Map.of("stone",80000D))); + } + @Test void nonFiniteCountersMustNotEnterPersistence() { + StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),mock(DatabaseManager.class)); + UUID id=UUID.randomUUID();stats.increment(id,"poison",Double.NaN); + assertTrue(Double.isFinite(stats.get(id,"poison")),"NaN poisons comparisons and SQLite NULL handling"); + } + @Test void duplicateSessionStartMustNotDiscardElapsedTimeOrStats() throws Exception { + StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),mock(DatabaseManager.class)); + Player player=mock(Player.class); UUID id=UUID.randomUUID();when(player.getUniqueId()).thenReturn(id); + stats.beginSession(player);stats.increment(id,"mine",25);stats.beginSession(player); + assertEquals(25D,stats.get(id,"mine")); + } + @Test void incrementRacingWithFlushMustRemainDirty() throws Exception { + DatabaseManager database=mock(DatabaseManager.class); + StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database);UUID id=UUID.randomUUID(); + CountDownLatch enteredSave=new CountDownLatch(1),allowSave=new CountDownLatch(1); + stats.load(id);stats.increment(id,"stone",1); + doAnswer(invocation->{enteredSave.countDown();assertTrue(allowSave.await(5,TimeUnit.SECONDS));return null;}).when(database).saveStatistics(anyMap()); + ExecutorService worker=Executors.newSingleThreadExecutor(); + try { + Future saving=worker.submit(()->{try{flush(stats);}catch(Exception e){throw new RuntimeException(e);}}); + assertTrue(enteredSave.await(5,TimeUnit.SECONDS));stats.increment(id,"stone",1); + allowSave.countDown();saving.get();flush(stats); + verify(database).saveStatistics(Map.of(id,Map.of("stone",2D))); + } finally { allowSave.countDown();worker.shutdownNow(); } + } + @Test void recoveringReadMergesQueuedIncrementOntoHistoricalBaseline() throws Exception { + DatabaseManager database=mock(DatabaseManager.class);UUID id=UUID.randomUUID(); + when(database.loadStatistics(id)).thenThrow(new SQLException("temporarily unavailable")).thenReturn(Map.of("stone",100D)); + StatisticsService stats=new StatisticsService(AuditSupport.plugin(directory),database); + stats.load(id);stats.increment(id,"stone",3);assertFalse(stats.isReady(id));flush(stats); + verify(database).saveStatistics(Map.of(id,Map.of("stone",103D))); + } + @Test void onlinePlayerCacheRemainsWhenOnlineTimeIsDisabled() throws Exception { + DatabaseManager database=mock(DatabaseManager.class); + when(database.submit(any())).thenAnswer(invocation->{java.util.concurrent.Callable action=invocation.getArgument(0);return CompletableFuture.completedFuture(action.call());}); + var plugin=AuditSupport.plugin(directory);plugin.getConfig().set("statistics.online-time-enabled",false); + StatisticsService stats=new StatisticsService(plugin,database);Player player=mock(Player.class);UUID id=UUID.randomUUID();when(player.getUniqueId()).thenReturn(id); + stats.beginSession(player).get();stats.increment(id,"stone",5);flush(stats); + assertTrue(stats.isReady(id));assertEquals(5D,stats.get(id,"stone")); + stats.endSession(id);flush(stats);assertEquals(0,stats.cachedPlayerCount()); + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/ItxiaohuiServerAdvancements.java b/src/main/java/top/itxiaohui/serveradvancements/ItxiaohuiServerAdvancements.java new file mode 100644 index 0000000..4e491ab --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/ItxiaohuiServerAdvancements.java @@ -0,0 +1,151 @@ +package top.itxiaohui.serveradvancements; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import top.itxiaohui.serveradvancements.advancement.AdvancementManager; +import top.itxiaohui.serveradvancements.command.IsaCommand; +import top.itxiaohui.serveradvancements.condition.ConditionEngine; +import top.itxiaohui.serveradvancements.config.ConfigurationManager; +import top.itxiaohui.serveradvancements.config.MessageService; +import top.itxiaohui.serveradvancements.database.DatabaseManager; +import top.itxiaohui.serveradvancements.gui.AdminGui; +import top.itxiaohui.serveradvancements.listener.PlayerActivityListener; +import top.itxiaohui.serveradvancements.reward.RewardService; +import top.itxiaohui.serveradvancements.statistics.StatisticsService; + +import java.io.File; +import java.sql.SQLException; +import java.util.Map; +import top.itxiaohui.serveradvancements.config.StrictYaml; +import top.itxiaohui.serveradvancements.config.BundledCatalogInstaller; +import org.bukkit.configuration.ConfigurationSection; + +public final class ItxiaohuiServerAdvancements extends JavaPlugin { + private DatabaseManager database; + private StatisticsService statistics; + private ConfigurationManager configuration; + private MessageService messages; + private AdvancementManager advancementManager; + private RewardService rewardService; + private ConditionEngine conditionEngine; + private AdminGui adminGui; + + @Override public void onEnable() { + saveDefaultConfig(); + saveBundled("advancements.yml"); + saveBundled("messages.yml"); + try { + StrictYaml.read(new File(getDataFolder(), "config.yml").toPath(), false); + String icon = getConfig().getString("root.icon", "minecraft:nether_star"); + var material = org.bukkit.Material.matchMaterial(icon); + if (material == null || !material.isItem() || org.bukkit.NamespacedKey.fromString(getConfig().getString("root.background", "minecraft:textures/block/deepslate_tiles.png")) == null) + throw new IllegalArgumentException("根进度图标或背景非法"); + } catch (Exception error) { getLogger().severe("全局配置非法: " + error.getMessage()); getServer().getPluginManager().disablePlugin(this); return; } + String rootId = getConfig().getString("root.id", "root"); + if (!ConfigurationManager.validId(rootId)) { getLogger().severe("root.id 非法,插件已停止;请修复后正常重启"); getServer().getPluginManager().disablePlugin(this); return; } + try { + var catalog = BundledCatalogInstaller.install(this); + if (catalog.backup() != null) getLogger().info("趣味成就补入 " + catalog.added() + " 项,升级未修改模板 " + catalog.updated() + " 项,原配置备份: " + catalog.backup()); + } catch (Exception error) { + getLogger().severe("趣味成就安装失败,为保护配置插件将停用: " + error.getMessage()); + getServer().getPluginManager().disablePlugin(this); + return; + } + try { + database = new DatabaseManager(this); + database.open(); + } catch (Exception | LinkageError exception) { + getLogger().severe("SQLite 初始化失败,为保护数据插件将停用: " + exception.getMessage()); + getServer().getPluginManager().disablePlugin(this); + return; + } + messages = new MessageService(this); + configuration = new ConfigurationManager(this); + ConfigurationManager.LoadResult initial = configuration.load(); + configuration.applyValidSubset(initial); + logValidation(initial); + advancementManager = new AdvancementManager(this); + AdvancementManager.RegistrationResult registered = advancementManager.registerAll(configuration.definitions()); + registered.errors().forEach(error -> getLogger().severe("Advancement 注册错误: " + error)); + statistics = new StatisticsService(this, database); + statistics.start(); + rewardService = new RewardService(this, database, messages); + conditionEngine = new ConditionEngine(this, configuration, statistics, advancementManager, rewardService); + adminGui = new AdminGui(this, configuration, advancementManager, conditionEngine); + getServer().getPluginManager().registerEvents(new PlayerActivityListener(this, statistics, conditionEngine, advancementManager), this); + getServer().getPluginManager().registerEvents(adminGui, this); + IsaCommand command = new IsaCommand(this, configuration, messages); + PluginCommand isa = getCommand("isa"); + if (isa == null) throw new IllegalStateException("plugin.yml 未注册 isa 命令"); + isa.setExecutor(command); + isa.setTabCompleter(command); + Bukkit.getScheduler().runTaskTimer(this, () -> { + statistics.updateOnlineSessions(); + for (Player player : Bukkit.getOnlinePlayers()) { + conditionEngine.observeEnvironment(player); + conditionEngine.evaluate(player); + } + }, 200L, 200L); + getLogger().info("已启用:注册 " + registered.count() + " 个原版进度(含根进度),SQLite=" + database.databasePath()); + } + + private void saveBundled(String name) { + File file = new File(getDataFolder(), name); + if (!file.exists()) saveResource(name, false); + } + + public boolean reloadDefinitions(CommandSender sender) { + try { + var global = StrictYaml.read(new File(getDataFolder(), "config.yml").toPath(), false); + Map current = new java.util.HashMap<>(getConfig().getValues(true)); + Map next = new java.util.HashMap<>(global.getValues(true)); + current.values().removeIf(value -> value instanceof ConfigurationSection); + next.values().removeIf(value -> value instanceof ConfigurationSection); + if (!current.equals(next)) { messages.send(sender, "reload-restart-required"); return false; } + } catch (Exception error) { getLogger().severe("config.yml 校验失败: " + error.getMessage()); messages.send(sender, "reload-failed"); return false; } + messages.reload(); + ConfigurationManager.LoadResult candidate = configuration.load(); + if (!candidate.validation().valid()) { + logValidation(candidate); + messages.send(sender, "reload-failed"); + return false; + } + if (!candidate.definitions().equals(configuration.definitions())) { + messages.send(sender, "reload-restart-required"); + return false; + } + configuration.apply(candidate); + messages.send(sender, "reloaded", Map.of("count", configuration.definitions().size())); + return true; + } + + private void logValidation(ConfigurationManager.LoadResult result) { + result.validation().errors().forEach(error -> getLogger().severe(error)); + result.validation().warnings().stream().distinct().forEach(warning -> getLogger().warning(warning)); + if (!result.validation().valid()) getLogger().warning("无效成就已隔离;其余解析成功的定义将继续运行。请执行 /isa validate 查看。 "); + } + + @Override public void onDisable() { + if (rewardService != null) rewardService.close(); + try { if (statistics != null) statistics.close(); } + catch (Exception error) { getLogger().severe("关闭时统计刷盘失败,请保留数据目录: " + error.getMessage()); } + finally { + if (advancementManager != null) advancementManager.unregisterAll(); + if (database != null) { + try { database.close(); } + catch (SQLException exception) { getLogger().severe("关闭 SQLite 失败: " + exception.getMessage()); } + } + } + } + + public DatabaseManager database() { return database; } + public StatisticsService statistics() { return statistics; } + public AdvancementManager advancementManager() { return advancementManager; } + public ConditionEngine conditionEngine() { return conditionEngine; } + public AdminGui adminGui() { return adminGui; } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/advancement/AdvancementManager.java b/src/main/java/top/itxiaohui/serveradvancements/advancement/AdvancementManager.java new file mode 100644 index 0000000..066d50f --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/advancement/AdvancementManager.java @@ -0,0 +1,193 @@ +package top.itxiaohui.serveradvancements.advancement; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.advancement.Advancement; +import org.bukkit.advancement.AdvancementProgress; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import top.itxiaohui.serveradvancements.model.AchievementDefinition; + +import java.util.*; +import java.util.logging.Level; + +@SuppressWarnings("deprecation") +public final class AdvancementManager { + public static final String NAMESPACE = "itxiaohui_server_advancements"; + private static final String CRITERION = "completed"; + private final JavaPlugin plugin; + private final Set registered = new LinkedHashSet<>(); + private String rootId; + + public AdvancementManager(JavaPlugin plugin) { this.plugin = plugin; } + + public RegistrationResult registerAll(Map definitions) { + Map> completed = captureOnlineProgress(); + unregisterAll(); + rootId = plugin.getConfig().getString("root.id", "root"); + List errors = new ArrayList<>(); + tryLoad(key(rootId), rootJson(), errors); + for (AchievementDefinition definition : sorted(definitions)) { + if (!definition.enabled()) continue; + tryLoad(key(definition.id()), advancementJson(definition), errors); + } + Bukkit.getServer().updateResources(); + Bukkit.getScheduler().runTaskLater(plugin, () -> { + for (Player player : Bukkit.getOnlinePlayers()) { + ensureRoot(player); + for (String id : completed.getOrDefault(player.getUniqueId(), Set.of())) award(player, id); + } + }, 2L); + return new RegistrationResult(registered.size(), List.copyOf(errors)); + } + + private void tryLoad(NamespacedKey key, String json, List errors) { + try { + Advancement existing = Bukkit.getAdvancement(key); + if (existing != null) { + registered.add(key); + plugin.getLogger().warning("检测到启动前已存在的进度 " + key + ";沿用当前定义。若刚修改配置,请正常停止并再次启动服务器。"); + return; + } + Advancement loaded = Bukkit.getUnsafe().loadAdvancement(key, json); + if (loaded == null) errors.add(key + ": Paper 返回 null"); + else registered.add(key); + } catch (RuntimeException exception) { + errors.add(key + ": " + exception.getMessage()); + plugin.getLogger().log(Level.SEVERE, "注册原版进度失败: " + key, exception); + } + } + + private List sorted(Map definitions) { + List result = new ArrayList<>(); + Set added = new HashSet<>(); + while (result.size() < definitions.size()) { + boolean progressed = false; + List candidates = definitions.values().stream() + .filter(AchievementDefinition::enabled) + .filter(d -> !added.contains(d.id())) + .filter(d -> d.parent().equals("root") || added.contains(d.parent())) + .sorted(Comparator.comparingDouble(AchievementDefinition::x) + .thenComparingDouble(AchievementDefinition::y).thenComparing(AchievementDefinition::id)) + .toList(); + for (AchievementDefinition candidate : candidates) { + result.add(candidate); + added.add(candidate.id()); + progressed = true; + } + if (!progressed) break; + } + return result; + } + + private String rootJson() { + JsonObject root = baseJson(); + JsonObject display = new JsonObject(); + display.add("icon", icon(plugin.getConfig().getString("root.icon", "minecraft:nether_star"))); + display.addProperty("title", plugin.getConfig().getString("root.title", "服务器成就树")); + display.addProperty("description", plugin.getConfig().getString("root.description", "记录服务器冒险")); + display.addProperty("background", plugin.getConfig().getString("root.background", "minecraft:textures/block/deepslate_tiles.png")); + display.addProperty("frame", "task"); + display.addProperty("show_toast", false); + display.addProperty("announce_to_chat", false); + display.addProperty("hidden", false); + root.add("display", display); + return root.toString(); + } + + private String advancementJson(AchievementDefinition definition) { + JsonObject root = baseJson(); + root.addProperty("parent", NAMESPACE + ":" + (definition.parent().equals("root") ? rootId : definition.parent())); + JsonObject display = new JsonObject(); + display.add("icon", icon(definition.icon())); + display.addProperty("title", definition.name()); + display.addProperty("description", definition.description()); + display.addProperty("frame", definition.frame().name().toLowerCase(Locale.ROOT)); + display.addProperty("show_toast", definition.showToast()); + display.addProperty("announce_to_chat", definition.announceChat()); + display.addProperty("hidden", definition.hidden()); + root.add("display", display); + return root.toString(); + } + + private JsonObject baseJson() { + JsonObject root = new JsonObject(); + JsonObject criteria = new JsonObject(); + JsonObject impossible = new JsonObject(); + impossible.addProperty("trigger", "minecraft:impossible"); + criteria.add(CRITERION, impossible); + root.add("criteria", criteria); + JsonArray group = new JsonArray(); + group.add(CRITERION); + JsonArray requirements = new JsonArray(); + requirements.add(group); + root.add("requirements", requirements); + return root; + } + + private JsonObject icon(String materialName) { + Material material = Material.matchMaterial(materialName); + JsonObject icon = new JsonObject(); + icon.addProperty("id", material == null ? "minecraft:stone" : material.getKey().toString()); + return icon; + } + + private Map> captureOnlineProgress() { + Map> result = new HashMap<>(); + for (Player player : Bukkit.getOnlinePlayers()) { + Set ids = new HashSet<>(); + for (NamespacedKey key : registered) { + Advancement advancement = Bukkit.getAdvancement(key); + if (advancement != null && player.getAdvancementProgress(advancement).isDone()) ids.add(key.getKey()); + } + result.put(player.getUniqueId(), ids); + } + return result; + } + + public void unregisterAll() { + List reverse = new ArrayList<>(registered); + Collections.reverse(reverse); + for (NamespacedKey key : reverse) { + try { Bukkit.getUnsafe().removeAdvancement(key); } + catch (RuntimeException exception) { plugin.getLogger().warning("移除进度失败 " + key + ": " + exception.getMessage()); } + } + registered.clear(); + } + + public void ensureRoot(Player player) { + if (!plugin.getConfig().getBoolean("root.auto-grant", true)) return; + award(player, rootId == null ? plugin.getConfig().getString("root.id", "root") : rootId); + } + + public boolean award(Player player, String id) { + Advancement advancement = Bukkit.getAdvancement(key(id)); + if (advancement == null) return false; + AdvancementProgress progress = player.getAdvancementProgress(advancement); + boolean changed = false; + for (String criterion : progress.getRemainingCriteria()) changed |= progress.awardCriteria(criterion); + return changed; + } + + public boolean revoke(Player player, String id) { + if (id.equals(rootId)) return false; + Advancement advancement = Bukkit.getAdvancement(key(id)); + if (advancement == null) return false; + AdvancementProgress progress = player.getAdvancementProgress(advancement); + boolean changed = false; + for (String criterion : progress.getAwardedCriteria()) changed |= progress.revokeCriteria(criterion); + return changed; + } + + public boolean isDone(Player player, String id) { + Advancement advancement = Bukkit.getAdvancement(key(id)); + return advancement != null && player.getAdvancementProgress(advancement).isDone(); + } + + public NamespacedKey key(String id) { return new NamespacedKey(NAMESPACE, id); } + public int registeredCount() { return registered.size(); } + public record RegistrationResult(int count, List errors) { public boolean success() { return errors.isEmpty(); } } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/command/IsaCommand.java b/src/main/java/top/itxiaohui/serveradvancements/command/IsaCommand.java new file mode 100644 index 0000000..f34b43a --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/command/IsaCommand.java @@ -0,0 +1,242 @@ +package top.itxiaohui.serveradvancements.command; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.*; +import org.bukkit.entity.Player; +import top.itxiaohui.serveradvancements.ItxiaohuiServerAdvancements; +import top.itxiaohui.serveradvancements.config.ConfigurationManager; +import top.itxiaohui.serveradvancements.config.MessageService; +import top.itxiaohui.serveradvancements.database.DatabaseManager; +import top.itxiaohui.serveradvancements.gui.AdminGui; +import top.itxiaohui.serveradvancements.model.AchievementDefinition; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.*; +import java.util.stream.Stream; + +public final class IsaCommand implements TabExecutor { + private static final String ADMIN = "itxiaohui.serveradvancements.admin"; + private final ItxiaohuiServerAdvancements plugin; + private final ConfigurationManager configuration; + private final MessageService messages; + + public IsaCommand(ItxiaohuiServerAdvancements plugin, ConfigurationManager configuration, MessageService messages) { + this.plugin = plugin; + this.configuration = configuration; + this.messages = messages; + } + + @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (args.length == 0 || args[0].equalsIgnoreCase("help")) { help(sender); return true; } + String sub = args[0].toLowerCase(Locale.ROOT); + try { + return switch (sub) { + case "list" -> list(sender); + case "info" -> info(sender, args); + case "editor" -> editor(sender); + case "give" -> give(sender, args); + case "revoke" -> revoke(sender, args); + case "progress" -> progress(sender, args); + case "reload" -> reload(sender); + case "create" -> create(sender, args); + case "delete" -> delete(sender, args); + case "validate" -> validate(sender); + case "backup" -> backup(sender); + default -> { help(sender); yield true; } + }; + } catch (Exception exception) { + sender.sendMessage(Component.text("操作失败: " + exception.getMessage(), NamedTextColor.RED)); + plugin.getLogger().severe("命令 /isa " + String.join(" ", args) + " 失败: " + exception); + return true; + } + } + + private void help(CommandSender sender) { + sender.sendMessage(Component.text("服务器成就树命令", NamedTextColor.GOLD)); + sender.sendMessage(Component.text("/isa list | info | progress <玩家>", NamedTextColor.YELLOW)); + if (sender.hasPermission(ADMIN)) { + sender.sendMessage(Component.text("/isa editor | give/revoke <玩家> ", NamedTextColor.YELLOW)); + sender.sendMessage(Component.text("/isa create/delete | reload | validate | backup", NamedTextColor.YELLOW)); + } + } + + private boolean list(CommandSender sender) { + sender.sendMessage(Component.text("已配置成就(" + configuration.definitions().size() + ")", NamedTextColor.GOLD)); + configuration.definitions().values().forEach(definition -> sender.sendMessage(Component.text( + "- " + definition.id() + ":" + definition.name() + (definition.enabled() ? "" : " [禁用]"), + definition.enabled() ? NamedTextColor.YELLOW : NamedTextColor.GRAY))); + return true; + } + + private boolean info(CommandSender sender, String[] args) { + if (args.length < 2) return usage(sender, "/isa info "); + AchievementDefinition definition = configuration.get(args[1]); + if (definition == null) { messages.send(sender, "unknown-achievement", Map.of("id", args[1])); return true; } + sender.sendMessage(Component.text(definition.name() + " (" + definition.id() + ")", NamedTextColor.GOLD)); + sender.sendMessage(Component.text(definition.description(), NamedTextColor.GRAY)); + sender.sendMessage(Component.text("父级=" + definition.parent() + " 类型=" + definition.frame().name().toLowerCase() + + " 条件=" + definition.conditions().size() + " 启用=" + definition.enabled(), NamedTextColor.YELLOW)); + return true; + } + + private boolean editor(CommandSender sender) { + if (!require(sender, ADMIN)) return true; + if (!(sender instanceof Player player)) { messages.send(sender, "player-only"); return true; } + plugin.adminGui().open(player, 0); + return true; + } + + private boolean give(CommandSender sender, String[] args) { + if (!require(sender, "itxiaohui.serveradvancements.give")) return true; + if (args.length < 3) return usage(sender, "/isa give <在线玩家> "); + Player target = findOnline(args[1]); + if (target == null) { messages.send(sender, "invalid-player", Map.of("player", args[1])); return true; } + AchievementDefinition definition = configuration.get(args[2]); + if (definition == null) { messages.send(sender, "unknown-achievement", Map.of("id", args[2])); return true; } + plugin.advancementManager().ensureRoot(target); + plugin.conditionEngine().completeAsync(target, definition).whenComplete((outcome, error) -> { + if (!plugin.isEnabled()) return; + Bukkit.getScheduler().runTask(plugin, () -> { + if (error != null) { sender.sendMessage(Component.text("授予失败,可稍后重试: " + error.getMessage(), NamedTextColor.RED)); return; } + switch (outcome) { + case COMPLETED, RESTORED_WITHOUT_REWARD -> messages.send(sender, "granted", Map.of("player", target.getName(), "id", definition.id())); + case ALREADY_COMPLETE, IN_FLIGHT -> messages.send(sender, "already-completed", Map.of("player", target.getName(), "id", definition.id())); + case REVIEW_REQUIRED -> sender.sendMessage(Component.text("奖励存在 PENDING/FAILED 记录,需要管理员核查,未重复发奖。", NamedTextColor.RED)); + case RETRY_LATER -> sender.sendMessage(Component.text("玩家数据尚未就绪、成就禁用或数据库暂不可用,未授予,可稍后重试。", NamedTextColor.YELLOW)); + } + }); + }); + plugin.database().auditAsync(sender.getName(), "GIVE_REQUEST", target.getUniqueId().toString(), definition.id()); + return true; + } + + private boolean revoke(CommandSender sender, String[] args) { + if (!require(sender, "itxiaohui.serveradvancements.revoke")) return true; + if (args.length < 3) return usage(sender, "/isa revoke <在线玩家> "); + Player target = findOnline(args[1]); + if (target == null) { messages.send(sender, "invalid-player", Map.of("player", args[1])); return true; } + AchievementDefinition definition = configuration.get(args[2]); + if (definition == null) { messages.send(sender, "unknown-achievement", Map.of("id", args[2])); return true; } + plugin.advancementManager().revoke(target, definition.id()); + plugin.database().auditAsync(sender.getName(), "REVOKE", target.getUniqueId().toString(), definition.id()); + messages.send(sender, "revoked", Map.of("player", target.getName(), "id", definition.id())); + return true; + } + + private boolean progress(CommandSender sender, String[] args) { + if (!require(sender, "itxiaohui.serveradvancements.view")) return true; + if (args.length < 2) return usage(sender, "/isa progress <在线玩家>"); + Player target = findOnline(args[1]); + if (target == null) { messages.send(sender, "invalid-player", Map.of("player", args[1])); return true; } + long done = configuration.definitions().keySet().stream().filter(id -> plugin.advancementManager().isDone(target, id)).count(); + sender.sendMessage(Component.text(target.getName() + ":完成 " + done + "/" + configuration.definitions().size(), NamedTextColor.GOLD)); + Map stats = plugin.statistics().snapshot(target.getUniqueId()); + stats.entrySet().stream().sorted(Map.Entry.comparingByKey()).limit(30).forEach(entry -> + sender.sendMessage(Component.text("- " + entry.getKey() + " = " + String.format(Locale.ROOT, "%.2f", entry.getValue()), NamedTextColor.GRAY))); + return true; + } + + private boolean reload(CommandSender sender) { + if (!require(sender, ADMIN)) return true; + plugin.reloadDefinitions(sender); + plugin.database().auditAsync(sender.getName(), "RELOAD", null, null); + return true; + } + + private boolean create(CommandSender sender, String[] args) throws IOException { + if (!require(sender, ADMIN)) return true; + if (args.length < 2) return usage(sender, "/isa create "); + if (!configuration.createSkeleton(args[1])) { + sender.sendMessage(Component.text("ID 非法、已存在或使用了保留 ID root。", NamedTextColor.RED)); + return true; + } + plugin.database().auditAsync(sender.getName(), "CREATE", args[1], null); + messages.send(sender, "created", Map.of("id", args[1])); + return true; + } + + private boolean delete(CommandSender sender, String[] args) throws IOException { + if (!require(sender, ADMIN)) return true; + if (args.length < 2) return usage(sender, "/isa delete confirm"); + if (args.length < 3 || !args[2].equalsIgnoreCase("confirm")) { + messages.send(sender, "delete-confirm", Map.of("id", args[1])); return true; + } + ConfigurationManager.DeleteResult result = configuration.delete(args[1]); + if (!result.success()) sender.sendMessage(Component.text("无法删除: " + result.reason(), NamedTextColor.RED)); + else { + plugin.database().auditAsync(sender.getName(), "DELETE", args[1], "配置已删除,原版玩家进度未批量清理"); + messages.send(sender, "deleted", Map.of("id", args[1])); + } + return true; + } + + private boolean validate(CommandSender sender) { + if (!require(sender, ADMIN)) return true; + ConfigurationManager.LoadResult result = configuration.load(); + result.validation().errors().forEach(error -> sender.sendMessage(Component.text("错误: " + error, NamedTextColor.RED))); + result.validation().warnings().forEach(warning -> sender.sendMessage(Component.text("警告: " + warning, NamedTextColor.YELLOW))); + if (result.validation().valid()) messages.send(sender, "validation-ok", Map.of("count", result.definitions().size())); + return true; + } + + private boolean backup(CommandSender sender) throws Exception { + if (!require(sender, ADMIN)) return true; + plugin.statistics().updateOnlineSessions(); + plugin.statistics().flushAllAsync().thenCompose(ignored -> plugin.database().submit(() -> plugin.database().backup())) + .whenComplete((path, error) -> { + if (!plugin.isEnabled()) return; + Bukkit.getScheduler().runTask(plugin, () -> { + if (error != null) sender.sendMessage(Component.text("备份失败: " + error.getMessage(), NamedTextColor.RED)); + else messages.send(sender, "backup-created", Map.of("path", path.toAbsolutePath())); + }); + }); + return true; + } + + private Player findOnline(String input) { + try { return Bukkit.getPlayer(UUID.fromString(input)); } + catch (IllegalArgumentException ignored) { return Bukkit.getPlayerExact(input); } + } + + private boolean require(CommandSender sender, String permission) { + if (sender.hasPermission(permission)) return true; + messages.send(sender, "no-permission"); + return false; + } + + private boolean usage(CommandSender sender, String usage) { + sender.sendMessage(Component.text("用法: " + usage, NamedTextColor.RED)); + return true; + } + + @Override public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { + if (args.length == 0) return List.of(); + if (args.length == 1) return filter(List.of("help", "list", "info", "editor", "give", "revoke", "progress", "reload", "create", "delete", "validate", "backup").stream().filter(sub -> allowed(sender, sub)).toList(), args[0]); + if (!allowed(sender, args[0].toLowerCase(Locale.ROOT))) return List.of(); + if (args.length == 2 && Set.of("give", "revoke", "progress").contains(args[0].toLowerCase())) + return filter(Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(), args[1]); + if ((args.length == 2 && Set.of("info", "delete").contains(args[0].toLowerCase())) || + (args.length == 3 && Set.of("give", "revoke").contains(args[0].toLowerCase()))) + return filter(new ArrayList<>(configuration.definitions().keySet()), args[args.length - 1]); + if (args.length == 3 && args[0].equalsIgnoreCase("delete")) return filter(List.of("confirm"), args[2]); + return List.of(); + } + + private boolean allowed(CommandSender sender, String sub) { + return switch (sub) { + case "help", "list", "info" -> true; + case "give", "revoke" -> sender.hasPermission("itxiaohui.serveradvancements." + sub); + case "progress" -> sender.hasPermission("itxiaohui.serveradvancements.view"); + default -> sender.hasPermission(ADMIN); + }; + } + + private List filter(List values, String prefix) { + String lower = prefix.toLowerCase(Locale.ROOT); + return values.stream().filter(value -> value.toLowerCase(Locale.ROOT).startsWith(lower)).sorted().toList(); + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/condition/AutomaticConditions.java b/src/main/java/top/itxiaohui/serveradvancements/condition/AutomaticConditions.java new file mode 100644 index 0000000..e6344da --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/condition/AutomaticConditions.java @@ -0,0 +1,133 @@ +package top.itxiaohui.serveradvancements.condition; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Statistic; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import top.itxiaohui.serveradvancements.model.ConditionDefinition; +import top.itxiaohui.serveradvancements.statistics.StatisticsService; + +import java.util.*; + +/** Read-only native state and persisted server observations. No AI/network calls. */ +public final class AutomaticConditions { + public static final Set EVENTS = Set.of("eat_food", "cook_food", "tame_animal", "fish_item", "place_block"); + private AutomaticConditions() { } + + public static List strings(ConditionDefinition condition, String key) { + Object value = condition.parameters().get(key); + if (!(value instanceof List list)) return List.of(); + return list.stream().map(String::valueOf).toList(); + } + + public static List validate(ConditionDefinition c) { + List errors = new ArrayList<>(); + for (String key : List.of("materials", "items", "structures", "subjects")) { + Object value = c.parameters().get(key); + if (value != null && (!(value instanceof List list) || list.stream().anyMatch(item -> !(item instanceof String)))) + errors.add(key + " 必须是字符串列表"); + } + switch (c.type()) { + case PLAYER_STATISTIC -> { + try { + Statistic statistic = Statistic.valueOf(c.string("statistic", "")); + var materials = strings(c, "materials"); + switch (statistic.getType()) { + case UNTYPED -> { if (!materials.isEmpty() || c.parameters().containsKey("entity")) errors.add("无类型统计不能指定物品或生物"); } + case ITEM, BLOCK -> { + validateMaterials(materials, errors, statistic.isBlock()); + if (c.parameters().containsKey("entity")) errors.add("物品统计不能指定 entity"); + } + case ENTITY -> { + EntityType type = entity(c.string("entity", "")); + if (type == null || !type.isAlive() || !materials.isEmpty()) errors.add("原版统计生物无效"); + } + } + } catch (IllegalArgumentException error) { errors.add("原版统计名称无效"); } + } + case VANILLA_ADVANCEMENT -> { + NamespacedKey key = NamespacedKey.fromString(c.string("advancement", "")); + if (key == null || !key.getNamespace().equals("minecraft") || !key.getKey().contains("/")) errors.add("只允许 minecraft 原版进度键"); + } + case INVENTORY_SET -> { + var items = strings(c, "items"); + validateMaterials(items, errors, false); + if (c.target() != Math.rint(c.target()) || c.target() > items.size()) errors.add("收藏种类数超过物品列表或非整数"); + double each = c.number("each", 1); + if (!Double.isFinite(each) || each < 1 || each > 4096 || each != Math.rint(each)) errors.add("收藏单种数量必须是 1–4096 整数"); + } + case VISIT_BIOME -> { if (!validMinecraftKey(c.string("biome", ""))) errors.add("生物群系键无效"); } + case VISIT_STRUCTURE -> { + var structures = strings(c, "structures"); + if (structures.isEmpty() || structures.size() > 32 || structures.stream().anyMatch(s -> !validMinecraftKey(s))) errors.add("结构列表无效"); + } + case EVENT_COUNT, EVENT_DISTINCT -> { + if (!EVENTS.contains(c.string("event", ""))) errors.add("自动事件名称无效"); + var subjects = strings(c, "subjects"); + if (subjects.size() > 64 || subjects.stream().anyMatch(s -> !validMinecraftKey(s))) errors.add("事件对象列表无效"); + if (!subjects.isEmpty() && c.type() == top.itxiaohui.serveradvancements.model.ConditionType.EVENT_DISTINCT && c.target() > new HashSet<>(subjects).size()) errors.add("不同种类目标大于对象列表"); + } + default -> { } + } + return errors; + } + + private static boolean validMinecraftKey(String value) { + NamespacedKey key = NamespacedKey.fromString(value); + return key != null && key.getNamespace().equals("minecraft"); + } + + private static EntityType entity(String key) { + return Arrays.stream(EntityType.values()).filter(type -> type.isAlive() && type.getKey().toString().equals(key)).findFirst().orElse(null); + } + + private static void validateMaterials(List values, List errors, boolean block) { + if (values.isEmpty() || values.size() > 64 || new HashSet<>(values).size() != values.size()) errors.add("物品列表必须有 1–64 个不同对象"); + for (String value : values) { + Material material = Material.matchMaterial(value); + if (!validMinecraftKey(value) || material == null || (block ? !material.isBlock() : !material.isItem())) errors.add("物品/方块无效: " + value); + } + } + + public static double current(Player player, ConditionDefinition c, StatisticsService statistics) { + return switch (c.type()) { + case PLAYER_STATISTIC -> nativeStatistic(player, c); + case VANILLA_ADVANCEMENT -> { + var advancement = Bukkit.getAdvancement(NamespacedKey.fromString(c.string("advancement", ""))); + yield advancement != null && player.getAdvancementProgress(advancement).isDone() ? 1 : 0; + } + case INVENTORY_SET -> { + Map counts = new HashMap<>(); + for (ItemStack item : player.getInventory().getContents()) if (item != null && !item.getType().isAir()) + counts.merge(item.getType().getKey().toString(), item.getAmount(), Integer::sum); + yield strings(c, "items").stream().filter(item -> counts.getOrDefault(item, 0) >= c.number("each", 1)).count(); + } + case VISIT_STRUCTURE -> { + var structures = strings(c, "structures"); + yield statistics.snapshot(player.getUniqueId()).entrySet().stream() + .filter(e -> e.getValue() > 0 && structures.stream().anyMatch(s -> e.getKey().startsWith("structure:" + s + ":"))).count(); + } + case EVENT_COUNT, EVENT_DISTINCT -> { + String prefix = "event:" + c.string("event", "") + ":"; + var subjects = strings(c, "subjects"); + var entries = statistics.snapshot(player.getUniqueId()).entrySet().stream() + .filter(e -> e.getKey().startsWith(prefix) && (subjects.isEmpty() || subjects.contains(e.getKey().substring(prefix.length())))); + yield c.type() == top.itxiaohui.serveradvancements.model.ConditionType.EVENT_DISTINCT + ? entries.filter(e -> e.getValue() > 0).count() : entries.mapToDouble(Map.Entry::getValue).sum(); + } + default -> statistics.get(player.getUniqueId(), c.statisticKey()); + }; + } + + private static double nativeStatistic(Player player, ConditionDefinition c) { + Statistic statistic = Statistic.valueOf(c.string("statistic", "")); + return switch (statistic.getType()) { + case UNTYPED -> player.getStatistic(statistic); + case ITEM, BLOCK -> strings(c, "materials").stream().mapToDouble(m -> player.getStatistic(statistic, Material.matchMaterial(m))).sum(); + case ENTITY -> player.getStatistic(statistic, entity(c.string("entity", ""))); + }; + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/condition/ConditionEngine.java b/src/main/java/top/itxiaohui/serveradvancements/condition/ConditionEngine.java new file mode 100644 index 0000000..8cdf2f2 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/condition/ConditionEngine.java @@ -0,0 +1,168 @@ +package top.itxiaohui.serveradvancements.condition; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import top.itxiaohui.serveradvancements.advancement.AdvancementManager; +import top.itxiaohui.serveradvancements.config.ConfigurationManager; +import top.itxiaohui.serveradvancements.model.*; +import top.itxiaohui.serveradvancements.reward.RewardService; +import top.itxiaohui.serveradvancements.statistics.StatisticsService; + +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public final class ConditionEngine { + private final JavaPlugin plugin; + private final ConfigurationManager configuration; + private final StatisticsService statistics; + private final AdvancementManager advancements; + private final RewardService rewards; + private long indexedRevision = Long.MIN_VALUE; + private final Map> byStatistic = new HashMap<>(); + private final List regions = new ArrayList<>(); + + public ConditionEngine(JavaPlugin plugin, ConfigurationManager configuration, StatisticsService statistics, + AdvancementManager advancements, RewardService rewards) { + this.plugin = plugin; + this.configuration = configuration; + this.statistics = statistics; + this.advancements = advancements; + this.rewards = rewards; + } + + public void record(Player player, ConditionType type, String discriminator, double amount) { + if (type == ConditionType.KILL_MOB || type == ConditionType.BREED_MOB) { + statistics.increment(player.getUniqueId(), key(type, "*"), amount); + } + statistics.increment(player.getUniqueId(), key(type, discriminator), amount); + evaluateAffected(player, key(type, discriminator), type == ConditionType.KILL_MOB || type == ConditionType.BREED_MOB ? key(type, "*") : ""); + } + + public void mark(Player player, ConditionType type, String discriminator) { + statistics.setMax(player.getUniqueId(), key(type, discriminator), 1); + evaluateAffected(player, key(type, discriminator), ""); + } + + public void setLevel(Player player, int level) { + statistics.setMax(player.getUniqueId(), "experience_level", level); + evaluateAffected(player, "experience_level", ""); + } + + public void event(Player player, String event, String subject, int amount) { + if (amount <= 0 || !AutomaticConditions.EVENTS.contains(event)) return; + statistics.increment(player.getUniqueId(), "event:" + event + ":" + subject, amount); + evaluateAffected(player, "event:" + event, ""); + } + + /** Called by the low-frequency main-thread sampler, not on every movement packet. */ + public void observeEnvironment(Player player) { + if (!statistics.isReady(player.getUniqueId())) return; + Location location = player.getLocation(); + statistics.setMax(player.getUniqueId(), "altitude", Math.max(0, location.getY())); + statistics.setMax(player.getUniqueId(), "visit_biome:" + location.getBlock().getBiome().getKey(), 1); + var world = location.getWorld(); + int x = location.getBlockX() >> 4, z = location.getBlockZ() >> 4; + if (!world.isChunkLoaded(x, z)) return; + for (var structure : world.getStructures(x, z)) { + var bounds = structure.getBoundingBox(); + if (!bounds.clone().expand(1, 2, 1).contains(location.toVector())) continue; + String identity = structure.getStructure().getKey() + ":" + world.getUID() + ":" + + (int) bounds.getMinX() + "," + (int) bounds.getMinY() + "," + (int) bounds.getMinZ(); + statistics.setMax(player.getUniqueId(), "structure:" + identity, 1); + } + } + + public void evaluate(Player player) { + if (!statistics.isReady(player.getUniqueId())) return; + for (AchievementDefinition definition : configuration.definitions().values()) evaluateOne(player, definition); + } + + private void evaluateOne(Player player, AchievementDefinition definition) { + if (definition.enabled() && !advancements.isDone(player, definition.id()) && !rewards.isInFlight(player.getUniqueId(), definition.id()) && satisfied(player, definition)) complete(player, definition); + } + + private void evaluateAffected(Player player, String key, String wildcard) { + if (!statistics.isReady(player.getUniqueId())) return; + if (indexedRevision != configuration.revision()) { + byStatistic.clear(); regions.clear(); + for (AchievementDefinition definition : configuration.definitions().values()) { + for (ConditionDefinition condition : definition.conditions()) { + byStatistic.computeIfAbsent(condition.statisticKey(), ignored -> new ArrayList<>()).add(definition); + if (condition.type() == ConditionType.REACH_LOCATION && !regions.contains(definition)) regions.add(definition); + } + } + indexedRevision = configuration.revision(); + } + Set affected = new LinkedHashSet<>(byStatistic.getOrDefault(key, List.of())); + affected.addAll(byStatistic.getOrDefault(wildcard, List.of())); + if (key.equals("move_distance")) affected.addAll(regions); + for (AchievementDefinition definition : affected) evaluateOne(player, definition); + } + + public boolean complete(Player player, AchievementDefinition definition) { + if (!definition.enabled() || !statistics.isReady(player.getUniqueId()) || advancements.isDone(player, definition.id()) || rewards.isInFlight(player.getUniqueId(), definition.id())) return false; + completeAsync(player, definition); + return true; + } + + public CompletableFuture completeAsync(Player player, AchievementDefinition definition) { + if (!definition.enabled() || !statistics.isReady(player.getUniqueId())) return CompletableFuture.completedFuture(RewardService.Outcome.RETRY_LATER); + if (advancements.isDone(player, definition.id())) return CompletableFuture.completedFuture(RewardService.Outcome.ALREADY_COMPLETE); + return rewards.complete(player, definition, () -> advancements.award(player, definition.id()), + () -> { + statistics.setMax(player.getUniqueId(), "achievement:" + definition.id(), 1); + if (plugin.isEnabled()) plugin.getServer().getScheduler().runTask(plugin, () -> { if (player.isOnline()) evaluate(player); }); + }); + } + + private boolean satisfied(Player player, AchievementDefinition definition) { + for (ConditionDefinition condition : definition.conditions()) { + if (!Double.isFinite(condition.target()) || condition.target() <= 0) return false; + if (condition.type() == ConditionType.MANUAL) return false; + if (condition.type() == ConditionType.REACH_LOCATION) { + if (statistics.get(player.getUniqueId(), condition.statisticKey()) < 1) { + if (!reached(player.getLocation(), condition)) return false; + statistics.setMax(player.getUniqueId(), condition.statisticKey(), 1); + } + } else if (condition.type() == ConditionType.COMPLETE_ACHIEVEMENT) { + if (!advancements.isDone(player, condition.string("achievement", ""))) return false; + } else if (AutomaticConditions.current(player, condition, statistics) < condition.target()) return false; + } + return true; + } + + private boolean reached(Location location, ConditionDefinition condition) { + if (!location.getWorld().getKey().toString().equalsIgnoreCase(condition.string("world", location.getWorld().getKey().toString())) + && !location.getWorld().getName().equalsIgnoreCase(condition.string("world", location.getWorld().getName()))) return false; + double x = condition.number("x", location.getX()); + double y = condition.number("y", location.getY()); + double z = condition.number("z", location.getZ()); + double radius = condition.number("radius", 5); + double dx = location.getX() - x, dy = location.getY() - y, dz = location.getZ() - z; + return dx * dx + dy * dy + dz * dz <= radius * radius; + } + + private String key(ConditionType type, String discriminator) { + return switch (type) { + case FIRST_JOIN -> "first_join"; + case ONLINE_TIME -> "online_time_ms"; + case MINE_BLOCK -> "mine_block:" + discriminator; + case COLLECT_ITEM -> "collect_item:" + discriminator; + case OBTAIN_ITEM -> "obtain_item:" + discriminator; + case KILL_MOB -> "kill_mob:" + discriminator; + case VISIT_DIMENSION -> "visit_dimension:" + discriminator; + case MOVE_DISTANCE -> "move_distance"; + case REACH_LOCATION -> "reach_location:" + discriminator; + case CRAFT_ITEM -> "craft_item:" + discriminator; + case BREED_MOB -> "breed_mob:" + discriminator; + case EXPERIENCE_LEVEL -> "experience_level"; + case COMPLETE_ACHIEVEMENT -> "achievement:" + discriminator; + case MANUAL -> "manual"; + case VISIT_BIOME -> "visit_biome:" + discriminator; + case ALTITUDE -> "altitude"; + case EVENT_COUNT, EVENT_DISTINCT -> "event:" + discriminator; + case PLAYER_STATISTIC, VANILLA_ADVANCEMENT, INVENTORY_SET, VISIT_STRUCTURE -> throw new IllegalArgumentException("该条件使用原版状态或环境采样,不接受直接累计: " + type); + }; + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/config/BundledCatalogInstaller.java b/src/main/java/top/itxiaohui/serveradvancements/config/BundledCatalogInstaller.java new file mode 100644 index 0000000..227902c --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/config/BundledCatalogInstaller.java @@ -0,0 +1,94 @@ +package top.itxiaohui.serveradvancements.config; + +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.Map; +import java.util.HashMap; + +/** One-time, additive catalog upgrade. Never replaces an administrator's existing ID. */ +public final class BundledCatalogInstaller { + private static final String MARKER = "bundled-fun-catalog-version"; + + private BundledCatalogInstaller() { } + + public static Result install(JavaPlugin plugin) throws IOException { + try (var resource = plugin.getResource("fun-advancements.yml")) { + if (resource == null) throw new IOException("JAR 缺少 fun-advancements.yml"); + var catalog = StrictYaml.parse(new String(resource.readAllBytes(), StandardCharsets.UTF_8), true); + return install(plugin.getDataFolder().toPath().resolve("advancements.yml"), catalog); + } + } + + public static Result install(Path target, YamlConfiguration catalog) throws IOException { + YamlConfiguration previous = new YamlConfiguration(); + if (catalog.getInt("catalog-version", 0) > 1) { + try (var resource = BundledCatalogInstaller.class.getClassLoader().getResourceAsStream("fun-advancements-v1.yml")) { + if (resource == null) throw new IOException("缺少旧版目录,拒绝不安全升级"); + previous = StrictYaml.parse(new String(resource.readAllBytes(), StandardCharsets.UTF_8), true); + } + } + return install(target, catalog, previous); + } + + public static Result install(Path target, YamlConfiguration catalog, YamlConfiguration previous) throws IOException { + int version = catalog.getInt("catalog-version", 0); + ConfigurationSection additions = catalog.getConfigurationSection("achievements"); + if (version < 1 || additions == null) throw new IOException("内置趣味成就目录无效"); + YamlConfiguration current = StrictYaml.read(target, true); + int installed = current.getInt(MARKER, 0); + if (installed >= version) return new Result(0, 0, null); + if (current.contains("achievements") && !current.isConfigurationSection("achievements")) + throw new IOException("现有 achievements 不是配置节,拒绝覆盖"); + ConfigurationSection destination = current.getConfigurationSection("achievements"); + if (destination == null) destination = current.createSection("achievements"); + int added = 0, updated = 0; + ConfigurationSection oldEntries = previous.getConfigurationSection("achievements"); + for (String id : additions.getKeys(false)) { + ConfigurationSection node = additions.getConfigurationSection(id); + if (!ConfigurationManager.validId(id) || node == null) throw new IOException("内置成就无效: " + id); + if (!destination.contains(id)) { + // A previously installed ID removed by the administrator stays removed. + if (installed > 0 && oldEntries != null && oldEntries.contains(id)) continue; + copy(node, destination.createSection(id)); + added++; + } else if (installed == 1 && oldEntries != null && oldEntries.isConfigurationSection(id) + && destination.isConfigurationSection(id) + && leaves(destination.getConfigurationSection(id)).equals(leaves(oldEntries.getConfigurationSection(id)))) { + destination.set(id, null); + copy(node, destination.createSection(id)); + updated++; + } + } + current.set(MARKER, version); + Path backup = null; + if (Files.exists(target)) { + backup = target.resolveSibling("advancements-before-fun-" + UUID.randomUUID() + ".yml.bak"); + Files.copy(target, backup); + } + StrictYaml.save(current, target); + return new Result(added, updated, backup); + } + + private static Map leaves(ConfigurationSection section) { + Map values = new HashMap<>(section.getValues(true)); + values.values().removeIf(value -> value instanceof ConfigurationSection); + return values; + } + + private static void copy(ConfigurationSection source, ConfigurationSection destination) { + for (String key : source.getKeys(false)) { + ConfigurationSection child = source.getConfigurationSection(key); + if (child == null) destination.set(key, source.get(key)); + else copy(child, destination.createSection(key)); + } + } + + public record Result(int added, int updated, Path backup) { } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/config/ConfigurationManager.java b/src/main/java/top/itxiaohui/serveradvancements/config/ConfigurationManager.java new file mode 100644 index 0000000..5f48de1 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/config/ConfigurationManager.java @@ -0,0 +1,241 @@ +package top.itxiaohui.serveradvancements.config; + +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; +import top.itxiaohui.serveradvancements.model.*; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.regex.Pattern; +import org.bukkit.entity.EntityType; + +public final class ConfigurationManager { + private static final Pattern ID_PATTERN = Pattern.compile("[a-z0-9._/-]+"); + private final JavaPlugin plugin; + private LinkedHashMap definitions = new LinkedHashMap<>(); + private ValidationResult lastValidation = new ValidationResult(List.of(), List.of()); + private long revision; + + public ConfigurationManager(JavaPlugin plugin) { this.plugin = plugin; } + + public LoadResult load() { + File file = new File(plugin.getDataFolder(), "advancements.yml"); + LinkedHashMap loaded = new LinkedHashMap<>(); + List errors = new ArrayList<>(); + List warnings = new ArrayList<>(); + YamlConfiguration yaml; + try { yaml = StrictYaml.read(file.toPath(), true); } + catch (IOException error) { return new LoadResult(loaded, new ValidationResult(List.of(error.getMessage()), List.of())); } + ConfigurationSection root = yaml.getConfigurationSection("achievements"); + if (root == null) { + errors.add("advancements.yml: 缺少 achievements 节点"); + return new LoadResult(loaded, new ValidationResult(errors, warnings)); + } + for (String id : root.getKeys(false)) { + ConfigurationSection section = root.getConfigurationSection(id); + if (section == null) continue; + try { + AchievementDefinition definition = parse(id, section); + List localErrors = validateOne(definition); + if (localErrors.isEmpty()) loaded.put(id, definition); + else localErrors.forEach(error -> errors.add("advancements.yml 成就 " + id + ": " + error)); + } catch (RuntimeException exception) { + errors.add("advancements.yml 成就 " + id + ": " + exception.getMessage()); + } + } + validateGraph(loaded, errors); + if (loaded.values().stream().anyMatch(definition -> definition.x() != 0 || definition.y() != 0)) + warnings.add("display.x/y 仅作为定义排序提示;原版客户端自动计算节点坐标"); + ValidationResult result = new ValidationResult(List.copyOf(errors), List.copyOf(warnings)); + return new LoadResult(loaded, result); + } + + public boolean apply(LoadResult result) { + lastValidation = result.validation(); + if (!result.validation().valid()) return false; + definitions = result.definitions(); + revision++; + return true; + } + + public void applyValidSubset(LoadResult result) { + lastValidation = result.validation(); + definitions = result.definitions(); + revision++; + } + + private AchievementDefinition parse(String id, ConfigurationSection section) { + List conditions = new ArrayList<>(); + for (Map raw : section.getMapList("conditions")) { + Map values = new LinkedHashMap<>(); + raw.forEach((key, value) -> values.put(String.valueOf(key), value)); + String type = String.valueOf(values.remove("type")); + conditions.add(new ConditionDefinition(ConditionType.parse(type), values)); + } + ConfigurationSection reward = section.getConfigurationSection("rewards"); + List items = new ArrayList<>(); + if (reward != null) { + for (Map raw : reward.getMapList("items")) { + items.add(new RewardDefinition.RewardItem(String.valueOf(raw.get("item")), strictInt(raw.get("amount"), 1))); + } + } + RewardDefinition rewards = new RewardDefinition( + reward == null ? 0 : strictInt(reward.get("experience"), 0), + List.copyOf(items), reward == null ? List.of() : List.copyOf(reward.getStringList("commands")), + reward != null && reward.getBoolean("allow-reclaim", plugin.getConfig().getBoolean("defaults.allow-reward-reclaim", false)), + reward == null ? "" : reward.getString("completion-message", "")); + ConfigurationSection display = section.getConfigurationSection("display"); + return new AchievementDefinition(id, section.getString("name", id), section.getString("description", ""), + section.getString("icon", "minecraft:stone"), AdvancementFrame.parse(section.getString("frame", "task")), + section.getString("parent", "root").equals(rootId()) ? "root" : section.getString("parent", "root"), display == null ? 0 : display.getDouble("x"), + display == null ? 0 : display.getDouble("y"), List.copyOf(conditions), + section.getBoolean("hidden", false), + section.getBoolean("show-toast", plugin.getConfig().getBoolean("defaults.show-toast", true)), + section.getBoolean("announce-chat", plugin.getConfig().getBoolean("defaults.announce-chat", false)), + section.getBoolean("enabled", true), rewards); + } + + private int strictInt(Object value, int fallback) { + if (value == null) return fallback; + if (!(value instanceof Number number) || !Double.isFinite(number.doubleValue()) || number.doubleValue() != number.intValue()) + throw new IllegalArgumentException("整数配置非法: " + value); + return number.intValue(); + } + + public String rootId() { return plugin.getConfig().getString("root.id", "root"); } + public long revision() { return revision; } + public static boolean validId(String id) { + return id != null && id.length() <= 128 && ID_PATTERN.matcher(id).matches() + && Arrays.stream(id.split("/", -1)).noneMatch(part -> part.isEmpty() || part.equals(".") || part.equals("..")); + } + + private List validateOne(AchievementDefinition definition) { + List errors = new ArrayList<>(); + if (!validId(definition.id()) || definition.id().equals("root") || definition.id().equals(rootId())) + errors.add("ID 非法,只允许小写字母、数字、._/-"); + Material icon = Material.matchMaterial(definition.icon()); + if (NamespacedKey.fromString(definition.icon()) == null || icon == null || !icon.isItem()) errors.add("图标不是有效物品: " + definition.icon()); + if (definition.conditions().isEmpty()) errors.add("至少需要一个条件"); + if (definition.conditions().size() > 64 || definition.name().length() > 256 || definition.description().length() > 2048 + || !Double.isFinite(definition.x()) || !Double.isFinite(definition.y())) errors.add("条件数量、显示文字长度或坐标非法"); + for (ConditionDefinition condition : definition.conditions()) { + errors.addAll(top.itxiaohui.serveradvancements.condition.AutomaticConditions.validate(condition)); + if (!Double.isFinite(condition.target()) || condition.target() <= 0) errors.add("条件 " + condition.type() + " 的目标必须为正有限数且单位有效"); + String materialKey = switch (condition.type()) { + case MINE_BLOCK -> condition.string("block", ""); + case COLLECT_ITEM, OBTAIN_ITEM, CRAFT_ITEM -> condition.string("item", ""); + default -> null; + }; + if (materialKey != null) { + Material material = Material.matchMaterial(materialKey); + if (NamespacedKey.fromString(materialKey) == null || material == null + || (condition.type() == ConditionType.MINE_BLOCK ? !material.isBlock() : !material.isItem())) + errors.add("条件 " + condition.type() + " 的物品/方块无效: " + materialKey); + } + if (condition.type() == ConditionType.KILL_MOB || condition.type() == ConditionType.BREED_MOB) { + String entity = condition.string("entity", ""); + if (!entity.equals("*")) { + if (Arrays.stream(EntityType.values()).noneMatch(type -> type.isAlive() && type.getKey().toString().equals(entity))) errors.add("生物 ID 无效: " + entity); + } + } + if (condition.type() == ConditionType.VISIT_DIMENSION && NamespacedKey.fromString(condition.string("dimension", "")) == null) errors.add("维度 ID 无效"); + if (condition.type() == ConditionType.REACH_LOCATION) { + if (condition.string("world", "").isBlank()) errors.add("区域必须指定 world"); + for (String axis : List.of("x", "y", "z")) if (!condition.parameters().containsKey(axis) || !Double.isFinite(condition.number(axis, Double.NaN))) errors.add("区域必须指定有限坐标 " + axis); + if (!Double.isFinite(condition.number("radius", 5)) || condition.number("radius", 5) < 0) errors.add("区域半径非法"); + } + } + if (definition.rewards().experience() < 0 || definition.rewards().experience() > 1_000_000) errors.add("经验奖励必须为 0 到 1000000"); + if (definition.rewards().items().size() > 64 || definition.rewards().commands().size() > 64) errors.add("奖励条目过多"); + for (String command : definition.rewards().commands()) if (command.isBlank() || command.length() > 1024 || command.contains("\n") || command.contains("\r")) errors.add("奖励命令为空、超长或包含换行"); + for (RewardDefinition.RewardItem item : definition.rewards().items()) { + Material material = Material.matchMaterial(item.material()); + if (material == null || !material.isItem() || item.amount() < 1 || item.amount() > 4096) + errors.add("奖励物品无效: " + item.material() + " x" + item.amount()); + } + return errors; + } + + private void validateGraph(Map map, List errors) { + Map> dependencies = new HashMap<>(); + Map> consumers = new HashMap<>(); + Set invalid = new HashSet<>(); Map indegree = new HashMap<>(); + for (AchievementDefinition definition : map.values()) { + Set required = new HashSet<>(); + if (!definition.parent().equals("root")) required.add(definition.parent()); + for (ConditionDefinition c : definition.conditions()) if (c.type() == ConditionType.COMPLETE_ACHIEVEMENT) required.add(c.string("achievement", "")); + dependencies.put(definition.id(), required); indegree.put(definition.id(), required.size()); + for (String dependency : required) { + consumers.computeIfAbsent(dependency, ignored -> new ArrayList<>()).add(definition.id()); + AchievementDefinition parent = map.get(dependency); + if (parent == null || definition.enabled() && !parent.enabled()) invalid.add(definition.id()); + } + } + Deque ready = new ArrayDeque<>(); indegree.forEach((id, count) -> { if (count == 0) ready.add(id); }); + Set visited = new HashSet<>(); Map depth = new HashMap<>(); + while (!ready.isEmpty()) { + String id = ready.remove(); visited.add(id); + int level = map.get(id).parent().equals("root") ? 1 : depth.getOrDefault(map.get(id).parent(), 0) + 1; + depth.put(id, level); if (level > 256) invalid.add(id); + for (String consumer : consumers.getOrDefault(id, List.of())) if (indegree.compute(consumer, (key, count) -> count - 1) == 0) ready.add(consumer); + } + for (String id : map.keySet()) if (!visited.contains(id)) invalid.add(id); + ready.addAll(invalid); + while (!ready.isEmpty()) for (String consumer : consumers.getOrDefault(ready.remove(), List.of())) if (invalid.add(consumer)) ready.add(consumer); + for (String id : invalid) { errors.add("成就 " + id + ": 依赖缺失、禁用、循环或树深度超过 256,已隔离"); map.remove(id); } + } + + public Map definitions() { return Collections.unmodifiableMap(definitions); } + public AchievementDefinition get(String id) { return definitions.get(id); } + public ValidationResult lastValidation() { return lastValidation; } + + public boolean createSkeleton(String id) throws IOException { + if (!validId(id) || id.equals("root") || id.equals(rootId())) return false; + File file = new File(plugin.getDataFolder(), "advancements.yml"); + YamlConfiguration yaml = StrictYaml.read(file.toPath(), true); + ConfigurationSection root = yaml.getConfigurationSection("achievements"); if (root == null) root = yaml.createSection("achievements"); + if (root.contains(id)) return false; + ConfigurationSection node = root.createSection(id); + node.set("name", id); node.set("description", "请编辑成就描述"); node.set("icon", "minecraft:stone"); node.set("frame", "task"); node.set("parent", "root"); + node.set("enabled", false); node.set("conditions", List.of(Map.of("type", "manual"))); + ConfigurationSection display = node.createSection("display"); display.set("x", 1); display.set("y", 0); + ConfigurationSection reward = node.createSection("rewards"); reward.set("experience", 0); reward.set("items", List.of()); reward.set("commands", List.of()); + StrictYaml.save(yaml, file.toPath()); + return true; + } + + public DeleteResult delete(String id) throws IOException { + if (id.equals("root") || id.equals(rootId()) || !validId(id)) return new DeleteResult(false, "根进度不可删除或 ID 非法"); + for (AchievementDefinition definition : definitions.values()) { + if (definition.parent().equals(id)) return new DeleteResult(false, "仍有子成就: " + definition.id()); + } + File file = new File(plugin.getDataFolder(), "advancements.yml"); + YamlConfiguration yaml = StrictYaml.read(file.toPath(), true); + ConfigurationSection root = yaml.getConfigurationSection("achievements"); + if (root == null || !root.contains(id)) return new DeleteResult(false, "成就不存在"); + for (String other : root.getKeys(false)) { + ConfigurationSection node = root.getConfigurationSection(other); if (node == null) continue; + if (node.getString("parent", "root").equals(id)) return new DeleteResult(false, "磁盘配置仍有子成就: " + other); + for (Map c : node.getMapList("conditions")) if ("complete_achievement".equals(c.get("type")) && id.equals(c.get("achievement"))) return new DeleteResult(false, "仍被条件引用: " + other); + } + root.set(id, null); StrictYaml.save(yaml, file.toPath()); + return new DeleteResult(true, ""); + } + + public boolean setEnabled(String id, boolean enabled) throws IOException { + File file = new File(plugin.getDataFolder(), "advancements.yml"); + YamlConfiguration yaml = StrictYaml.read(file.toPath(), true); + ConfigurationSection root = yaml.getConfigurationSection("achievements"); + ConfigurationSection node = root == null ? null : root.getConfigurationSection(id); + if (node == null) return false; + node.set("enabled", enabled); StrictYaml.save(yaml, file.toPath()); + return true; + } + + public record LoadResult(LinkedHashMap definitions, ValidationResult validation) {} + public record DeleteResult(boolean success, String reason) {} +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/config/MessageService.java b/src/main/java/top/itxiaohui/serveradvancements/config/MessageService.java new file mode 100644 index 0000000..7b79564 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/config/MessageService.java @@ -0,0 +1,54 @@ +package top.itxiaohui.serveradvancements.config; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +public final class MessageService { + private final JavaPlugin plugin; + private YamlConfiguration messages; + private final LegacyComponentSerializer legacy = LegacyComponentSerializer.legacyAmpersand(); + + public MessageService(JavaPlugin plugin) { + this.plugin = plugin; + reload(); + } + + public void reload() { + File file = new File(plugin.getDataFolder(), "messages.yml"); + messages = YamlConfiguration.loadConfiguration(file); + InputStream bundled = plugin.getResource("messages.yml"); + if (bundled != null) { + try (InputStreamReader reader = new InputStreamReader(bundled, StandardCharsets.UTF_8)) { + messages.setDefaults(YamlConfiguration.loadConfiguration(reader)); + } catch (java.io.IOException exception) { + plugin.getLogger().warning("读取内置消息默认值失败: " + exception.getMessage()); + } + } + } + + public Component component(String key, Map replacements) { + String value = messages.getString(key, key); + for (Map.Entry entry : replacements.entrySet()) { + value = value.replace("{" + entry.getKey() + "}", String.valueOf(entry.getValue())); + } + String prefix = messages.getString("prefix", ""); + return legacy.deserialize(prefix + value); + } + + public Component component(String key) { return component(key, Map.of()); } + + public void send(CommandSender sender, String key) { sender.sendMessage(component(key)); } + + public void send(CommandSender sender, String key, Map values) { + sender.sendMessage(component(key, values)); + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/config/StrictYaml.java b/src/main/java/top/itxiaohui/serveradvancements/config/StrictYaml.java new file mode 100644 index 0000000..3b11ce5 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/config/StrictYaml.java @@ -0,0 +1,38 @@ +package top.itxiaohui.serveradvancements.config; + +import org.bukkit.configuration.file.YamlConfiguration; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; + +public final class StrictYaml { + private StrictYaml() { } + public static YamlConfiguration read(Path file, boolean literalKeys) throws IOException { + if (!Files.exists(file)) return parse("", literalKeys); + if (Files.size(file) > 3_000_000) throw new IOException("配置文件超过 3 MB: " + file.getFileName()); + return parse(Files.readString(file, StandardCharsets.UTF_8), literalKeys); + } + public static YamlConfiguration parse(String content, boolean literalKeys) throws IOException { + if (content.length() > 3_000_000) throw new IOException("配置文本超过大小限制"); + YamlConfiguration result = new YamlConfiguration(); + if (literalKeys) result.options().pathSeparator('\u001f'); + LoaderOptions options = new LoaderOptions(); options.setAllowDuplicateKeys(false); options.setMaxAliasesForCollections(20); + try { + new Yaml(new SafeConstructor(options)).load(content); + result.loadFromString(content); + } catch (Exception error) { throw new IOException("YAML 无效或有重复键: " + error.getMessage(), error); } + return result; + } + public static void save(YamlConfiguration yaml, Path file) throws IOException { + Files.createDirectories(file.toAbsolutePath().getParent()); + Path temporary = Files.createTempFile(file.toAbsolutePath().getParent(), "isa-config-", ".tmp"); + try { + Files.writeString(temporary, yaml.saveToString(), StandardCharsets.UTF_8); + try { Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } + catch (AtomicMoveNotSupportedException ignored) { Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING); } + } finally { Files.deleteIfExists(temporary); } + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/config/ValidationResult.java b/src/main/java/top/itxiaohui/serveradvancements/config/ValidationResult.java new file mode 100644 index 0000000..72f58fb --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/config/ValidationResult.java @@ -0,0 +1,7 @@ +package top.itxiaohui.serveradvancements.config; + +import java.util.List; + +public record ValidationResult(List errors, List warnings) { + public boolean valid() { return errors.isEmpty(); } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/database/BundledSqliteDriver.java b/src/main/java/top/itxiaohui/serveradvancements/database/BundledSqliteDriver.java new file mode 100644 index 0000000..ae36677 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/database/BundledSqliteDriver.java @@ -0,0 +1,30 @@ +package top.itxiaohui.serveradvancements.database; + +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.sql.*; +import java.util.Properties; + +/** SQLite JNI symbols require the original org.sqlite package; isolate instead of relocating. */ +final class BundledSqliteDriver extends URLClassLoader { + BundledSqliteDriver(URL source) { super(new URL[]{source}, DatabaseManager.class.getClassLoader()); } + @Override protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!name.startsWith("org.sqlite.")) return super.loadClass(name, resolve); + synchronized (getClassLoadingLock(name)) { + Class type = findLoadedClass(name); + if (type == null) type = findClass(name); + if (resolve) resolveClass(type); + return type; + } + } + @Override public URL getResource(String name) { + return name.startsWith("org/sqlite/") ? findResource(name) : super.getResource(name); + } + Connection connect(String url) throws SQLException { + try { + Driver driver = (Driver) loadClass("org.sqlite.JDBC").getDeclaredConstructor().newInstance(); + return driver.connect(url, new Properties()); + } catch (ReflectiveOperationException error) { throw new SQLException("无法加载打包的 SQLite 驱动", error); } + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/database/DatabaseManager.java b/src/main/java/top/itxiaohui/serveradvancements/database/DatabaseManager.java new file mode 100644 index 0000000..4a67dbd --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/database/DatabaseManager.java @@ -0,0 +1,290 @@ +package top.itxiaohui.serveradvancements.database; + +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.sql.*; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.concurrent.*; + +public final class DatabaseManager implements AutoCloseable { + private static final int SCHEMA_VERSION = 1; + private final JavaPlugin plugin; + private Connection connection; + private Path databasePath; + private BundledSqliteDriver bundledLoader; + private final ExecutorService io = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(4096), runnable -> { + Thread thread = new Thread(runnable, "isa-database"); + thread.setDaemon(true); + return thread; + }); + + /** All runtime database work is serialized here, never on the server tick thread. */ + public CompletableFuture submit(Callable operation) { + CompletableFuture result = new CompletableFuture<>(); + try { + io.execute(() -> { + try { result.complete(operation.call()); } + catch (Throwable error) { result.completeExceptionally(error); } + }); + } catch (RejectedExecutionException error) { result.completeExceptionally(error); } + return result; + } + + public CompletableFuture auditAsync(String actor, String action, String target, String detail) { + return submit(() -> { audit(actor, action, target, detail); return null; }); + } + + public DatabaseManager(JavaPlugin plugin) { this.plugin = plugin; } + + public synchronized void open() throws SQLException, IOException { + Path dataDirectory = plugin.getDataFolder().toPath().resolve("data"); + Files.createDirectories(dataDirectory); + databasePath = dataDirectory.resolve("advancements.db"); + // Explicitly select our bundled driver; Paper also registers a different SQLite driver. + var origin = DatabaseManager.class.getProtectionDomain().getCodeSource().getLocation(); + if (origin.getPath().endsWith(".jar")) { + bundledLoader = new BundledSqliteDriver(origin); + connection = bundledLoader.connect("jdbc:sqlite:" + databasePath.toAbsolutePath()); + } else { + connection = new org.sqlite.JDBC().connect("jdbc:sqlite:" + databasePath.toAbsolutePath(), new Properties()); + } + try { + if (!connection.getMetaData().getDriverVersion().equals("3.50.3.0")) throw new SQLException("实际 SQLite 驱动版本与固定依赖 3.50.3.0 不符"); + try (Statement statement = connection.createStatement()) { + statement.execute("PRAGMA foreign_keys=ON"); + statement.execute("PRAGMA journal_mode=WAL"); + statement.execute("PRAGMA synchronous=FULL"); + statement.execute("PRAGMA busy_timeout=" + Math.clamp(plugin.getConfig().getInt("database.busy-timeout-millis", 5000), 0, 10000)); + } + migrate(); + } catch (SQLException error) { + try { connection.close(); } catch (SQLException closeError) { error.addSuppressed(closeError); } + connection = null; + throw error; + } + } + + private void migrate() throws SQLException { + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + statement.executeUpdate("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"); + try (ResultSet rs = statement.executeQuery("SELECT COUNT(*) FROM schema_version")) { + if (rs.next() && rs.getInt(1) == 0) statement.executeUpdate("INSERT INTO schema_version(version) VALUES (0)"); + } + int current; + try (ResultSet rs = statement.executeQuery("SELECT version FROM schema_version LIMIT 1")) { + current = rs.next() ? rs.getInt(1) : 0; + } + if (current < 1) { + statement.executeUpdate("CREATE TABLE IF NOT EXISTS player_statistics (" + + "player_uuid TEXT NOT NULL, statistic_key TEXT NOT NULL, value REAL NOT NULL DEFAULT 0," + + "updated_at INTEGER NOT NULL, PRIMARY KEY(player_uuid, statistic_key))"); + statement.executeUpdate("CREATE INDEX IF NOT EXISTS idx_player_statistics_key ON player_statistics(statistic_key)"); + statement.executeUpdate("CREATE TABLE IF NOT EXISTS player_achievement_data (" + + "player_uuid TEXT NOT NULL, achievement_id TEXT NOT NULL, condition_key TEXT NOT NULL," + + "value REAL NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL," + + "PRIMARY KEY(player_uuid, achievement_id, condition_key))"); + statement.executeUpdate("CREATE INDEX IF NOT EXISTS idx_achievement_data_id ON player_achievement_data(achievement_id)"); + statement.executeUpdate("CREATE TABLE IF NOT EXISTS reward_claims (" + + "player_uuid TEXT NOT NULL, achievement_id TEXT NOT NULL, status TEXT NOT NULL," + + "attempts INTEGER NOT NULL DEFAULT 0, detail TEXT, updated_at INTEGER NOT NULL," + + "PRIMARY KEY(player_uuid, achievement_id))"); + statement.executeUpdate("CREATE INDEX IF NOT EXISTS idx_reward_status ON reward_claims(status)"); + statement.executeUpdate("CREATE TABLE IF NOT EXISTS admin_audit_log (" + + "id INTEGER PRIMARY KEY AUTOINCREMENT, actor TEXT NOT NULL, action TEXT NOT NULL," + + "target TEXT, detail TEXT, created_at INTEGER NOT NULL)"); + statement.executeUpdate("CREATE INDEX IF NOT EXISTS idx_audit_created ON admin_audit_log(created_at)"); + statement.executeUpdate("UPDATE schema_version SET version=1"); + } + if (current > SCHEMA_VERSION) throw new SQLException("数据库版本 " + current + " 高于插件支持版本 " + SCHEMA_VERSION); + connection.commit(); + } catch (SQLException exception) { + connection.rollback(); + throw exception; + } finally { + connection.setAutoCommit(true); + } + } + + public synchronized Map loadStatistics(UUID playerId) throws SQLException { + ensureOpen(); + Map result = new HashMap<>(); + try (PreparedStatement statement = connection.prepareStatement( + "SELECT statistic_key, value FROM player_statistics WHERE player_uuid=?")) { + statement.setString(1, playerId.toString()); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) result.put(rs.getString(1), rs.getDouble(2)); + } + } + return result; + } + + public synchronized void saveStatistics(Map> batch) throws SQLException { + if (batch.isEmpty()) return; + ensureOpen(); + String sql = "INSERT INTO player_statistics(player_uuid,statistic_key,value,updated_at) VALUES(?,?,?,?) " + + "ON CONFLICT(player_uuid,statistic_key) DO UPDATE SET value=excluded.value,updated_at=excluded.updated_at"; + connection.setAutoCommit(false); + try (PreparedStatement statement = connection.prepareStatement(sql)) { + long now = System.currentTimeMillis(); + for (Map.Entry> player : batch.entrySet()) { + for (Map.Entry statistic : player.getValue().entrySet()) { + statement.setString(1, player.getKey().toString()); + statement.setString(2, statistic.getKey()); + statement.setDouble(3, statistic.getValue()); + statement.setLong(4, now); + statement.addBatch(); + } + } + statement.executeBatch(); + connection.commit(); + } catch (SQLException exception) { + connection.rollback(); + throw exception; + } finally { + connection.setAutoCommit(true); + } + } + + public synchronized RewardStatus rewardStatus(UUID playerId, String achievementId) throws SQLException { + ensureOpen(); + try (PreparedStatement statement = connection.prepareStatement( + "SELECT status FROM reward_claims WHERE player_uuid=? AND achievement_id=?")) { + statement.setString(1, playerId.toString()); + statement.setString(2, achievementId); + try (ResultSet rs = statement.executeQuery()) { + if (!rs.next()) return RewardStatus.NONE; + try { return RewardStatus.valueOf(rs.getString(1)); } + catch (IllegalArgumentException ignored) { return RewardStatus.FAILED; } + } + } + } + + public synchronized boolean beginReward(UUID playerId, String achievementId, boolean reclaim) throws SQLException { + ensureOpen(); + try (PreparedStatement statement = connection.prepareStatement( + "INSERT INTO reward_claims(player_uuid,achievement_id,status,attempts,detail,updated_at) VALUES(?,?,?,1,NULL,?) " + + "ON CONFLICT(player_uuid,achievement_id) DO UPDATE SET status='PENDING',attempts=attempts+1,detail=NULL,updated_at=excluded.updated_at " + + "WHERE reward_claims.status='CLAIMED' AND ?")) { + statement.setString(1, playerId.toString()); + statement.setString(2, achievementId); + statement.setString(3, RewardStatus.PENDING.name()); + statement.setLong(4, System.currentTimeMillis()); + statement.setBoolean(5, reclaim); + return statement.executeUpdate() == 1; + } + } + + public synchronized Reservation reserveReward(UUID playerId, String achievementId, boolean reclaim) throws SQLException { + ensureOpen(); + RewardStatus status = rewardStatus(playerId, achievementId); + if (status == RewardStatus.PENDING || status == RewardStatus.FAILED) return Reservation.REVIEW_REQUIRED; + if (status == RewardStatus.CLAIMED && !reclaim) return Reservation.NO_REWARD; + if (status == RewardStatus.RESERVED) return Reservation.RESERVED; + try (PreparedStatement statement = connection.prepareStatement( + "INSERT INTO reward_claims(player_uuid,achievement_id,status,attempts,detail,updated_at) VALUES(?,?,'RESERVED',1,NULL,?) " + + "ON CONFLICT(player_uuid,achievement_id) DO UPDATE SET status='RESERVED',attempts=attempts+1,detail=NULL,updated_at=excluded.updated_at " + + "WHERE reward_claims.status='CLAIMED' AND ?")) { + statement.setString(1, playerId.toString()); statement.setString(2, achievementId); + statement.setLong(3, System.currentTimeMillis()); statement.setBoolean(4, reclaim); + return statement.executeUpdate() == 1 ? Reservation.RESERVED : Reservation.REVIEW_REQUIRED; + } + } + + public synchronized boolean startReward(UUID playerId, String achievementId) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement( + "UPDATE reward_claims SET status='PENDING',updated_at=? WHERE player_uuid=? AND achievement_id=? AND status='RESERVED'")) { + statement.setLong(1, System.currentTimeMillis()); statement.setString(2, playerId.toString()); statement.setString(3, achievementId); + return statement.executeUpdate() == 1; + } + } + + /** Only call when no game-side effect has run: a RESERVED record is safe to resume. */ + public synchronized void releaseUnexecutedReward(UUID playerId, String achievementId) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement( + "UPDATE reward_claims SET status='RESERVED',detail='not executed',updated_at=? WHERE player_uuid=? AND achievement_id=? AND status='PENDING'")) { + statement.setLong(1, System.currentTimeMillis()); statement.setString(2, playerId.toString()); statement.setString(3, achievementId); statement.executeUpdate(); + } + } + + public synchronized void finishReward(UUID playerId, String achievementId, boolean success, String detail) throws SQLException { + ensureOpen(); + try (PreparedStatement statement = connection.prepareStatement( + "UPDATE reward_claims SET status=?,detail=?,updated_at=? WHERE player_uuid=? AND achievement_id=?")) { + statement.setString(1, success ? RewardStatus.CLAIMED.name() : RewardStatus.FAILED.name()); + statement.setString(2, detail); + statement.setLong(3, System.currentTimeMillis()); + statement.setString(4, playerId.toString()); + statement.setString(5, achievementId); + statement.executeUpdate(); + } + } + + public synchronized void audit(String actor, String action, String target, String detail) { + try { + ensureOpen(); + try (PreparedStatement statement = connection.prepareStatement( + "INSERT INTO admin_audit_log(actor,action,target,detail,created_at) VALUES(?,?,?,?,?)")) { + statement.setString(1, actor); + statement.setString(2, action); + statement.setString(3, target); + statement.setString(4, detail); + statement.setLong(5, System.currentTimeMillis()); + statement.executeUpdate(); + } + } catch (SQLException exception) { + plugin.getLogger().severe("写入管理审计日志失败: " + exception.getMessage()); + } + } + + public synchronized Path backup() throws SQLException, IOException { + ensureOpen(); + Path backupDirectory = plugin.getDataFolder().toPath().resolve("backups"); + Files.createDirectories(backupDirectory); + String timestamp = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").withZone(ZoneId.systemDefault()).format(Instant.now()); + Path snapshot = backupDirectory.resolve(timestamp + "-" + UUID.randomUUID()); + Files.createDirectories(snapshot); + Path target = snapshot.resolve("advancements.db"); + // VACUUM INTO creates a consistent SQLite snapshot, including committed WAL pages. + try (PreparedStatement statement = connection.prepareStatement("VACUUM INTO ?")) { + statement.setString(1, target.toAbsolutePath().toString()); statement.execute(); + } + for (String name : List.of("config.yml", "advancements.yml", "messages.yml")) { + Path source = plugin.getDataFolder().toPath().resolve(name); + if (Files.exists(source)) Files.copy(source, snapshot.resolve(name), StandardCopyOption.COPY_ATTRIBUTES); + } + return target; + } + + public Path databasePath() { return databasePath; } + + private void ensureOpen() throws SQLException { + if (connection == null || connection.isClosed()) throw new SQLException("SQLite 连接未打开"); + } + + @Override public void close() throws SQLException { + io.shutdown(); + try { + if (!io.awaitTermination(30, TimeUnit.SECONDS)) throw new SQLException("数据库队列未在 30 秒内排空;请保留 WAL 文件并检查日志"); + } catch (InterruptedException error) { Thread.currentThread().interrupt(); throw new SQLException("等待数据库关闭被中断", error); } + synchronized (this) { + try { + if (connection != null && !connection.isClosed()) { + try (Statement statement = connection.createStatement()) { statement.execute("PRAGMA wal_checkpoint(TRUNCATE)"); } + finally { connection.close(); } + } + } finally { if (bundledLoader != null) try { bundledLoader.close(); } catch (IOException error) { throw new SQLException("关闭 SQLite 类加载器失败", error); } } + } + } + + public enum RewardStatus { NONE, RESERVED, PENDING, CLAIMED, FAILED } + public enum Reservation { RESERVED, NO_REWARD, REVIEW_REQUIRED } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/gui/AdminGui.java b/src/main/java/top/itxiaohui/serveradvancements/gui/AdminGui.java new file mode 100644 index 0000000..a573720 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/gui/AdminGui.java @@ -0,0 +1,128 @@ +package top.itxiaohui.serveradvancements.gui; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.plugin.java.JavaPlugin; +import top.itxiaohui.serveradvancements.advancement.AdvancementManager; +import top.itxiaohui.serveradvancements.condition.ConditionEngine; +import top.itxiaohui.serveradvancements.config.ConfigurationManager; +import top.itxiaohui.serveradvancements.model.AchievementDefinition; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public final class AdminGui implements Listener { + public static final String PERMISSION = "itxiaohui.serveradvancements.admin"; + private final JavaPlugin plugin; + private final ConfigurationManager configuration; + private final AdvancementManager advancements; + private final ConditionEngine conditions; + + public AdminGui(JavaPlugin plugin, ConfigurationManager configuration, AdvancementManager advancements, + ConditionEngine conditions) { + this.plugin = plugin; + this.configuration = configuration; + this.advancements = advancements; + this.conditions = conditions; + } + + public void open(Player player, int page) { + if (!player.hasPermission(PERMISSION)) return; + List all = new ArrayList<>(configuration.definitions().values()); + int maxPage = Math.max(0, (all.size() - 1) / 45); + page = Math.max(0, Math.min(page, maxPage)); + Holder holder = new Holder(page); + Inventory inventory = Bukkit.createInventory(holder, 54, Component.text("服务器成就管理 第 " + (page + 1) + " 页")); + holder.inventory = inventory; + int start = page * 45; + for (int i = start; i < Math.min(start + 45, all.size()); i++) { + AchievementDefinition definition = all.get(i); + Material material = Material.matchMaterial(definition.icon()); + ItemStack item = new ItemStack(material == null ? Material.BARRIER : material); + ItemMeta meta = item.getItemMeta(); + meta.displayName(Component.text(definition.name(), definition.enabled() ? NamedTextColor.GOLD : NamedTextColor.GRAY)); + meta.lore(List.of( + Component.text("ID: " + definition.id(), NamedTextColor.DARK_GRAY), + Component.text(definition.description(), NamedTextColor.GRAY), + Component.text("左键: 详情 | 右键: 授予自己", NamedTextColor.YELLOW), + Component.text("Shift+左键: 启用/禁用 | Q: 撤销自己", NamedTextColor.YELLOW))); + item.setItemMeta(meta); + inventory.setItem(i - start, item); + holder.ids[i - start] = definition.id(); + } + inventory.setItem(45, button(Material.ARROW, "上一页")); + inventory.setItem(47, button(Material.PLAYER_HEAD, "玩家进度:/isa progress <玩家>")); + inventory.setItem(48, button(Material.BARRIER, "删除:/isa delete confirm")); + inventory.setItem(49, button(Material.WRITABLE_BOOK, "创建:使用 /isa create ")); + inventory.setItem(50, button(Material.REDSTONE, "重载配置")); + inventory.setItem(51, button(Material.CHEST, "备份:使用 /isa backup")); + inventory.setItem(53, button(Material.ARROW, "下一页")); + player.openInventory(inventory); + } + + private ItemStack button(Material material, String name) { + ItemStack item = new ItemStack(material); + ItemMeta meta = item.getItemMeta(); + meta.displayName(Component.text(name, NamedTextColor.AQUA)); + item.setItemMeta(meta); + return item; + } + + @EventHandler(ignoreCancelled = true) + public void onClick(InventoryClickEvent event) { + if (!(event.getInventory().getHolder(false) instanceof Holder holder)) return; + event.setCancelled(true); + if (!(event.getWhoClicked() instanceof Player player) || !player.hasPermission(PERMISSION)) { + event.getWhoClicked().closeInventory(); + return; + } + int slot = event.getRawSlot(); + if (slot < 0 || slot >= 54) return; + if (slot == 45) { open(player, holder.page - 1); return; } + if (slot == 53) { open(player, holder.page + 1); return; } + if (slot == 50) { player.closeInventory(); player.performCommand("isa reload"); return; } + String id = slot < 45 ? holder.ids[slot] : null; + if (id == null) return; + AchievementDefinition definition = configuration.get(id); + if (definition == null) return; + if (event.isShiftClick() && event.isLeftClick()) { + try { + configuration.setEnabled(id, !definition.enabled()); + player.closeInventory(); + player.performCommand("isa reload"); + } catch (IOException exception) { player.sendMessage(Component.text("保存失败: " + exception.getMessage(), NamedTextColor.RED)); } + } else if (event.getClick() == org.bukkit.event.inventory.ClickType.DROP || event.getClick() == org.bukkit.event.inventory.ClickType.CONTROL_DROP) { + player.performCommand("isa revoke " + player.getName() + " " + id); + } else if (event.isRightClick()) { + player.performCommand("isa give " + player.getName() + " " + id); + } else { + player.sendMessage(Component.text(id + " — " + definition.description(), NamedTextColor.GOLD)); + player.sendMessage(Component.text("父级: " + definition.parent() + ",条件数: " + definition.conditions().size(), NamedTextColor.GRAY)); + } + } + + @EventHandler(ignoreCancelled = true) + public void onDrag(InventoryDragEvent event) { + if (event.getInventory().getHolder(false) instanceof Holder) event.setCancelled(true); + } + + private static final class Holder implements InventoryHolder { + private final int page; + private final String[] ids = new String[45]; + private Inventory inventory; + private Holder(int page) { this.page = page; } + @Override public Inventory getInventory() { return inventory; } + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/listener/PlayerActivityListener.java b/src/main/java/top/itxiaohui/serveradvancements/listener/PlayerActivityListener.java new file mode 100644 index 0000000..85d9db6 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/listener/PlayerActivityListener.java @@ -0,0 +1,158 @@ +package top.itxiaohui.serveradvancements.listener; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.Entity; +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.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.inventory.FurnaceExtractEvent; +import org.bukkit.event.entity.EntityTameEvent; +import org.bukkit.event.entity.EntityBreedEvent; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.entity.EntityPickupItemEvent; +import org.bukkit.event.inventory.CraftItemEvent; +import org.bukkit.event.player.*; +import org.bukkit.inventory.CraftingInventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; +import top.itxiaohui.serveradvancements.advancement.AdvancementManager; +import top.itxiaohui.serveradvancements.condition.ConditionEngine; +import top.itxiaohui.serveradvancements.model.ConditionType; +import top.itxiaohui.serveradvancements.statistics.StatisticsService; + +public final class PlayerActivityListener implements Listener { + private final JavaPlugin plugin; + private final StatisticsService statistics; + private final ConditionEngine conditions; + private final AdvancementManager advancements; + + public PlayerActivityListener(JavaPlugin plugin, StatisticsService statistics, ConditionEngine conditions, + AdvancementManager advancements) { + this.plugin = plugin; + this.statistics = statistics; + this.conditions = conditions; + this.advancements = advancements; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + boolean firstJoin = !player.hasPlayedBefore(); + var loadedFuture = statistics.beginSession(player); + if (firstJoin) conditions.mark(player, ConditionType.FIRST_JOIN, ""); + conditions.mark(player, ConditionType.VISIT_DIMENSION, player.getWorld().getKey().toString()); + conditions.setLevel(player, player.getLevel()); + loadedFuture.thenAccept(loaded -> { + if (!loaded) return; + plugin.getServer().getScheduler().runTask(plugin, () -> { + if (!player.isOnline()) return; + conditions.evaluate(player); + }); + }); + plugin.getServer().getScheduler().runTaskLater(plugin, () -> { + if (!player.isOnline()) return; + advancements.ensureRoot(player); + }, 20L); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onQuit(PlayerQuitEvent event) { + statistics.endSession(event.getPlayer().getUniqueId()); + statistics.flushSoon(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBreak(BlockBreakEvent event) { + conditions.record(event.getPlayer(), ConditionType.MINE_BLOCK, event.getBlock().getType().getKey().toString(), 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickup(EntityPickupItemEvent event) { + if (!(event.getEntity() instanceof Player player)) return; + ItemStack stack = event.getItem().getItemStack(); + conditions.record(player, ConditionType.COLLECT_ITEM, stack.getType().getKey().toString(), stack.getAmount()); + conditions.record(player, ConditionType.OBTAIN_ITEM, stack.getType().getKey().toString(), stack.getAmount()); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onDeath(EntityDeathEvent event) { + Player killer = event.getEntity().getKiller(); + if (killer != null) conditions.record(killer, ConditionType.KILL_MOB, event.getEntityType().getKey().toString(), 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onWorldChange(PlayerChangedWorldEvent event) { + conditions.mark(event.getPlayer(), ConditionType.VISIT_DIMENSION, event.getPlayer().getWorld().getKey().toString()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + Location from = event.getFrom(); + Location to = event.getTo(); + if (to == null || from.getWorld() != to.getWorld()) return; + double distance = from.distance(to); + if (distance > 0 && distance < 100) conditions.record(event.getPlayer(), ConditionType.MOVE_DISTANCE, "", distance); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onCraft(CraftItemEvent event) { + // A click is only an attempt (NOTHING, full inventory, etc.). Count the native + // successful ITEM_CRAFTED statistic below, not an estimated recipe matrix. + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onStatistic(PlayerStatisticIncrementEvent event) { + if (event.getStatistic() != Statistic.CRAFT_ITEM || event.getMaterial() == null) return; + long amount = (long) event.getNewValue() - event.getPreviousValue(); + if (amount <= 0) return; + conditions.record(event.getPlayer(), ConditionType.CRAFT_ITEM, event.getMaterial().getKey().toString(), amount); + conditions.record(event.getPlayer(), ConditionType.OBTAIN_ITEM, event.getMaterial().getKey().toString(), amount); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBreed(EntityBreedEvent event) { + Entity breeder = event.getBreeder(); + if (breeder instanceof Player player) + conditions.record(player, ConditionType.BREED_MOB, event.getEntityType().getKey().toString(), 1); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onLevel(PlayerLevelChangeEvent event) { + conditions.setLevel(event.getPlayer(), event.getNewLevel()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onEat(PlayerItemConsumeEvent event) { + if (event.getItem().getType().isEdible()) + conditions.event(event.getPlayer(), "eat_food", event.getItem().getType().getKey().toString(), 1); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onCook(FurnaceExtractEvent event) { + if (event.getItemType().isEdible()) + conditions.event(event.getPlayer(), "cook_food", event.getItemType().getKey().toString(), event.getItemAmount()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTame(EntityTameEvent event) { + if (event.getOwner() instanceof Player player) + conditions.event(player, "tame_animal", event.getEntityType().getKey().toString(), 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onFish(PlayerFishEvent event) { + if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH && event.getCaught() instanceof org.bukkit.entity.Item item) + conditions.event(event.getPlayer(), "fish_item", item.getItemStack().getType().getKey().toString(), item.getItemStack().getAmount()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent event) { + if (event.canBuild()) conditions.event(event.getPlayer(), "place_block", event.getBlockPlaced().getType().getKey().toString(), 1); + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/model/AchievementDefinition.java b/src/main/java/top/itxiaohui/serveradvancements/model/AchievementDefinition.java new file mode 100644 index 0000000..585400e --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/model/AchievementDefinition.java @@ -0,0 +1,10 @@ +package top.itxiaohui.serveradvancements.model; + +import java.util.List; + +public record AchievementDefinition( + String id, String name, String description, String icon, AdvancementFrame frame, + String parent, double x, double y, List conditions, + boolean hidden, boolean showToast, boolean announceChat, boolean enabled, + RewardDefinition rewards) { +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/model/AdvancementFrame.java b/src/main/java/top/itxiaohui/serveradvancements/model/AdvancementFrame.java new file mode 100644 index 0000000..168d001 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/model/AdvancementFrame.java @@ -0,0 +1,11 @@ +package top.itxiaohui.serveradvancements.model; + +import java.util.Locale; + +public enum AdvancementFrame { + TASK, GOAL, CHALLENGE; + + public static AdvancementFrame parse(String value) { + return valueOf(value.trim().toUpperCase(Locale.ROOT)); + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/model/ConditionDefinition.java b/src/main/java/top/itxiaohui/serveradvancements/model/ConditionDefinition.java new file mode 100644 index 0000000..e9cddf5 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/model/ConditionDefinition.java @@ -0,0 +1,62 @@ +package top.itxiaohui.serveradvancements.model; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +public record ConditionDefinition(ConditionType type, Map parameters) { + public ConditionDefinition { + parameters = Collections.unmodifiableMap(new LinkedHashMap<>(parameters)); + } + + public String string(String key, String fallback) { + Object value = parameters.get(key); + return value == null ? fallback : String.valueOf(value); + } + + public double number(String key, double fallback) { + Object value = parameters.get(key); + if (value instanceof Number number) return number.doubleValue(); + try { return value == null ? fallback : Double.parseDouble(String.valueOf(value)); } + catch (NumberFormatException ignored) { return Double.NaN; } + } + + public String statisticKey() { + return switch (type) { + case FIRST_JOIN -> "first_join"; + case ONLINE_TIME -> "online_time_ms"; + case MINE_BLOCK -> "mine_block:" + string("block", ""); + case COLLECT_ITEM -> "collect_item:" + string("item", ""); + case OBTAIN_ITEM -> "obtain_item:" + string("item", ""); + case KILL_MOB -> "kill_mob:" + string("entity", "*"); + case VISIT_DIMENSION -> "visit_dimension:" + string("dimension", ""); + case MOVE_DISTANCE -> "move_distance"; + case REACH_LOCATION -> "reach_location:" + string("world", "world") + ":" + string("id", string("x", "") + "," + string("y", "") + "," + string("z", "") + "," + string("radius", "5")); + case CRAFT_ITEM -> "craft_item:" + string("item", ""); + case BREED_MOB -> "breed_mob:" + string("entity", "*"); + case EXPERIENCE_LEVEL -> "experience_level"; + case COMPLETE_ACHIEVEMENT -> "achievement:" + string("achievement", ""); + case MANUAL -> "manual"; + case PLAYER_STATISTIC -> "player_statistic"; + case VANILLA_ADVANCEMENT -> "vanilla_advancement"; + case INVENTORY_SET -> "inventory_set"; + case VISIT_BIOME -> "visit_biome:" + string("biome", ""); + case VISIT_STRUCTURE -> "visit_structure"; + case ALTITUDE -> "altitude"; + case EVENT_COUNT, EVENT_DISTINCT -> "event:" + string("event", ""); + }; + } + + public double target() { + if (type == ConditionType.ONLINE_TIME) { + double amount = number("amount", 1); + return switch (string("unit", "seconds").toLowerCase(java.util.Locale.ROOT)) { + case "minutes", "minute" -> amount * 60_000D; + case "hours", "hour" -> amount * 3_600_000D; + case "seconds", "second" -> amount * 1_000D; + default -> Double.NaN; + }; + } + return number("amount", 1); + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/model/ConditionType.java b/src/main/java/top/itxiaohui/serveradvancements/model/ConditionType.java new file mode 100644 index 0000000..c62bbf5 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/model/ConditionType.java @@ -0,0 +1,14 @@ +package top.itxiaohui.serveradvancements.model; + +import java.util.Locale; + +public enum ConditionType { + FIRST_JOIN, ONLINE_TIME, MINE_BLOCK, COLLECT_ITEM, OBTAIN_ITEM, KILL_MOB, VISIT_DIMENSION, + MOVE_DISTANCE, REACH_LOCATION, CRAFT_ITEM, BREED_MOB, EXPERIENCE_LEVEL, + COMPLETE_ACHIEVEMENT, MANUAL, PLAYER_STATISTIC, VANILLA_ADVANCEMENT, INVENTORY_SET, + VISIT_BIOME, VISIT_STRUCTURE, ALTITUDE, EVENT_COUNT, EVENT_DISTINCT; + + public static ConditionType parse(String value) { + return valueOf(value.trim().toUpperCase(Locale.ROOT)); + } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/model/RewardDefinition.java b/src/main/java/top/itxiaohui/serveradvancements/model/RewardDefinition.java new file mode 100644 index 0000000..8965b25 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/model/RewardDefinition.java @@ -0,0 +1,8 @@ +package top.itxiaohui.serveradvancements.model; + +import java.util.List; + +public record RewardDefinition(int experience, List items, List commands, + boolean allowReclaim, String completionMessage) { + public record RewardItem(String material, int amount) {} +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/reward/RewardService.java b/src/main/java/top/itxiaohui/serveradvancements/reward/RewardService.java new file mode 100644 index 0000000..abb1de8 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/reward/RewardService.java @@ -0,0 +1,124 @@ +package top.itxiaohui.serveradvancements.reward; + +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 top.itxiaohui.serveradvancements.config.MessageService; +import top.itxiaohui.serveradvancements.database.DatabaseManager; +import top.itxiaohui.serveradvancements.model.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.function.BooleanSupplier; + +/** Durable reservation -> execution intent -> game-side effects -> durable result. */ +public final class RewardService implements AutoCloseable { + public enum Outcome { COMPLETED, RESTORED_WITHOUT_REWARD, ALREADY_COMPLETE, IN_FLIGHT, REVIEW_REQUIRED, RETRY_LATER } + private record Key(UUID player, String achievement) { } + private final JavaPlugin plugin; + private final DatabaseManager database; + private final MessageService messages; + private final Executor mainThread; + private final Set inFlight = ConcurrentHashMap.newKeySet(); + private volatile boolean closed; + + public RewardService(JavaPlugin plugin, DatabaseManager database, MessageService messages) { + this(plugin, database, messages, task -> Bukkit.getScheduler().runTask(plugin, task)); + } + public RewardService(JavaPlugin plugin, DatabaseManager database, MessageService messages, Executor mainThread) { + this.plugin = plugin; this.database = database; this.messages = messages; this.mainThread = mainThread; + } + + public boolean isInFlight(UUID id, String achievement) { return inFlight.contains(new Key(id, achievement)); } + + public CompletableFuture grant(Player player, AchievementDefinition achievement) { + return complete(player, achievement, () -> true, () -> { }); + } + + public CompletableFuture complete(Player player, AchievementDefinition achievement, BooleanSupplier award, Runnable completed) { + Key key = new Key(player.getUniqueId(), achievement.id()); + if (closed) return CompletableFuture.completedFuture(Outcome.RETRY_LATER); + if (!inFlight.add(key)) return CompletableFuture.completedFuture(Outcome.IN_FLIGHT); + CompletableFuture result = new CompletableFuture<>(); + result.whenComplete((value, error) -> inFlight.remove(key)); + database.submit(() -> database.reserveReward(key.player(), key.achievement(), achievement.rewards().allowReclaim())) + .whenComplete((reservation, error) -> { + if (error != null) { failBeforeExecution(result, key, error); return; } + if (reservation == DatabaseManager.Reservation.REVIEW_REQUIRED) { result.complete(Outcome.REVIEW_REQUIRED); return; } + if (reservation == DatabaseManager.Reservation.NO_REWARD) { + onMain(() -> { + if (!player.isOnline()) { result.complete(Outcome.RETRY_LATER); return; } + if (award.getAsBoolean()) { completed.run(); result.complete(Outcome.RESTORED_WITHOUT_REWARD); } + else result.complete(Outcome.ALREADY_COMPLETE); + }, () -> result.complete(Outcome.RETRY_LATER), result); + return; + } + // PENDING is persisted before awarding a native criterion or running any reward. + database.submit(() -> database.startReward(key.player(), key.achievement())).whenComplete((started, startError) -> { + if (startError != null) { failBeforeExecution(result, key, startError); return; } + if (!started) { result.complete(Outcome.REVIEW_REQUIRED); return; } + Runnable notExecuted = () -> database.submit(() -> { + database.releaseUnexecutedReward(key.player(), key.achievement()); return null; + }).whenComplete((ignored, releaseError) -> result.complete(Outcome.RETRY_LATER)); + onMain(() -> { + if (!player.isOnline()) { notExecuted.run(); return; } + if (!award.getAsBoolean()) { notExecuted.run(); return; } + // The native state is now done; failed or uncertain effects are never automatically replayed. + boolean success = false; + String detail = "ok"; + try { execute(player, achievement); success = true; } + catch (RuntimeException executionError) { + detail = executionError.toString(); + plugin.getLogger().severe("奖励部分失败,需要人工核查 " + key + ": " + detail); + } + completed.run(); + final boolean delivered = success; final String deliveryDetail = detail; + database.submit(() -> { database.finishReward(key.player(), key.achievement(), delivered, deliveryDetail); return null; }) + .whenComplete((ignored, finishError) -> { + if (finishError != null) plugin.getLogger().severe("奖励结果保存失败,PENDING 已保留,禁止自动重放 " + key + ": " + finishError); + result.complete(delivered && finishError == null ? Outcome.COMPLETED : Outcome.REVIEW_REQUIRED); + }); + }, notExecuted, result); + }); + }); + return result; + } + + private void onMain(Runnable work, Runnable abort, CompletableFuture result) { + if (closed) { abort.run(); return; } + try { + mainThread.execute(() -> { + if (closed) { abort.run(); return; } + try { work.run(); } + catch (RuntimeException error) { plugin.getLogger().severe("奖励状态转换异常,保留记录核查: " + error); result.complete(Outcome.REVIEW_REQUIRED); } + }); + } catch (RuntimeException error) { abort.run(); } + } + + private void failBeforeExecution(CompletableFuture result, Key key, Throwable error) { + plugin.getLogger().warning("奖励预约失败,尚未授予进度,允许稍后重试 " + key + ": " + error); + result.complete(Outcome.RETRY_LATER); + } + + private void execute(Player player, AchievementDefinition achievement) { + RewardDefinition reward = achievement.rewards(); + if (reward.experience() > 0) player.giveExp(reward.experience()); + for (RewardDefinition.RewardItem configured : reward.items()) { + Material material = Material.matchMaterial(configured.material()); + if (material == null || configured.amount() < 1 || configured.amount() > 4096) throw new IllegalStateException("奖励物品无效"); + Map overflow = player.getInventory().addItem(new ItemStack(material, configured.amount())); + overflow.values().forEach(item -> player.getWorld().dropItemNaturally(player.getLocation(), item)); + } + for (String raw : reward.commands()) if (!Bukkit.dispatchCommand(Bukkit.getConsoleSender(), renderCommand(raw, player))) throw new IllegalStateException("命令返回失败: " + raw); + if (!reward.completionMessage().isBlank()) player.sendMessage(reward.completionMessage()); + else messages.send(player, "completed", Map.of("name", achievement.name())); + } + + private String renderCommand(String input, Player player) { + if (input.length() > 1024 || input.indexOf('\n') >= 0 || input.indexOf('\r') >= 0) throw new IllegalArgumentException("奖励命令无效"); + return input.replace("{player}", player.getName().replaceAll("[^A-Za-z0-9_]", "")) + .replace("{uuid}", player.getUniqueId().toString()).replaceFirst("^/", ""); + } + @Override public void close() { closed = true; } +} diff --git a/src/main/java/top/itxiaohui/serveradvancements/statistics/StatisticsService.java b/src/main/java/top/itxiaohui/serveradvancements/statistics/StatisticsService.java new file mode 100644 index 0000000..e3338b8 --- /dev/null +++ b/src/main/java/top/itxiaohui/serveradvancements/statistics/StatisticsService.java @@ -0,0 +1,150 @@ +package top.itxiaohui.serveradvancements.statistics; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitTask; +import top.itxiaohui.serveradvancements.database.DatabaseManager; +import java.sql.SQLException; +import java.util.*; +import java.util.concurrent.*; + +/** Versioned snapshots: never hold the cache lock during JDBC work. */ +public final class StatisticsService implements AutoCloseable { + private final JavaPlugin plugin; + private final DatabaseManager database; + private final Object cacheLock = new Object(); + private final Map states = new HashMap<>(); + private final Map sessions = new HashMap<>(); + private final Set activePlayers = new HashSet<>(); + private BukkitTask flushTask; + private CompletableFuture scheduledFlush; + private volatile boolean lastFlushSucceeded = true; + private static final class State { + final Map values = new HashMap<>(); + final Map additions = new HashMap<>(); + final Map maxima = new HashMap<>(); + boolean loaded; + long version; + long savedVersion; + CompletableFuture loading; + } + public StatisticsService(JavaPlugin plugin, DatabaseManager database) { this.plugin = plugin; this.database = database; } + public void start() { + long ticks = Math.clamp(plugin.getConfig().getLong("statistics.flush-interval-seconds", 30), 5, 3600) * 20; + flushTask = Bukkit.getScheduler().runTaskTimer(plugin, () -> { updateOnlineSessions(); flushSoon(); }, ticks, ticks); + } + /** Synchronous diagnostic entry point; runtime joins use loadAsync instead. */ + public void load(UUID id) { + State state; + synchronized (cacheLock) { state = states.computeIfAbsent(id, ignored -> new State()); if (state.loaded) return; } + try { + Map persisted = database.loadStatistics(id); + synchronized (cacheLock) { + if (state.loaded) return; + state.values.putAll(persisted); + state.additions.forEach((key, value) -> state.values.merge(key, value, Double::sum)); + state.maxima.forEach((key, value) -> state.values.merge(key, value, Math::max)); + state.additions.clear(); state.maxima.clear(); state.loaded = true; + } + } catch (SQLException error) { plugin.getLogger().severe("读取统计失败,未就绪数据不会覆盖数据库,将重试 " + id + ": " + error.getMessage()); } + } + public CompletableFuture loadAsync(UUID id) { + synchronized (cacheLock) { + State state = states.computeIfAbsent(id, ignored -> new State()); + if (state.loaded) return CompletableFuture.completedFuture(true); + if (state.loading != null && !state.loading.isDone()) return state.loading; + state.loading = database.submit(() -> { load(id); return isReady(id); }); + return state.loading; + } + } + public CompletableFuture beginSession(Player player) { + UUID id = player.getUniqueId(); + synchronized (cacheLock) { + states.computeIfAbsent(id, ignored -> new State()); + activePlayers.add(id); + if (plugin.getConfig().getBoolean("statistics.online-time-enabled", true)) sessions.putIfAbsent(id, System.nanoTime()); + } + return loadAsync(id); + } + public void endSession(UUID id) { + synchronized (cacheLock) { activePlayers.remove(id); Long start = sessions.remove(id); if (start != null) increment(id, "online_time_ms", Math.max(0, (System.nanoTime() - start) / 1_000_000D)); } + } + public void updateOnlineSessions() { + synchronized (cacheLock) { + long now = System.nanoTime(); + sessions.replaceAll((id, start) -> { increment(id, "online_time_ms", Math.max(0, (now - start) / 1_000_000D)); return now; }); + } + } + public boolean isReady(UUID id) { synchronized (cacheLock) { State state = states.get(id); return state != null && state.loaded; } } + public double increment(UUID id, String key, double amount) { + synchronized (cacheLock) { + if (!Double.isFinite(amount) || amount < 0) return get(id, key); + State state = states.computeIfAbsent(id, ignored -> new State()); + Map target = state.loaded ? state.values : state.additions; + double value = target.getOrDefault(key, 0D) + amount; + if (!Double.isFinite(value)) return get(id, key); + target.put(key, value); state.version++; + return get(id, key); + } + } + public void setMax(UUID id, String key, double value) { + if (!Double.isFinite(value) || value < 0) return; + synchronized (cacheLock) { + State state = states.computeIfAbsent(id, ignored -> new State()); + Map target = state.loaded ? state.values : state.maxima; + if (value > target.getOrDefault(key, 0D)) { target.put(key, value); state.version++; } + } + } + public double get(UUID id, String key) { + synchronized (cacheLock) { + State state = states.get(id); if (state == null) return 0; + return Math.max(state.values.getOrDefault(key, 0D) + state.additions.getOrDefault(key, 0D), state.maxima.getOrDefault(key, 0D)); + } + } + public Map snapshot(UUID id) { synchronized (cacheLock) { State state = states.get(id); return state == null ? Map.of() : Map.copyOf(state.values); } } + public int cachedPlayerCount() { synchronized (cacheLock) { return states.size(); } } + public CompletableFuture flushSoon() { + synchronized (cacheLock) { + if (scheduledFlush != null && !scheduledFlush.isDone()) return scheduledFlush; + scheduledFlush = flushAllAsync(); return scheduledFlush; + } + } + public CompletableFuture flushAllAsync() { + return database.submit(() -> { + flushAsyncBody(); + if (!lastFlushSucceeded) throw new SQLException("有统计尚未保存,备份/关闭不能视为已完整刷盘"); + return null; + }); + } + private void flushAsyncBody() { + List awaiting; + synchronized (cacheLock) { awaiting = states.entrySet().stream().filter(e -> !e.getValue().loaded).map(Map.Entry::getKey).toList(); } + for (UUID id : awaiting) load(id); + lastFlushSucceeded = true; + Map> batch = new HashMap<>(); Map versions = new HashMap<>(); + synchronized (cacheLock) { + states.forEach((id, state) -> { + if (!state.loaded && state.version != state.savedVersion) lastFlushSucceeded = false; + if (state.loaded && state.version != state.savedVersion) { batch.put(id, Map.copyOf(state.values)); versions.put(id, state.version); } + }); + } + try { + if (!batch.isEmpty()) database.saveStatistics(batch); + synchronized (cacheLock) { + versions.forEach((id, version) -> { State state = states.get(id); if (state != null) state.savedVersion = version; }); + states.entrySet().removeIf(entry -> { State state = entry.getValue(); return state.loaded && state.version == state.savedVersion && !activePlayers.contains(entry.getKey()); }); + } + } catch (SQLException error) { lastFlushSucceeded = false; plugin.getLogger().severe("批量保存失败,内存版本保留以重试: " + error.getMessage()); } + } + public void flushBlocking() { + updateOnlineSessions(); + try { flushAllAsync().get(30, TimeUnit.SECONDS); } + catch (Exception error) { throw new IllegalStateException("统计刷盘失败,已保留缓存: " + error.getMessage(), error); } + } + @Override public void close() { + if (flushTask != null) flushTask.cancel(); + synchronized (cacheLock) { for (UUID id : new ArrayList<>(activePlayers)) endSession(id); } + flushBlocking(); + } +} diff --git a/src/main/resources/advancements.yml b/src/main/resources/advancements.yml new file mode 100644 index 0000000..d734660 --- /dev/null +++ b/src/main/resources/advancements.yml @@ -0,0 +1,218 @@ +achievements: + first_join: + name: "首次加入服务器" + description: "欢迎来到服务器" + icon: "minecraft:oak_door" + frame: task + parent: root + display: { x: 1, y: 3 } + hidden: false + show-toast: true + announce-chat: false + enabled: true + conditions: + - { type: first_join } + rewards: + experience: 10 + allow-reclaim: false + items: [] + commands: [] + + first_log: + name: "第一块木头" + description: "累计挖掘 1 个橡木原木" + icon: "minecraft:oak_log" + frame: task + parent: root + display: { x: 1, y: 0 } + enabled: true + conditions: + - { type: mine_block, block: "minecraft:oak_log", amount: 1 } + rewards: { experience: 10, items: [], commands: [] } + + mineral_collector: + name: "矿物收藏家" + description: "累计挖掘 32 个铁矿石" + icon: "minecraft:iron_ore" + frame: goal + parent: first_log + display: { x: 2, y: 0 } + enabled: true + conditions: + - { type: mine_block, block: "minecraft:iron_ore", amount: 32 } + rewards: { experience: 50, items: [], commands: [] } + + diamond_collector: + name: "钻石收藏家" + description: "累计拾取 64 个钻石" + icon: "minecraft:diamond" + frame: goal + parent: mineral_collector + display: { x: 3, y: 0 } + enabled: true + conditions: + - { type: collect_item, item: "minecraft:diamond", amount: 64 } + rewards: + experience: 100 + items: + - { item: "minecraft:emerald", amount: 3 } + commands: [] + + netherite_collector: + name: "下界合金收藏家" + description: "累计拾取 4 个下界合金锭" + icon: "minecraft:netherite_ingot" + frame: challenge + parent: diamond_collector + display: { x: 4, y: 0 } + enabled: true + conditions: + - { type: collect_item, item: "minecraft:netherite_ingot", amount: 4 } + rewards: { experience: 250, items: [], commands: [] } + + first_combat: + name: "初次战斗" + description: "击杀任意一只生物" + icon: "minecraft:iron_sword" + frame: task + parent: root + display: { x: 1, y: -2 } + enabled: true + conditions: + - { type: kill_mob, entity: "*", amount: 1 } + rewards: { experience: 10, items: [], commands: [] } + + zombie_hunter: + name: "僵尸猎人" + description: "累计击杀 25 只僵尸" + icon: "minecraft:rotten_flesh" + frame: goal + parent: first_combat + display: { x: 2, y: -2 } + enabled: true + conditions: + - { type: kill_mob, entity: "minecraft:zombie", amount: 25 } + rewards: { experience: 80, items: [], commands: [] } + + skeleton_slayer: + name: "骷髅克星" + description: "累计击杀 25 只骷髅" + icon: "minecraft:bone" + frame: goal + parent: first_combat + display: { x: 2, y: -1 } + enabled: true + conditions: + - { type: kill_mob, entity: "minecraft:skeleton", amount: 25 } + rewards: { experience: 80, items: [], commands: [] } + + ender_dragon: + name: "末影龙挑战者" + description: "亲手击杀末影龙" + icon: "minecraft:dragon_head" + frame: challenge + parent: zombie_hunter + display: { x: 3, y: -2 } + enabled: true + conditions: + - { type: kill_mob, entity: "minecraft:ender_dragon", amount: 1 } + rewards: { experience: 500, items: [], commands: [] } + + wither_conqueror: + name: "凋灵征服者" + description: "亲手击杀凋灵" + icon: "minecraft:nether_star" + frame: challenge + parent: skeleton_slayer + display: { x: 3, y: -1 } + enabled: true + conditions: + - { type: kill_mob, entity: "minecraft:wither", amount: 1 } + rewards: { experience: 500, items: [], commands: [] } + + first_explore: + name: "初次探索" + description: "累计移动 1000 格" + icon: "minecraft:compass" + frame: task + parent: root + display: { x: 1, y: 1 } + enabled: true + conditions: + - { type: move_distance, amount: 1000 } + rewards: { experience: 30, items: [], commands: [] } + + enter_nether: + name: "进入下界" + description: "首次进入下界" + icon: "minecraft:obsidian" + frame: task + parent: first_explore + display: { x: 2, y: 1 } + enabled: true + conditions: + - { type: visit_dimension, dimension: "minecraft:the_nether" } + rewards: { experience: 50, items: [], commands: [] } + + visit_end: + name: "末地探险家" + description: "首次进入末地" + icon: "minecraft:end_stone" + frame: goal + parent: enter_nether + display: { x: 3, y: 1 } + enabled: true + conditions: + - { type: visit_dimension, dimension: "minecraft:the_end" } + rewards: { experience: 100, items: [], commands: [] } + + traveler: + name: "远行者" + description: "累计移动 10000 格" + icon: "minecraft:elytra" + frame: goal + parent: first_explore + display: { x: 3, y: 2 } + enabled: true + conditions: + - { type: move_distance, amount: 10000 } + rewards: { experience: 150, items: [], commands: [] } + + online_10h: + name: "累计在线 10 小时" + description: "在服务器累计在线 10 小时" + icon: "minecraft:clock" + frame: goal + parent: first_join + display: { x: 2, y: 3 } + enabled: true + conditions: + - { type: online_time, amount: 10, unit: hours } + rewards: { experience: 100, items: [], commands: [] } + + online_100h: + name: "累计在线 100 小时" + description: "在服务器累计在线 100 小时" + icon: "minecraft:clock" + frame: challenge + parent: online_10h + display: { x: 3, y: 3 } + enabled: true + conditions: + - { type: online_time, amount: 100, unit: hours } + rewards: { experience: 1000, items: [], commands: [] } + + survival_master: + name: "完成全部生存成就" + description: "完成木头、矿物、钻石和下界合金成就" + icon: "minecraft:totem_of_undying" + frame: challenge + parent: netherite_collector + display: { x: 5, y: 0 } + enabled: true + conditions: + - { type: complete_achievement, achievement: first_log } + - { type: complete_achievement, achievement: mineral_collector } + - { type: complete_achievement, achievement: diamond_collector } + - { type: complete_achievement, achievement: netherite_collector } + rewards: { experience: 1000, items: [], commands: [] } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml new file mode 100644 index 0000000..8a9f9d8 --- /dev/null +++ b/src/main/resources/config.yml @@ -0,0 +1,24 @@ +language: zh_CN + +root: + id: root + title: "服务器成就树" + description: "记录你在本服务器中的冒险旅程" + icon: "minecraft:nether_star" + background: "minecraft:textures/block/deepslate_tiles.png" + auto-grant: true + +defaults: + show-toast: true + announce-chat: false + allow-reward-reclaim: false + +statistics: + online-time-enabled: true + flush-interval-seconds: 30 + +database: + busy-timeout-millis: 5000 + +logging: + debug: false diff --git a/src/main/resources/fun-advancements-v1.yml b/src/main/resources/fun-advancements-v1.yml new file mode 100644 index 0000000..e5d3d43 --- /dev/null +++ b/src/main/resources/fun-advancements-v1.yml @@ -0,0 +1,1122 @@ +# 74 个趣味成就。精确可统计项自动解锁;特殊行为、建筑与社交项由管理员验收。 +# 启动时一次性补入 advancements.yml;此资源是安装模板,不是第二份运行配置。 +catalog-version: 1 +achievements: + fun_diamond_64: + name: "先富带动后富" + description: "累计从地面拾取 64 个钻石" + icon: "minecraft:diamond" + frame: goal + parent: root + display: { x: 1, y: 0 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"collect_item","item":"minecraft:diamond","amount":64} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_neighborhood_guard: + name: "小区保安" + description: "击杀 30 只僵尸、20 只骷髅和 10 只苦力怕" + icon: "minecraft:iron_sword" + frame: challenge + parent: root + display: { x: 1, y: 1 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"kill_mob","entity":"minecraft:zombie","amount":30} + - {"type":"kill_mob","entity":"minecraft:skeleton","amount":20} + - {"type":"kill_mob","entity":"minecraft:creeper","amount":10} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_bread_factory: + name: "这不是流水线" + description: "累计合成 1024 个面包" + icon: "minecraft:bread" + frame: challenge + parent: root + display: { x: 1, y: 2 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"craft_item","item":"minecraft:bread","amount":1024} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_responsible_rancher: + name: "禁止随地大小牧" + description: "成功繁殖动物 50 次" + icon: "minecraft:wheat" + frame: goal + parent: fun_bread_factory + display: { x: 1, y: 3 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"breed_mob","entity":"*","amount":50} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_level_30: + name: "差一点就附魔了" + description: "历史达到 30 级经验" + icon: "minecraft:enchanting_table" + frame: task + parent: root + display: { x: 1, y: 4 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"experience_level","amount":30} + rewards: { experience: 20, allow-reclaim: false, items: [], commands: [] } + + fun_remote_village: + name: "这里居然还有人住" + description: "到达服主指定的偏远村庄或玩家聚落【人工验收:完成后联系管理员授予】" + icon: "minecraft:oak_door" + frame: task + parent: root + display: { x: 1, y: 5 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_server_archaeologist: + name: "服务器考古学家" + description: "找到三个老建筑遗址,并了解沿途的服务器历史【人工验收:完成后联系管理员授予】" + icon: "minecraft:brush" + frame: goal + parent: fun_remote_village + display: { x: 1, y: 6 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 60, allow-reclaim: false, items: [], commands: [] } + + fun_lonely_peak: + name: "高处不胜寒" + description: "登上服主指定山顶;恭喜,你还得自己下去【人工验收:完成后联系管理员授予】" + icon: "minecraft:snow_block" + frame: task + parent: fun_remote_village + display: { x: 1, y: 7 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_distant_cafe: + name: "地图边缘的咖啡馆" + description: "找到服主设置在远方的小屋或咖啡馆【人工验收:完成后联系管理员授予】" + icon: "minecraft:flower_pot" + frame: task + parent: fun_remote_village + display: { x: 1, y: 8 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_walk_10km: + name: "腿是自己的,路是服主的" + description: "累计移动 10000 格;不计单次至少 100 格的跳变" + icon: "minecraft:leather_boots" + frame: goal + parent: root + display: { x: 1, y: 9 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"move_distance","amount":10000} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_nether_business: + name: "下界出差申请已批准" + description: "首次进入下界,解锁探索分支" + icon: "minecraft:obsidian" + frame: task + parent: fun_walk_10km + display: { x: 1, y: 10 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_dimension","dimension":"minecraft:the_nether"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_new_beginning: + name: "不是终点,是新起点" + description: "进入末地并亲手击杀末影龙" + icon: "minecraft:dragon_head" + frame: challenge + parent: fun_nether_business + display: { x: 1, y: 11 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_dimension","dimension":"minecraft:the_end"} + - {"type":"kill_mob","entity":"minecraft:ender_dragon","amount":1} + rewards: { experience: 100, allow-reclaim: false, items: [], commands: [] } + + fun_jack_of_trades: + name: "什么都懂一点" + description: "完成钻石收集、面包合成、社区防卫和长途探索四项成就" + icon: "minecraft:book" + frame: challenge + parent: root + display: { x: 1, y: 12 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"complete_achievement","achievement":"fun_diamond_64"} + - {"type":"complete_achievement","achievement":"fun_bread_factory"} + - {"type":"complete_achievement","achievement":"fun_neighborhood_guard"} + - {"type":"complete_achievement","achievement":"fun_walk_10km"} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_old_friend: + name: "服里的老熟人" + description: "完成综合入门、动物繁殖、经验等级和三处遗址探索" + icon: "minecraft:name_tag" + frame: challenge + parent: fun_jack_of_trades + display: { x: 1, y: 13 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"complete_achievement","achievement":"fun_jack_of_trades"} + - {"type":"complete_achievement","achievement":"fun_responsible_rancher"} + - {"type":"complete_achievement","achievement":"fun_level_30"} + - {"type":"complete_achievement","achievement":"fun_server_archaeologist"} + rewards: { experience: 100, allow-reclaim: false, items: [], commands: [] } + + fun_first_bed: + name: "今晚终于有床了" + description: "制作第一张床,任意颜色均可【人工验收:完成后联系管理员授予】" + icon: "minecraft:red_bed" + frame: task + parent: root + display: { x: 1, y: 14 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 10, allow-reclaim: false, items: [], commands: [] } + + fun_cooked_food: + name: "拒绝吃生的" + description: "累计烹饪 64 份食物,保留过程或成果供验收【人工验收:完成后联系管理员授予】" + icon: "minecraft:cooked_beef" + frame: task + parent: fun_first_bed + display: { x: 1, y: 15 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_pocket_zoo: + name: "背包里有个动物园" + description: "同时携带五种不同的动物相关物品,由管理员确认【人工验收:完成后联系管理员授予】" + icon: "minecraft:egg" + frame: task + parent: fun_first_bed + display: { x: 1, y: 16 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 20, allow-reclaim: false, items: [], commands: [] } + + fun_varied_diet: + name: "吃点好的" + description: "实际吃下十种不同食物【人工验收:完成后联系管理员授予】" + icon: "minecraft:apple" + frame: task + parent: fun_cooked_food + display: { x: 1, y: 17 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_totem_saved: + name: "保命的钱不能省" + description: "首次触发不死图腾并存活【人工验收:完成后联系管理员授予】" + icon: "minecraft:totem_of_undying" + frame: task + parent: fun_first_bed + display: { x: 1, y: 18 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_water_landing: + name: "自由落体体验券" + description: "从挑战高台落入指定水池并存活;由服主设置安全场地【人工验收:完成后联系管理员授予】" + icon: "minecraft:water_bucket" + frame: task + parent: fun_first_bed + display: { x: 1, y: 19 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_lava_escape: + name: "这水有点烫" + description: "进入岩浆后成功脱险,提供过程证据【人工验收:完成后联系管理员授予】" + icon: "minecraft:lava_bucket" + frame: task + parent: fun_totem_saved + display: { x: 1, y: 20 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_self_made_iron: + name: "出门在外靠自己" + description: "不接受他人物资,自行完成一套铁装备【人工验收:完成后联系管理员授予】" + icon: "minecraft:iron_chestplate" + frame: goal + parent: fun_first_bed + display: { x: 1, y: 21 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_boat_3km: + name: "今天不想走路" + description: "乘船累计航行 3000 格【人工验收:完成后联系管理员授予】" + icon: "minecraft:oak_boat" + frame: goal + parent: fun_walk_10km + display: { x: 1, y: 22 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_forgot_bed: + name: "我的床有自己的想法" + description: "设置重生点后远行,发现忘带床并记录这次冒险【人工验收:完成后联系管理员授予】" + icon: "minecraft:white_bed" + frame: task + parent: fun_first_bed + display: { x: 1, y: 23 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 10, allow-reclaim: false, items: [], commands: [] } + + fun_desert_temple: + name: "沙漠里也有惊喜" + description: "找到并探索一座沙漠神殿【人工验收:完成后联系管理员授予】" + icon: "minecraft:sandstone" + frame: task + parent: fun_remote_village + display: { x: 1, y: 24 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_jungle_temple: + name: "小心脚下" + description: "完整探索一座丛林神庙【人工验收:完成后联系管理员授予】" + icon: "minecraft:mossy_cobblestone" + frame: task + parent: fun_desert_temple + display: { x: 1, y: 25 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_three_shipwrecks: + name: "船长已经下班" + description: "找到三艘位置不同的沉船,提交坐标【人工验收:完成后联系管理员授予】" + icon: "minecraft:spruce_boat" + frame: goal + parent: fun_remote_village + display: { x: 1, y: 26 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_buried_treasure: + name: "X 标记的地方" + description: "根据藏宝图找到并挖出宝藏【人工验收:完成后联系管理员授予】" + icon: "minecraft:map" + frame: goal + parent: fun_three_shipwrecks + display: { x: 1, y: 27 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_ocean_monument: + name: "海底不包呼吸" + description: "找到并探索一座海底神殿【人工验收:完成后联系管理员授予】" + icon: "minecraft:prismarine" + frame: goal + parent: fun_three_shipwrecks + display: { x: 1, y: 28 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_ancient_city: + name: "安静,现在很危险" + description: "进入远古城市并成功返回【人工验收:完成后联系管理员授予】" + icon: "minecraft:sculk" + frame: goal + parent: fun_server_archaeologist + display: { x: 1, y: 29 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 60, allow-reclaim: false, items: [], commands: [] } + + fun_woodland_mansion: + name: "这房子比我家大" + description: "找到并探索一座林地府邸【人工验收:完成后联系管理员授予】" + icon: "minecraft:dark_oak_log" + frame: goal + parent: fun_remote_village + display: { x: 1, y: 30 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_ice_spikes: + name: "冰箱门忘关了" + description: "到达冰刺平原,记录坐标或截图【人工验收:完成后联系管理员授予】" + icon: "minecraft:packed_ice" + frame: task + parent: fun_lonely_peak + display: { x: 1, y: 31 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_mushroom_fields: + name: "蘑菇比树还像树" + description: "到达蘑菇岛,记录坐标或截图【人工验收:完成后联系管理员授予】" + icon: "minecraft:red_mushroom_block" + frame: task + parent: fun_three_shipwrecks + display: { x: 1, y: 32 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_secret_room: + name: "此处禁止施工" + description: "找到服主藏在地图里的秘密房间;无需破坏建筑【人工验收:完成后联系管理员授予】" + icon: "minecraft:chiseled_bookshelf" + frame: goal + parent: fun_distant_cafe + display: { x: 1, y: 33 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_wheat_1000: + name: "一粒种子的野心" + description: "累计从地面收集 1000 个小麦;收获后拾取也计入" + icon: "minecraft:wheat" + frame: goal + parent: fun_bread_factory + display: { x: 1, y: 34 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"collect_item","item":"minecraft:wheat","amount":1000} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_potato_512: + name: "土豆不是货币" + description: "累计从地面收集 512 个马铃薯" + icon: "minecraft:potato" + frame: goal + parent: fun_wheat_1000 + display: { x: 1, y: 35 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"collect_item","item":"minecraft:potato","amount":512} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_melon_1024: + name: "西瓜批发市场" + description: "累计从地面收集 1024 片西瓜" + icon: "minecraft:melon_slice" + frame: goal + parent: fun_wheat_1000 + display: { x: 1, y: 36 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"collect_item","item":"minecraft:melon_slice","amount":1024} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_pumpkin_farm: + name: "南瓜董事长" + description: "建成至少有 100 个南瓜的农场【人工验收:完成后联系管理员授予】" + icon: "minecraft:pumpkin" + frame: goal + parent: fun_wheat_1000 + display: { x: 1, y: 37 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_honey_64: + name: "蜂蜜自由" + description: "累计收集 64 瓶蜂蜜;蜂箱取蜜不属于现有拾取统计,需验收【人工验收:完成后联系管理员授予】" + icon: "minecraft:honey_bottle" + frame: goal + parent: fun_responsible_rancher + display: { x: 1, y: 38 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_rainbow_wool: + name: "羊毛色卡" + description: "收集全部 16 种颜色的羊毛并展示【人工验收:完成后联系管理员授予】" + icon: "minecraft:magenta_wool" + frame: goal + parent: fun_responsible_rancher + display: { x: 1, y: 39 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_three_cats: + name: "猫说这里归它了" + description: "驯服三只猫,确认均属于自己【人工验收:完成后联系管理员授予】" + icon: "minecraft:cod" + frame: task + parent: fun_responsible_rancher + display: { x: 1, y: 40 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_five_wolves: + name: "出门带保镖" + description: "驯服五只狼,确认均属于自己【人工验收:完成后联系管理员授予】" + icon: "minecraft:bone" + frame: task + parent: fun_responsible_rancher + display: { x: 1, y: 41 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_fishing_variety: + name: "鱼没钓到,家当不少" + description: "通过钓鱼获得五种不同物品,提供钓获记录【人工验收:完成后联系管理员授予】" + icon: "minecraft:fishing_rod" + frame: task + parent: fun_responsible_rancher + display: { x: 1, y: 42 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_humane_ranch: + name: "给动物一点体面" + description: "建成有照明、遮雨与分区的牧场【人工验收:完成后联系管理员授予】" + icon: "minecraft:hay_block" + frame: goal + parent: fun_responsible_rancher + display: { x: 1, y: 43 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_first_home: + name: "从火柴盒开始" + description: "建成第一座带门、床和照明的住宅【人工验收:完成后联系管理员授予】" + icon: "minecraft:oak_planks" + frame: task + parent: root + display: { x: 1, y: 44 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 20, allow-reclaim: false, items: [], commands: [] } + + fun_windows_20: + name: "窗户不是装饰" + description: "给住宅安装至少 20 块玻璃【人工验收:完成后联系管理员授予】" + icon: "minecraft:glass" + frame: task + parent: fun_first_home + display: { x: 1, y: 45 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 20, allow-reclaim: false, items: [], commands: [] } + + fun_public_lighting: + name: "夜里终于看得见了" + description: "完成一段公共道路的照明;先取得道路管理者同意【人工验收:完成后联系管理员授予】" + icon: "minecraft:lantern" + frame: goal + parent: fun_first_home + display: { x: 1, y: 46 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_river_bridge: + name: "桥归桥,路归路" + description: "建造一座安全、可通行的跨河桥【人工验收:完成后联系管理员授予】" + icon: "minecraft:stone_bricks" + frame: goal + parent: fun_first_home + display: { x: 1, y: 47 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_railway_500: + name: "铁路不是摆设" + description: "建成至少 500 格的连通可用铁路【人工验收:完成后联系管理员授予】" + icon: "minecraft:rail" + frame: challenge + parent: fun_river_bridge + display: { x: 1, y: 48 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_underground_home: + name: "地下也要有生活" + description: "建造含卧室、仓库和种植区的地下基地【人工验收:完成后联系管理员授予】" + icon: "minecraft:deepslate_bricks" + frame: goal + parent: fun_first_home + display: { x: 1, y: 49 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_organized_storage: + name: "整理,是一种修行" + description: "建成具有明确分类标识的仓库【人工验收:完成后联系管理员授予】" + icon: "minecraft:chest" + frame: task + parent: fun_first_home + display: { x: 1, y: 50 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_six_records: + name: "唱片不负责打怪" + description: "展示六张不同的音乐唱片【人工验收:完成后联系管理员授予】" + icon: "minecraft:jukebox" + frame: goal + parent: fun_organized_storage + display: { x: 1, y: 51 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_flower_garden: + name: "花里胡哨才是家" + description: "在花园中种植十种不同的花【人工验收:完成后联系管理员授予】" + icon: "minecraft:poppy" + frame: task + parent: fun_first_home + display: { x: 1, y: 52 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_preserved_hut: + name: "请勿拆除,具有历史价值" + description: "保留自己的第一间小屋,并设置纪念牌【人工验收:完成后联系管理员授予】" + icon: "minecraft:oak_sign" + frame: goal + parent: fun_first_home + display: { x: 1, y: 53 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_spiders_50: + name: "蜘蛛不是室友" + description: "累计亲手击杀 50 只蜘蛛" + icon: "minecraft:string" + frame: goal + parent: fun_neighborhood_guard + display: { x: 1, y: 54 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"kill_mob","entity":"minecraft:spider","amount":50} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_phantoms_10: + name: "今晚不做梦" + description: "累计亲手击杀 10 只幻翼" + icon: "minecraft:phantom_membrane" + frame: goal + parent: fun_spiders_50 + display: { x: 1, y: 55 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"kill_mob","entity":"minecraft:phantom","amount":10} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_sniper_skeleton: + name: "隔壁的弓箭更准" + description: "从至少 50 格外射杀一只骷髅,提供过程证据【人工验收:完成后联系管理员授予】" + icon: "minecraft:bow" + frame: goal + parent: fun_neighborhood_guard + display: { x: 1, y: 56 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_shield_10: + name: "盾牌不是锅盖" + description: "使用盾牌成功格挡十次攻击【人工验收:完成后联系管理员授予】" + icon: "minecraft:shield" + frame: task + parent: fun_neighborhood_guard + display: { x: 1, y: 57 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_return_to_sender: + name: "让它自己冷静一下" + description: "反弹恶魂火球并以此击杀恶魂【人工验收:完成后联系管理员授予】" + icon: "minecraft:fire_charge" + frame: goal + parent: fun_nether_business + display: { x: 1, y: 58 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 60, allow-reclaim: false, items: [], commands: [] } + + fun_blaze_rods_32: + name: "烈焰人事部" + description: "累计从地面拾取 32 根烈焰棒" + icon: "minecraft:blaze_rod" + frame: goal + parent: fun_nether_business + display: { x: 1, y: 59 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"collect_item","item":"minecraft:blaze_rod","amount":32} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_elder_guardian: + name: "海底清洁工" + description: "亲手击败一只远古守卫者" + icon: "minecraft:wet_sponge" + frame: challenge + parent: fun_ocean_monument + display: { x: 1, y: 60 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"kill_mob","entity":"minecraft:elder_guardian","amount":1} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_wither_boss: + name: "三个头也得排队" + description: "亲手击败一只凋灵" + icon: "minecraft:nether_star" + frame: challenge + parent: fun_neighborhood_guard + display: { x: 1, y: 61 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"kill_mob","entity":"minecraft:wither","amount":1} + rewards: { experience: 100, allow-reclaim: false, items: [], commands: [] } + + fun_piercing_arrow: + name: "箭有自己的想法" + description: "使用弩完成一次穿透多个目标的攻击【人工验收:完成后联系管理员授予】" + icon: "minecraft:crossbow" + frame: goal + parent: fun_sniper_skeleton + display: { x: 1, y: 62 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_light_gear_challenge: + name: "装备差,胆子大" + description: "不穿钻石及以上护甲,完成服主指定挑战副本【人工验收:完成后联系管理员授予】" + icon: "minecraft:chainmail_chestplate" + frame: challenge + parent: fun_neighborhood_guard + display: { x: 1, y: 63 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_welcome_newcomer: + name: "新人接待处" + description: "自愿帮助一位新人完成安家,经对方确认【人工验收:完成后联系管理员授予】" + icon: "minecraft:oak_door" + frame: task + parent: root + display: { x: 1, y: 64 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_lend_a_pickaxe: + name: "借你一把镐" + description: "向新人赠送一套实用工具,经对方确认;不索要回报【人工验收:完成后联系管理员授予】" + icon: "minecraft:iron_pickaxe" + frame: task + parent: fun_welcome_newcomer + display: { x: 1, y: 65 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_public_road: + name: "这条路大家都能走" + description: "参与修建一条公共道路,获得负责人确认【人工验收:完成后联系管理员授予】" + icon: "minecraft:gravel" + frame: goal + parent: fun_welcome_newcomer + display: { x: 1, y: 66 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_community_donation: + name: "免费,但不是垃圾桶" + description: "向公共物资站捐赠一组指定实用物资【人工验收:完成后联系管理员授予】" + icon: "minecraft:barrel" + frame: task + parent: fun_welcome_newcomer + display: { x: 1, y: 67 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_open_house: + name: "我家大门常打开" + description: "举办一次自愿参加的玩家参观活动【人工验收:完成后联系管理员授予】" + icon: "minecraft:birch_door" + frame: task + parent: fun_welcome_newcomer + display: { x: 1, y: 68 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_group_photo: + name: "合影请看这里" + description: "与五名其他玩家在指定地标合影;尊重参与意愿【人工验收:完成后联系管理员授予】" + icon: "minecraft:painting" + frame: task + parent: fun_open_house + display: { x: 1, y: 69 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_event_participant: + name: "差一点就是冠军" + description: "完整参加一次服务器活动,不要求获胜【人工验收:完成后联系管理员授予】" + icon: "minecraft:gold_nugget" + frame: goal + parent: fun_welcome_newcomer + display: { x: 1, y: 70 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_community_builder: + name: "建筑工地有我一份" + description: "参与一次公共建筑项目,经负责人确认【人工验收:完成后联系管理员授予】" + icon: "minecraft:scaffolding" + frame: goal + parent: fun_public_road + display: { x: 1, y: 71 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_original_story: + name: "今天由我来讲故事" + description: "为服务器图书馆写一本原创游戏故事【人工验收:完成后联系管理员授予】" + icon: "minecraft:writable_book" + frame: goal + parent: fun_welcome_newcomer + display: { x: 1, y: 72 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_time_capsule: + name: "多年以后还能找到这里" + description: "在纪念馆留下自己的书、署名和加入日期【人工验收:完成后联系管理员授予】" + icon: "minecraft:written_book" + frame: goal + parent: fun_original_story + display: { x: 1, y: 73 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } diff --git a/src/main/resources/fun-advancements.yml b/src/main/resources/fun-advancements.yml new file mode 100644 index 0000000..b0c53f3 --- /dev/null +++ b/src/main/resources/fun-advancements.yml @@ -0,0 +1,2025 @@ +# 1.2.0 自动优先目录;旧版人工项目保留但默认禁用。 +catalog-version: 2 +achievements: + fun_diamond_64: + name: "先富带动后富" + description: "累计从地面拾取 64 个钻石" + icon: "minecraft:diamond" + frame: goal + parent: root + display: { x: 1, y: 0 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"collect_item","item":"minecraft:diamond","amount":64} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_neighborhood_guard: + name: "小区保安" + description: "击杀 30 只僵尸、20 只骷髅和 10 只苦力怕" + icon: "minecraft:iron_sword" + frame: challenge + parent: root + display: { x: 1, y: 1 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"kill_mob","entity":"minecraft:zombie","amount":30} + - {"type":"kill_mob","entity":"minecraft:skeleton","amount":20} + - {"type":"kill_mob","entity":"minecraft:creeper","amount":10} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_bread_factory: + name: "这不是流水线" + description: "累计合成 1024 个面包" + icon: "minecraft:bread" + frame: challenge + parent: root + display: { x: 1, y: 2 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"craft_item","item":"minecraft:bread","amount":1024} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_responsible_rancher: + name: "禁止随地大小牧" + description: "成功繁殖动物 50 次" + icon: "minecraft:wheat" + frame: goal + parent: root + display: { x: 1, y: 3 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"breed_mob","entity":"*","amount":50} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_level_30: + name: "差一点就附魔了" + description: "历史达到 30 级经验" + icon: "minecraft:enchanting_table" + frame: task + parent: root + display: { x: 1, y: 4 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"experience_level","amount":30} + rewards: { experience: 20, allow-reclaim: false, items: [], commands: [] } + + fun_remote_village: + name: "这里居然还有人住" + description: "进入一处天然生成的村庄范围(不要求偏远)" + icon: "minecraft:oak_door" + frame: task + parent: root + display: { x: 1, y: 5 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_structure","structures":["minecraft:village_plains","minecraft:village_desert","minecraft:village_savanna","minecraft:village_snowy","minecraft:village_taiga"],"amount":1} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_server_archaeologist: + name: "服务器考古学家" + description: "探索三处不同的天然遗迹:神殿或海底废墟;按结构位置去重" + icon: "minecraft:brush" + frame: goal + parent: root + display: { x: 1, y: 6 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_structure","structures":["minecraft:desert_pyramid","minecraft:jungle_pyramid","minecraft:ocean_ruin_cold","minecraft:ocean_ruin_warm"],"amount":3} + rewards: { experience: 60, allow-reclaim: false, items: [], commands: [] } + + fun_lonely_peak: + name: "高处不胜寒" + description: "历史到达 Y≥200 的高处;不限定服主自建山顶" + icon: "minecraft:snow_block" + frame: task + parent: root + display: { x: 1, y: 7 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"altitude","amount":200} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_distant_cafe: + name: "地图边缘的咖啡馆" + description: "找到服主设置在远方的小屋或咖啡馆【可选人工项目,默认关闭】" + icon: "minecraft:flower_pot" + frame: task + parent: root + display: { x: 1, y: 8 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_walk_10km: + name: "腿是自己的,路是服主的" + description: "累计移动 10000 格;不计单次至少 100 格的跳变" + icon: "minecraft:leather_boots" + frame: goal + parent: root + display: { x: 1, y: 9 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"move_distance","amount":10000} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_nether_business: + name: "下界出差申请已批准" + description: "首次进入下界,解锁探索分支" + icon: "minecraft:obsidian" + frame: task + parent: root + display: { x: 1, y: 10 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_dimension","dimension":"minecraft:the_nether"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_new_beginning: + name: "不是终点,是新起点" + description: "进入末地并亲手击杀末影龙" + icon: "minecraft:dragon_head" + frame: challenge + parent: root + display: { x: 1, y: 11 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_dimension","dimension":"minecraft:the_end"} + - {"type":"kill_mob","entity":"minecraft:ender_dragon","amount":1} + rewards: { experience: 100, allow-reclaim: false, items: [], commands: [] } + + fun_jack_of_trades: + name: "什么都懂一点" + description: "完成钻石收集、面包合成、社区防卫和长途探索四项成就" + icon: "minecraft:book" + frame: challenge + parent: root + display: { x: 1, y: 12 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"complete_achievement","achievement":"fun_diamond_64"} + - {"type":"complete_achievement","achievement":"fun_bread_factory"} + - {"type":"complete_achievement","achievement":"fun_neighborhood_guard"} + - {"type":"complete_achievement","achievement":"fun_walk_10km"} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_old_friend: + name: "服里的老熟人" + description: "完成综合入门、繁殖、经验等级、首次合成床;不再依赖人工考古审核" + icon: "minecraft:name_tag" + frame: challenge + parent: root + display: { x: 1, y: 13 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"complete_achievement","achievement":"fun_jack_of_trades"} + - {"type":"complete_achievement","achievement":"fun_responsible_rancher"} + - {"type":"complete_achievement","achievement":"fun_level_30"} + - {"type":"complete_achievement","achievement":"fun_first_bed"} + rewards: { experience: 100, allow-reclaim: false, items: [], commands: [] } + + fun_first_bed: + name: "今晚终于有床了" + description: "亲手合成第一张床,任意颜色均可" + icon: "minecraft:red_bed" + frame: task + parent: root + display: { x: 1, y: 14 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"CRAFT_ITEM","amount":1,"materials":["minecraft:white_bed","minecraft:orange_bed","minecraft:magenta_bed","minecraft:light_blue_bed","minecraft:yellow_bed","minecraft:lime_bed","minecraft:pink_bed","minecraft:gray_bed","minecraft:light_gray_bed","minecraft:cyan_bed","minecraft:purple_bed","minecraft:blue_bed","minecraft:brown_bed","minecraft:green_bed","minecraft:red_bed","minecraft:black_bed"]} + rewards: { experience: 10, allow-reclaim: false, items: [], commands: [] } + + fun_cooked_food: + name: "拒绝吃生的" + description: "从熔炉、烟熏炉等取出累计 64 份已烹饪食物" + icon: "minecraft:cooked_beef" + frame: task + parent: root + display: { x: 1, y: 15 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"cook_food","amount":64} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_pocket_zoo: + name: "背包里有个动物园" + description: "同时持有清单中五种动物相关物品:蛋、羽毛、骨头、线、皮革、墨囊、蜂蜜、鳕鱼" + icon: "minecraft:egg" + frame: task + parent: root + display: { x: 1, y: 16 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:egg","minecraft:feather","minecraft:bone","minecraft:string","minecraft:leather","minecraft:ink_sac","minecraft:honey_bottle","minecraft:cod"],"amount":5,"each":1} + rewards: { experience: 20, allow-reclaim: false, items: [], commands: [] } + + fun_varied_diet: + name: "吃点好的" + description: "安装新版后实际吃下十种不同食物" + icon: "minecraft:apple" + frame: task + parent: root + display: { x: 1, y: 17 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_distinct","event":"eat_food","amount":10} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_totem_saved: + name: "保命的钱不能省" + description: "达成原版进度:使用不死图腾逃过一劫" + icon: "minecraft:totem_of_undying" + frame: task + parent: root + display: { x: 1, y: 18 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:adventure/totem_of_undying"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_water_landing: + name: "自由落体体验券" + description: "从挑战高台落入指定水池并存活;由服主设置安全场地【可选人工项目,默认关闭】" + icon: "minecraft:water_bucket" + frame: task + parent: root + display: { x: 1, y: 19 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_lava_escape: + name: "这水有点烫" + description: "进入岩浆后成功脱险,提供过程证据【可选人工项目,默认关闭】" + icon: "minecraft:lava_bucket" + frame: task + parent: root + display: { x: 1, y: 20 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_self_made_iron: + name: "出门在外靠自己" + description: "背包或身穿同时攒齐铁头盔、胸甲、护腿和靴子;不限制物资来源" + icon: "minecraft:iron_chestplate" + frame: goal + parent: root + display: { x: 1, y: 21 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:iron_helmet","minecraft:iron_chestplate","minecraft:iron_leggings","minecraft:iron_boots"],"amount":4,"each":1} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_boat_3km: + name: "今天不想走路" + description: "原版统计累计乘船航行 3000 格(300000 厘米)" + icon: "minecraft:oak_boat" + frame: goal + parent: root + display: { x: 1, y: 22 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"BOAT_ONE_CM","amount":300000} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_forgot_bed: + name: "我的床有自己的想法" + description: "设置重生点后远行,发现忘带床并记录这次冒险【可选人工项目,默认关闭】" + icon: "minecraft:white_bed" + frame: task + parent: root + display: { x: 1, y: 23 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 10, allow-reclaim: false, items: [], commands: [] } + + fun_desert_temple: + name: "沙漠里也有惊喜" + description: "进入一座天然沙漠神殿的结构范围" + icon: "minecraft:sandstone" + frame: task + parent: root + display: { x: 1, y: 24 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_structure","structures":["minecraft:desert_pyramid"],"amount":1} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_jungle_temple: + name: "小心脚下" + description: "进入一座天然丛林神庙的结构范围" + icon: "minecraft:mossy_cobblestone" + frame: task + parent: root + display: { x: 1, y: 25 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_structure","structures":["minecraft:jungle_pyramid"],"amount":1} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_three_shipwrecks: + name: "船长已经下班" + description: "进入三艘位置不同的天然沉船范围" + icon: "minecraft:spruce_boat" + frame: goal + parent: root + display: { x: 1, y: 26 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_structure","structures":["minecraft:shipwreck","minecraft:shipwreck_beached"],"amount":3} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_buried_treasure: + name: "X 标记的地方" + description: "到达一处天然埋藏宝藏位置;不验证是否使用藏宝图" + icon: "minecraft:map" + frame: goal + parent: root + display: { x: 1, y: 27 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_structure","structures":["minecraft:buried_treasure"],"amount":1} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_ocean_monument: + name: "海底不包呼吸" + description: "进入一座天然海底神殿的结构范围" + icon: "minecraft:prismarine" + frame: goal + parent: root + display: { x: 1, y: 28 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_structure","structures":["minecraft:monument"],"amount":1} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_ancient_city: + name: "安静,现在很危险" + description: "进入一座天然远古城市的结构范围;不要求往返" + icon: "minecraft:sculk" + frame: goal + parent: root + display: { x: 1, y: 29 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_structure","structures":["minecraft:ancient_city"],"amount":1} + rewards: { experience: 60, allow-reclaim: false, items: [], commands: [] } + + fun_woodland_mansion: + name: "这房子比我家大" + description: "进入一座天然林地府邸的结构范围" + icon: "minecraft:dark_oak_log" + frame: goal + parent: root + display: { x: 1, y: 30 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_structure","structures":["minecraft:mansion"],"amount":1} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_ice_spikes: + name: "冰箱门忘关了" + description: "被环境采样记录到达冰刺平原" + icon: "minecraft:packed_ice" + frame: task + parent: root + display: { x: 1, y: 31 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:ice_spikes"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_mushroom_fields: + name: "蘑菇比树还像树" + description: "被环境采样记录到达蘑菇岛" + icon: "minecraft:red_mushroom_block" + frame: task + parent: root + display: { x: 1, y: 32 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:mushroom_fields"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_secret_room: + name: "此处禁止施工" + description: "找到服主藏在地图里的秘密房间;无需破坏建筑【可选人工项目,默认关闭】" + icon: "minecraft:chiseled_bookshelf" + frame: goal + parent: root + display: { x: 1, y: 33 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_wheat_1000: + name: "一粒种子的野心" + description: "累计从地面收集 1000 个小麦;收获后拾取也计入" + icon: "minecraft:wheat" + frame: goal + parent: root + display: { x: 1, y: 34 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"collect_item","item":"minecraft:wheat","amount":1000} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_potato_512: + name: "土豆不是货币" + description: "累计从地面收集 512 个马铃薯" + icon: "minecraft:potato" + frame: goal + parent: root + display: { x: 1, y: 35 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"collect_item","item":"minecraft:potato","amount":512} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_melon_1024: + name: "西瓜批发市场" + description: "累计从地面收集 1024 片西瓜" + icon: "minecraft:melon_slice" + frame: goal + parent: root + display: { x: 1, y: 36 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"collect_item","item":"minecraft:melon_slice","amount":1024} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_pumpkin_farm: + name: "南瓜董事长" + description: "建成至少有 100 个南瓜的农场【可选人工项目,默认关闭】" + icon: "minecraft:pumpkin" + frame: goal + parent: root + display: { x: 1, y: 37 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_honey_64: + name: "蜂蜜自由" + description: "同时在随身物品栏持有 64 瓶蜂蜜,不限制获取方式" + icon: "minecraft:honey_bottle" + frame: goal + parent: root + display: { x: 1, y: 38 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:honey_bottle"],"amount":1,"each":64} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_rainbow_wool: + name: "羊毛色卡" + description: "同时在随身物品栏持有全部 16 色羊毛" + icon: "minecraft:magenta_wool" + frame: goal + parent: root + display: { x: 1, y: 39 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:white_wool","minecraft:orange_wool","minecraft:magenta_wool","minecraft:light_blue_wool","minecraft:yellow_wool","minecraft:lime_wool","minecraft:pink_wool","minecraft:gray_wool","minecraft:light_gray_wool","minecraft:cyan_wool","minecraft:purple_wool","minecraft:blue_wool","minecraft:brown_wool","minecraft:green_wool","minecraft:red_wool","minecraft:black_wool"],"amount":16,"each":1} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_three_cats: + name: "猫说这里归它了" + description: "安装新版后亲自驯服三只猫" + icon: "minecraft:cod" + frame: task + parent: root + display: { x: 1, y: 40 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"tame_animal","amount":3,"subjects":["minecraft:cat"]} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_five_wolves: + name: "出门带保镖" + description: "安装新版后亲自驯服五只狼" + icon: "minecraft:bone" + frame: task + parent: root + display: { x: 1, y: 41 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"tame_animal","amount":5,"subjects":["minecraft:wolf"]} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_fishing_variety: + name: "鱼没钓到,家当不少" + description: "安装新版后通过成功钓获获得五种不同物品" + icon: "minecraft:fishing_rod" + frame: task + parent: root + display: { x: 1, y: 42 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_distinct","event":"fish_item","amount":5} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_humane_ranch: + name: "给动物一点体面" + description: "建成有照明、遮雨与分区的牧场【可选人工项目,默认关闭】" + icon: "minecraft:hay_block" + frame: goal + parent: root + display: { x: 1, y: 43 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_first_home: + name: "从火柴盒开始" + description: "完成开荒建材清单:合成床,放置 64 块木板、1 扇木门和 4 支火把;不鉴定房屋外形" + icon: "minecraft:oak_planks" + frame: task + parent: root + display: { x: 1, y: 44 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"CRAFT_ITEM","amount":1,"materials":["minecraft:white_bed","minecraft:orange_bed","minecraft:magenta_bed","minecraft:light_blue_bed","minecraft:yellow_bed","minecraft:lime_bed","minecraft:pink_bed","minecraft:gray_bed","minecraft:light_gray_bed","minecraft:cyan_bed","minecraft:purple_bed","minecraft:blue_bed","minecraft:brown_bed","minecraft:green_bed","minecraft:red_bed","minecraft:black_bed"]} + - {"type":"event_count","event":"place_block","amount":64,"subjects":["minecraft:oak_planks","minecraft:spruce_planks","minecraft:birch_planks","minecraft:jungle_planks","minecraft:acacia_planks","minecraft:dark_oak_planks","minecraft:mangrove_planks","minecraft:cherry_planks","minecraft:bamboo_planks","minecraft:crimson_planks","minecraft:warped_planks"]} + - {"type":"event_count","event":"place_block","amount":1,"subjects":["minecraft:oak_door","minecraft:spruce_door","minecraft:birch_door","minecraft:jungle_door","minecraft:acacia_door","minecraft:dark_oak_door","minecraft:mangrove_door","minecraft:cherry_door","minecraft:bamboo_door","minecraft:crimson_door","minecraft:warped_door"]} + - {"type":"event_count","event":"place_block","amount":4,"subjects":["minecraft:torch","minecraft:wall_torch"]} + rewards: { experience: 20, allow-reclaim: false, items: [], commands: [] } + + fun_windows_20: + name: "窗户不是装饰" + description: "安装新版后累计放置 20 个玻璃方块或玻璃板,不要求属于住宅" + icon: "minecraft:glass" + frame: task + parent: root + display: { x: 1, y: 45 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"place_block","amount":20,"subjects":["minecraft:glass","minecraft:glass_pane","minecraft:white_stained_glass","minecraft:orange_stained_glass","minecraft:magenta_stained_glass","minecraft:light_blue_stained_glass","minecraft:yellow_stained_glass","minecraft:lime_stained_glass","minecraft:pink_stained_glass","minecraft:gray_stained_glass","minecraft:light_gray_stained_glass","minecraft:cyan_stained_glass","minecraft:purple_stained_glass","minecraft:blue_stained_glass","minecraft:brown_stained_glass","minecraft:green_stained_glass","minecraft:red_stained_glass","minecraft:black_stained_glass","minecraft:white_stained_glass_pane","minecraft:orange_stained_glass_pane","minecraft:magenta_stained_glass_pane","minecraft:light_blue_stained_glass_pane","minecraft:yellow_stained_glass_pane","minecraft:lime_stained_glass_pane","minecraft:pink_stained_glass_pane","minecraft:gray_stained_glass_pane","minecraft:light_gray_stained_glass_pane","minecraft:cyan_stained_glass_pane","minecraft:purple_stained_glass_pane","minecraft:blue_stained_glass_pane","minecraft:brown_stained_glass_pane","minecraft:green_stained_glass_pane","minecraft:red_stained_glass_pane","minecraft:black_stained_glass_pane"]} + rewards: { experience: 20, allow-reclaim: false, items: [], commands: [] } + + fun_public_lighting: + name: "夜里终于看得见了" + description: "完成一段公共道路的照明;先取得道路管理者同意【可选人工项目,默认关闭】" + icon: "minecraft:lantern" + frame: goal + parent: root + display: { x: 1, y: 46 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_river_bridge: + name: "桥归桥,路归路" + description: "建造一座安全、可通行的跨河桥【可选人工项目,默认关闭】" + icon: "minecraft:stone_bricks" + frame: goal + parent: root + display: { x: 1, y: 47 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_railway_500: + name: "铁路不是摆设" + description: "安装新版后累计放置 500 个铁轨类方块;不验证线路连通" + icon: "minecraft:rail" + frame: challenge + parent: root + display: { x: 1, y: 48 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"place_block","amount":500,"subjects":["minecraft:rail","minecraft:powered_rail","minecraft:detector_rail","minecraft:activator_rail"]} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_underground_home: + name: "地下也要有生活" + description: "建造含卧室、仓库和种植区的地下基地【可选人工项目,默认关闭】" + icon: "minecraft:deepslate_bricks" + frame: goal + parent: root + display: { x: 1, y: 49 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_organized_storage: + name: "整理,是一种修行" + description: "亲手合成 16 个箱子及 8 块告示牌,准备分类仓储;不评价整理效果" + icon: "minecraft:chest" + frame: task + parent: root + display: { x: 1, y: 50 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"CRAFT_ITEM","amount":16,"materials":["minecraft:chest"]} + - {"type":"player_statistic","statistic":"CRAFT_ITEM","amount":8,"materials":["minecraft:oak_sign","minecraft:spruce_sign","minecraft:birch_sign","minecraft:jungle_sign","minecraft:acacia_sign","minecraft:dark_oak_sign","minecraft:mangrove_sign","minecraft:cherry_sign","minecraft:bamboo_sign","minecraft:crimson_sign","minecraft:warped_sign"]} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_six_records: + name: "唱片不负责打怪" + description: "同时持有内置唱片清单中六张不同唱片" + icon: "minecraft:jukebox" + frame: goal + parent: root + display: { x: 1, y: 51 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:music_disc_13","minecraft:music_disc_cat","minecraft:music_disc_blocks","minecraft:music_disc_chirp","minecraft:music_disc_far","minecraft:music_disc_mall","minecraft:music_disc_mellohi","minecraft:music_disc_stal","minecraft:music_disc_strad","minecraft:music_disc_ward","minecraft:music_disc_11","minecraft:music_disc_wait","minecraft:music_disc_pigstep","minecraft:music_disc_otherside","minecraft:music_disc_5","minecraft:music_disc_relic"],"amount":6,"each":1} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_flower_garden: + name: "花里胡哨才是家" + description: "安装新版后实际种下十种清单内不同的花;不要求位于同一花园" + icon: "minecraft:poppy" + frame: task + parent: root + display: { x: 1, y: 52 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_distinct","event":"place_block","amount":10,"subjects":["minecraft:dandelion","minecraft:poppy","minecraft:blue_orchid","minecraft:allium","minecraft:azure_bluet","minecraft:red_tulip","minecraft:orange_tulip","minecraft:white_tulip","minecraft:pink_tulip","minecraft:oxeye_daisy","minecraft:cornflower","minecraft:lily_of_the_valley","minecraft:wither_rose","minecraft:sunflower","minecraft:lilac","minecraft:rose_bush","minecraft:peony"]} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_preserved_hut: + name: "请勿拆除,具有历史价值" + description: "保留自己的第一间小屋,并设置纪念牌【可选人工项目,默认关闭】" + icon: "minecraft:oak_sign" + frame: goal + parent: root + display: { x: 1, y: 53 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_spiders_50: + name: "蜘蛛不是室友" + description: "累计亲手击杀 50 只蜘蛛" + icon: "minecraft:string" + frame: goal + parent: root + display: { x: 1, y: 54 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"kill_mob","entity":"minecraft:spider","amount":50} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_phantoms_10: + name: "今晚不做梦" + description: "累计亲手击杀 10 只幻翼" + icon: "minecraft:phantom_membrane" + frame: goal + parent: root + display: { x: 1, y: 55 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"kill_mob","entity":"minecraft:phantom","amount":10} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_sniper_skeleton: + name: "隔壁的弓箭更准" + description: "达成原版狙击手进度:从至少 50 格外射杀骷髅" + icon: "minecraft:bow" + frame: goal + parent: root + display: { x: 1, y: 56 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:adventure/sniper_duel"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_shield_10: + name: "盾牌不是锅盖" + description: "原版盾牌格挡伤害统计达到 100(原版十分之一伤害点计量)" + icon: "minecraft:shield" + frame: task + parent: root + display: { x: 1, y: 57 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"DAMAGE_BLOCKED_BY_SHIELD","amount":100} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_return_to_sender: + name: "让它自己冷静一下" + description: "达成原版见鬼去吧进度:反弹恶魂火球并击杀它" + icon: "minecraft:fire_charge" + frame: goal + parent: root + display: { x: 1, y: 58 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:nether/return_to_sender"} + rewards: { experience: 60, allow-reclaim: false, items: [], commands: [] } + + fun_blaze_rods_32: + name: "烈焰人事部" + description: "累计从地面拾取 32 根烈焰棒" + icon: "minecraft:blaze_rod" + frame: goal + parent: root + display: { x: 1, y: 59 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"collect_item","item":"minecraft:blaze_rod","amount":32} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_elder_guardian: + name: "海底清洁工" + description: "亲手击败一只远古守卫者" + icon: "minecraft:wet_sponge" + frame: challenge + parent: root + display: { x: 1, y: 60 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"kill_mob","entity":"minecraft:elder_guardian","amount":1} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_wither_boss: + name: "三个头也得排队" + description: "亲手击败一只凋灵" + icon: "minecraft:nether_star" + frame: challenge + parent: root + display: { x: 1, y: 61 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"kill_mob","entity":"minecraft:wither","amount":1} + rewards: { experience: 100, allow-reclaim: false, items: [], commands: [] } + + fun_piercing_arrow: + name: "箭有自己的想法" + description: "达成原版一箭双雕进度:用穿透弩一箭击杀两只幻翼" + icon: "minecraft:crossbow" + frame: goal + parent: root + display: { x: 1, y: 62 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:adventure/two_birds_one_arrow"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_light_gear_challenge: + name: "装备差,胆子大" + description: "不穿钻石及以上护甲,完成服主指定挑战副本【可选人工项目,默认关闭】" + icon: "minecraft:chainmail_chestplate" + frame: challenge + parent: root + display: { x: 1, y: 63 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 80, allow-reclaim: false, items: [], commands: [] } + + fun_welcome_newcomer: + name: "新人接待处" + description: "自愿帮助一位新人完成安家,经对方确认【可选人工项目,默认关闭】" + icon: "minecraft:oak_door" + frame: task + parent: root + display: { x: 1, y: 64 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_lend_a_pickaxe: + name: "借你一把镐" + description: "向新人赠送一套实用工具,经对方确认;不索要回报【可选人工项目,默认关闭】" + icon: "minecraft:iron_pickaxe" + frame: task + parent: root + display: { x: 1, y: 65 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_public_road: + name: "这条路大家都能走" + description: "参与修建一条公共道路,获得负责人确认【可选人工项目,默认关闭】" + icon: "minecraft:gravel" + frame: goal + parent: root + display: { x: 1, y: 66 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_community_donation: + name: "免费,但不是垃圾桶" + description: "向公共物资站捐赠一组指定实用物资【可选人工项目,默认关闭】" + icon: "minecraft:barrel" + frame: task + parent: root + display: { x: 1, y: 67 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_open_house: + name: "我家大门常打开" + description: "举办一次自愿参加的玩家参观活动【可选人工项目,默认关闭】" + icon: "minecraft:birch_door" + frame: task + parent: root + display: { x: 1, y: 68 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_group_photo: + name: "合影请看这里" + description: "与五名其他玩家在指定地标合影;尊重参与意愿【可选人工项目,默认关闭】" + icon: "minecraft:painting" + frame: task + parent: root + display: { x: 1, y: 69 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + fun_event_participant: + name: "差一点就是冠军" + description: "完整参加一次服务器活动,不要求获胜【可选人工项目,默认关闭】" + icon: "minecraft:gold_nugget" + frame: goal + parent: root + display: { x: 1, y: 70 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_community_builder: + name: "建筑工地有我一份" + description: "参与一次公共建筑项目,经负责人确认【可选人工项目,默认关闭】" + icon: "minecraft:scaffolding" + frame: goal + parent: root + display: { x: 1, y: 71 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + fun_original_story: + name: "今天由我来讲故事" + description: "为服务器图书馆写一本原创游戏故事【可选人工项目,默认关闭】" + icon: "minecraft:writable_book" + frame: goal + parent: root + display: { x: 1, y: 72 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + fun_time_capsule: + name: "多年以后还能找到这里" + description: "在纪念馆留下自己的书、署名和加入日期【可选人工项目,默认关闭】" + icon: "minecraft:written_book" + frame: goal + parent: root + display: { x: 1, y: 73 } + enabled: false + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"manual"} + rewards: { experience: 40, allow-reclaim: false, items: [], commands: [] } + + auto_jumps: + name: "膝盖还好吗" + description: "累计跳跃 1000 次" + icon: "minecraft:rabbit_foot" + frame: task + parent: root + display: { x: 1, y: 74 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"JUMP","amount":1000} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_sprint: + name: "风一样的方块人" + description: "累计疾跑 10 公里" + icon: "minecraft:sugar" + frame: task + parent: root + display: { x: 1, y: 75 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"SPRINT_ONE_CM","amount":1000000} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_crouch: + name: "悄悄地进村" + description: "累计潜行移动 500 格" + icon: "minecraft:leather_boots" + frame: task + parent: root + display: { x: 1, y: 76 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"CROUCH_ONE_CM","amount":50000} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_swim: + name: "泳池已经装不下你" + description: "累计游泳 1000 格" + icon: "minecraft:tropical_fish" + frame: task + parent: root + display: { x: 1, y: 77 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"SWIM_ONE_CM","amount":100000} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_minecart: + name: "下一站没有终点" + description: "累计乘矿车移动 3000 格" + icon: "minecraft:minecart" + frame: task + parent: root + display: { x: 1, y: 78 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"MINECART_ONE_CM","amount":300000} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_horse: + name: "这匹马有编制" + description: "累计骑马移动 2000 格" + icon: "minecraft:saddle" + frame: task + parent: root + display: { x: 1, y: 79 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"HORSE_ONE_CM","amount":200000} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_elytra: + name: "今天也不走正门" + description: "累计鞘翅飞行 10 公里" + icon: "minecraft:elytra" + frame: task + parent: root + display: { x: 1, y: 80 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"AVIATE_ONE_CM","amount":1000000} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_climb: + name: "楼梯对你没有吸引力" + description: "累计攀爬 500 格" + icon: "minecraft:ladder" + frame: task + parent: root + display: { x: 1, y: 81 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"CLIMB_ONE_CM","amount":50000} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_strider: + name: "岩浆专线乘客" + description: "累计骑炽足兽移动 1000 格" + icon: "minecraft:warped_fungus_on_a_stick" + frame: task + parent: root + display: { x: 1, y: 82 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"STRIDER_ONE_CM","amount":100000} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_fish100: + name: "愿者上钩一百次" + description: "原版成功钓鱼统计达到 100" + icon: "minecraft:fishing_rod" + frame: task + parent: root + display: { x: 1, y: 83 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"FISH_CAUGHT","amount":100} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_trade50: + name: "村民看见你就上班" + description: "与村民成功交易 50 次" + icon: "minecraft:emerald" + frame: task + parent: root + display: { x: 1, y: 84 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"TRADED_WITH_VILLAGER","amount":50} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_enchant10: + name: "附魔台的常客" + description: "完成 10 次物品附魔" + icon: "minecraft:enchanting_table" + frame: task + parent: root + display: { x: 1, y: 85 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"ITEM_ENCHANTED","amount":10} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_bells: + name: "全村都知道你来了" + description: "敲钟 100 次" + icon: "minecraft:bell" + frame: task + parent: root + display: { x: 1, y: 86 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"BELL_RING","amount":100} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_notes: + name: "音乐可能不是你的错" + description: "演奏音符盒 100 次" + icon: "minecraft:note_block" + frame: task + parent: root + display: { x: 1, y: 87 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"NOTEBLOCK_PLAYED","amount":100} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_records: + name: "点歌台营业中" + description: "播放唱片 10 次" + icon: "minecraft:jukebox" + frame: task + parent: root + display: { x: 1, y: 88 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"RECORD_PLAYED","amount":10} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_sleep: + name: "床才是终极装备" + description: "原版入睡统计达到 10 次" + icon: "minecraft:blue_bed" + frame: task + parent: root + display: { x: 1, y: 89 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"SLEEP_IN_BED","amount":10} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_anvil: + name: "铁砧正在申请工伤" + description: "与铁砧交互 20 次" + icon: "minecraft:anvil" + frame: task + parent: root + display: { x: 1, y: 90 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"INTERACT_WITH_ANVIL","amount":20} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_potted: + name: "阳台承包商" + description: "向花盆种入植物 16 次" + icon: "minecraft:flower_pot" + frame: task + parent: root + display: { x: 1, y: 91 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"FLOWER_POTTED","amount":16} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_raid: + name: "本村荣誉保安" + description: "原版袭击胜利统计达到 1" + icon: "minecraft:white_banner" + frame: task + parent: root + display: { x: 1, y: 92 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"RAID_WIN","amount":1} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_brewing: + name: "炼药室的新员工" + description: "与酿造台交互 10 次;不冒充酿出药水次数" + icon: "minecraft:brewing_stand" + frame: task + parent: root + display: { x: 1, y: 93 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"player_statistic","statistic":"BREWINGSTAND_INTERACTION","amount":10} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_fortress: + name: "下界也有房地产" + description: "进入原版进度认可的下界要塞" + icon: "minecraft:nether_bricks" + frame: goal + parent: root + display: { x: 1, y: 94 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:nether/find_fortress"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + auto_debris: + name: "古代人的零花钱" + description: "获得远古残骸并达成对应原版进度" + icon: "minecraft:ancient_debris" + frame: goal + parent: root + display: { x: 1, y: 95 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:nether/obtain_ancient_debris"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + auto_crying: + name: "黑曜石也会哭" + description: "获得哭泣的黑曜石并达成对应原版进度" + icon: "minecraft:crying_obsidian" + frame: goal + parent: root + display: { x: 1, y: 96 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:nether/obtain_crying_obsidian"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + auto_hero: + name: "村民今天有折扣" + description: "达成原版村庄英雄进度" + icon: "minecraft:emerald" + frame: goal + parent: root + display: { x: 1, y: 97 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:adventure/hero_of_the_village"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + auto_tame: + name: "它好像认得你" + description: "达成原版驯服动物进度" + icon: "minecraft:bone" + frame: goal + parent: root + display: { x: 1, y: 98 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:husbandry/tame_an_animal"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + auto_seed: + name: "明天的饭有着落了" + description: "达成原版种下种子的进度" + icon: "minecraft:wheat_seeds" + frame: goal + parent: root + display: { x: 1, y: 99 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:husbandry/plant_seed"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + auto_hoe: + name: "这把锄头有点贵" + description: "达成原版下界合金锄进度" + icon: "minecraft:netherite_hoe" + frame: goal + parent: root + display: { x: 1, y: 100 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:husbandry/obtain_netherite_hoe"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + auto_wings: + name: "快递员正式上岗" + description: "达成原版获得鞘翅进度" + icon: "minecraft:elytra" + frame: goal + parent: root + display: { x: 1, y: 101 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:end/elytra"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + auto_levitate: + name: "电梯维修中" + description: "达成原版在末地漂浮挑战进度" + icon: "minecraft:shulker_shell" + frame: goal + parent: root + display: { x: 1, y: 102 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:end/levitate"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + auto_spyglass: + name: "看清楚再打" + description: "用望远镜观察末影龙并达成对应原版进度" + icon: "minecraft:spyglass" + frame: goal + parent: root + display: { x: 1, y: 103 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"vanilla_advancement","advancement":"minecraft:adventure/spyglass_at_dragon"} + rewards: { experience: 50, allow-reclaim: false, items: [], commands: [] } + + auto_wood_palette: + name: "木匠的色卡" + description: "同时携带八种不同木板" + icon: "minecraft:oak_planks" + frame: task + parent: root + display: { x: 1, y: 104 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:oak_planks","minecraft:spruce_planks","minecraft:birch_planks","minecraft:jungle_planks","minecraft:acacia_planks","minecraft:dark_oak_planks","minecraft:mangrove_planks","minecraft:cherry_planks","minecraft:bamboo_planks","minecraft:crimson_planks","minecraft:warped_planks"],"amount":8,"each":1} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_miner_pockets: + name: "口袋里有半座矿山" + description: "同时持有铁铜金粗矿、红石、青金石、煤、钻石、绿宝石和石英" + icon: "minecraft:raw_iron" + frame: task + parent: root + display: { x: 1, y: 105 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:raw_iron","minecraft:raw_copper","minecraft:raw_gold","minecraft:redstone","minecraft:lapis_lazuli","minecraft:coal","minecraft:diamond","minecraft:emerald","minecraft:quartz"],"amount":9,"each":1} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_enchanted_book: + name: "书里真的有力量" + description: "随身持有一本附魔书" + icon: "minecraft:enchanted_book" + frame: task + parent: root + display: { x: 1, y: 106 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:enchanted_book"],"amount":1,"each":1} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_saddles: + name: "骑乘业务扩张中" + description: "随身持有三个鞍" + icon: "minecraft:saddle" + frame: task + parent: root + display: { x: 1, y: 107 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:saddle"],"amount":1,"each":3} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_amethyst: + name: "叮叮当当一整组" + description: "随身持有 64 个紫水晶碎片" + icon: "minecraft:amethyst_shard" + frame: task + parent: root + display: { x: 1, y: 108 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:amethyst_shard"],"amount":1,"each":64} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_echo: + name: "地底寄来的回声" + description: "随身持有 8 个回响碎片" + icon: "minecraft:echo_shard" + frame: task + parent: root + display: { x: 1, y: 109 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:echo_shard"],"amount":1,"each":8} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_nautilus: + name: "海螺里的声音" + description: "随身持有 8 个鹦鹉螺壳" + icon: "minecraft:nautilus_shell" + frame: task + parent: root + display: { x: 1, y: 110 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:nautilus_shell"],"amount":1,"each":8} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_trident: + name: "海王的备用餐具" + description: "随身持有三叉戟" + icon: "minecraft:trident" + frame: task + parent: root + display: { x: 1, y: 111 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:trident"],"amount":1,"each":1} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_shulkers: + name: "移动仓库开张" + description: "随身持有 16 个潜影壳" + icon: "minecraft:shulker_shell" + frame: task + parent: root + display: { x: 1, y: 112 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:shulker_shell"],"amount":1,"each":16} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_trims: + name: "盔甲也要穿搭" + description: "同时持有哨兵、沙丘、监守和尖塔四种锻造模板" + icon: "minecraft:sentry_armor_trim_smithing_template" + frame: task + parent: root + display: { x: 1, y: 113 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"inventory_set","items":["minecraft:sentry_armor_trim_smithing_template","minecraft:dune_armor_trim_smithing_template","minecraft:ward_armor_trim_smithing_template","minecraft:spire_armor_trim_smithing_template"],"amount":4,"each":1} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_badlands: + name: "红土不用滤镜" + description: "环境采样记录到达 badlands 生物群系" + icon: "minecraft:terracotta" + frame: task + parent: root + display: { x: 1, y: 114 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:badlands"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_cherry_grove: + name: "樱花开到你面前" + description: "环境采样记录到达 cherry_grove 生物群系" + icon: "minecraft:cherry_sapling" + frame: task + parent: root + display: { x: 1, y: 115 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:cherry_grove"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_deep_dark: + name: "声音请调到最小" + description: "环境采样记录到达 deep_dark 生物群系" + icon: "minecraft:sculk" + frame: task + parent: root + display: { x: 1, y: 116 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:deep_dark"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_mangrove_swamp: + name: "树根比路还多" + description: "环境采样记录到达 mangrove_swamp 生物群系" + icon: "minecraft:mangrove_roots" + frame: task + parent: root + display: { x: 1, y: 117 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:mangrove_swamp"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_lush_caves: + name: "地底居然有花园" + description: "环境采样记录到达 lush_caves 生物群系" + icon: "minecraft:glow_berries" + frame: task + parent: root + display: { x: 1, y: 118 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:lush_caves"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_dripstone_caves: + name: "天花板有点尖" + description: "环境采样记录到达 dripstone_caves 生物群系" + icon: "minecraft:pointed_dripstone" + frame: task + parent: root + display: { x: 1, y: 119 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:dripstone_caves"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_snowy_slopes: + name: "雪山慢递" + description: "环境采样记录到达 snowy_slopes 生物群系" + icon: "minecraft:snowball" + frame: task + parent: root + display: { x: 1, y: 120 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:snowy_slopes"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_warped_forest: + name: "蓝色森林不卖奶茶" + description: "环境采样记录到达 warped_forest 生物群系" + icon: "minecraft:warped_fungus" + frame: task + parent: root + display: { x: 1, y: 121 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:warped_forest"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_crimson_forest: + name: "红色森林不卖草莓" + description: "环境采样记录到达 crimson_forest 生物群系" + icon: "minecraft:crimson_fungus" + frame: task + parent: root + display: { x: 1, y: 122 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:crimson_forest"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_basalt_deltas: + name: "鞋底快熟了" + description: "环境采样记录到达 basalt_deltas 生物群系" + icon: "minecraft:basalt" + frame: task + parent: root + display: { x: 1, y: 123 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"visit_biome","biome":"minecraft:basalt_deltas"} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_eat64: + name: "干饭也算正经事" + description: "安装新版后实际吃下 64 份食物" + icon: "minecraft:cooked_porkchop" + frame: task + parent: root + display: { x: 1, y: 124 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"eat_food","amount":64} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_eat20: + name: "菜单已经翻到第二页" + description: "安装新版后实际吃下 20 种不同食物" + icon: "minecraft:golden_carrot" + frame: task + parent: root + display: { x: 1, y: 125 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_distinct","event":"eat_food","amount":20} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_cook256: + name: "食堂今天我值班" + description: "安装新版后从烹饪设备取出 256 份食物" + icon: "minecraft:smoker" + frame: task + parent: root + display: { x: 1, y: 126 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"cook_food","amount":256} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_cook5: + name: "火候各有讲究" + description: "安装新版后取出五种不同的烹饪食物" + icon: "minecraft:cooked_salmon" + frame: task + parent: root + display: { x: 1, y: 127 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_distinct","event":"cook_food","amount":5} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_fish256: + name: "鱼塘股东" + description: "安装新版后成功钓获累计 256 个物品" + icon: "minecraft:fishing_rod" + frame: task + parent: root + display: { x: 1, y: 128 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"fish_item","amount":256} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_fish10: + name: "水底杂货铺" + description: "安装新版后成功钓获十种不同物品" + icon: "minecraft:lily_pad" + frame: task + parent: root + display: { x: 1, y: 129 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_distinct","event":"fish_item","amount":10} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_tame10: + name: "朋友圈开始长毛" + description: "安装新版后亲自成功驯服十只动物" + icon: "minecraft:lead" + frame: task + parent: root + display: { x: 1, y: 130 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"tame_animal","amount":10} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_place1000: + name: "一块一块垒起来" + description: "安装新版后实际放置 1000 个方块;拆后重放也计数" + icon: "minecraft:bricks" + frame: task + parent: root + display: { x: 1, y: 131 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"place_block","amount":1000} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_glass100: + name: "采光优先" + description: "安装新版后实际放置 100 块透明玻璃" + icon: "minecraft:glass" + frame: task + parent: root + display: { x: 1, y: 132 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_count","event":"place_block","amount":100,"subjects":["minecraft:glass"]} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } + + auto_flowers16: + name: "花店终于进齐货" + description: "安装新版后实际种下清单中 16 种不同的花" + icon: "minecraft:flower_pot" + frame: task + parent: root + display: { x: 1, y: 133 } + enabled: true + hidden: false + show-toast: true + announce-chat: false + conditions: + - {"type":"event_distinct","event":"place_block","amount":16,"subjects":["minecraft:dandelion","minecraft:poppy","minecraft:blue_orchid","minecraft:allium","minecraft:azure_bluet","minecraft:red_tulip","minecraft:orange_tulip","minecraft:white_tulip","minecraft:pink_tulip","minecraft:oxeye_daisy","minecraft:cornflower","minecraft:lily_of_the_valley","minecraft:wither_rose","minecraft:sunflower","minecraft:lilac","minecraft:rose_bush","minecraft:peony"]} + rewards: { experience: 30, allow-reclaim: false, items: [], commands: [] } diff --git a/src/main/resources/messages.yml b/src/main/resources/messages.yml new file mode 100644 index 0000000..591bf57 --- /dev/null +++ b/src/main/resources/messages.yml @@ -0,0 +1,17 @@ +prefix: "&8[&6服务器成就&8] &r" +no-permission: "&c你没有权限执行此操作。" +player-only: "&c该命令只能由游戏内玩家执行。" +unknown-achievement: "&c不存在成就:{id}" +invalid-player: "&c找不到玩家:{player}" +granted: "&a已向 {player} 授予成就 {id}。" +revoked: "&e已撤销 {player} 的成就 {id}(累计统计未清除)。" +completed: "&a你完成了服务器成就:&6{name}" +reloaded: "&a配置未发生定义变化;消息已重载,当前有 {count} 个有效成就。" +reload-failed: "&c配置重载失败,继续使用旧定义。详情见控制台。" +reload-restart-required: "&e配置校验通过,但 Advancement 定义发生变化。为保证安全,本次未应用;请正常重启服务器。" +already-completed: "&e{player} 已经完成成就 {id},未重复发放奖励。" +created: "&a已在 advancements.yml 创建成就 {id},请编辑后执行 /isa reload。" +deleted: "&e已删除成就 {id},请执行 /isa reload 应用。" +delete-confirm: "&c再次执行 /isa delete {id} confirm 确认删除。玩家原版进度不会被批量清理。" +backup-created: "&a备份已创建:{path}" +validation-ok: "&a配置校验通过,共 {count} 个成就。" diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..c67d789 --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,29 @@ +name: ItxiaohuiServerAdvancements +version: '${version}' +main: top.itxiaohui.serveradvancements.ItxiaohuiServerAdvancements +api-version: '1.21' +description: 使用 Minecraft 原版进度界面的服务器成就树 +author: itxiaohui +load: POSTWORLD +commands: + isa: + description: 服务器成就树管理命令 + usage: /isa help + aliases: [itxiaohuiadvancements] +permissions: + itxiaohui.serveradvancements.admin: + description: 管理服务器成就树全部功能 + default: op + children: + itxiaohui.serveradvancements.give: true + itxiaohui.serveradvancements.revoke: true + itxiaohui.serveradvancements.view: true + itxiaohui.serveradvancements.give: + description: 手动授予服务器成就 + default: op + itxiaohui.serveradvancements.revoke: + description: 撤销服务器成就 + default: op + itxiaohui.serveradvancements.view: + description: 查看玩家成就统计 + default: op diff --git a/src/test/java/top/itxiaohui/serveradvancements/model/ConditionDefinitionTest.java b/src/test/java/top/itxiaohui/serveradvancements/model/ConditionDefinitionTest.java new file mode 100644 index 0000000..0779373 --- /dev/null +++ b/src/test/java/top/itxiaohui/serveradvancements/model/ConditionDefinitionTest.java @@ -0,0 +1,28 @@ +package top.itxiaohui.serveradvancements.model; + +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +class ConditionDefinitionTest { + @Test void convertsOnlineHoursToMilliseconds() { + ConditionDefinition condition = new ConditionDefinition(ConditionType.ONLINE_TIME, + Map.of("amount", 10, "unit", "hours")); + assertEquals(36_000_000D, condition.target()); + assertEquals("online_time_ms", condition.statisticKey()); + } + + @Test void buildsStableQualifiedStatisticKeys() { + ConditionDefinition mined = new ConditionDefinition(ConditionType.MINE_BLOCK, + Map.of("block", "minecraft:stone", "amount", 1000)); + assertEquals("mine_block:minecraft:stone", mined.statisticKey()); + assertEquals(1000D, mined.target()); + } + + @Test void parsesConditionNamesCaseInsensitively() { + assertEquals(ConditionType.COMPLETE_ACHIEVEMENT, ConditionType.parse("complete_achievement")); + assertThrows(IllegalArgumentException.class, () -> ConditionType.parse("not_real")); + } +}