Dungeon Trials
Minecraft Paper 插件 — 自动生成试炼地牢、基于波次的怪物生成、5 级进度系统,以及可选的无限模式。
简介
Dungeon Trials 是一款面向 Paper 服务器的“试炼地牢”插件。当玩家执行 /dt start 命令时,系统会生成一个独立的试炼地牢(默认情况下使用共享世界网格,每个地牢分配一个网格单元),自动放置原版 Minecraft 试炼密室结构,并启动由基于波次的怪物生成 + 等级进度组成的战斗循环。玩家可以通过满足要求来推进等级(或通过 /dt next 在地牢内手动升级)。在清除第 5 级后,玩家可以选择进入无限模式。
核心功能
- 单人 / 多人合作 — 房主可以邀请访客加入其地牢(最多
settings.max-visitors 人,默认为 3 人)。
- 5 个明确定义的等级(第 6 级及以上使用隐式配置,每级所需的清除目标数量增加 12 个)。
- 基于波次的生成 — 当玩家移动距离起始点超过
DISTANCE_THRESHOLD=5 格时触发。
- 动态难度缩放 — 自动为第 6 级及以上的多玩家会话提升生成强度。
- 数据持久化 — SQLite (WAL) + Caffeine 缓存,确保记录在服务器重启后得以保留。
- 国际化 (i18n) — 支持英文 + 繁体中文,可通过
settings.locale 进行配置。
- BossBar 进度显示 — 实时显示击杀进度,采用三色系统(绿色 / 黄色 / 红色)。
- 孤儿清理 — 在启动和禁用阶段自动扫描残留的世界文件。
技术栈
| 项目 |
版本 / 描述 |
| Minecraft |
Paper 26.1.2 |
| Java |
25(通过 toolchain 锁定) |
| 构建工具 |
Gradle 9.5.1(启用配置缓存) |
| Shadow JAR |
9.4.2 |
| 开发插件 |
xyz.jpenilla.run-paper 3.0.2 |
| 包名 |
org.swim.dungeonTrials |
| Maven group |
org.swim |
| 版本号 |
1.0-SNAPSHOT |
| 持久化 |
SQLite (WAL) + Caffeine 缓存 |
| 国际化 |
MiniMessage (Adventure API) + 自定义 YAML |
| 注解 |
Lombok (@Getter) + JSpecify (@NonNull) |
| 权限兼容性 |
LuckPerms API 5.5(运行时下载) |
依赖解析机制
所有运行时依赖项(sqlite-jdbc, caffeine, luckperms-api)均声明为 compileOnly,并且不会打包进 fat jar 中。相反,DungeonTrialsLoader 实现了 Paper 的 PluginLoader 接口,以便在 classloader(...) 阶段通过 MavenLibraryResolver 从 Maven Central 动态下载它们。
优点:Jar 包体积保持极小,且依赖去重由 Paper 处理。
缺点:服务器在初始启动时需要网络连接。
项目结构
src/main/
├── java/org/swim/dungeonTrials/
│ ├── DungeonTrials.java ← 主插件类
│ ├── DungeonTrialsLoader.java ← Paper PluginLoader
│ ├── config/
│ │ ├── ConfigManager.java ← 配置 + 国际化
│ │ └── LevelConfig.java ← record
│ ├── database/
│ │ └── DatabaseManager.java ← SQLite + Caffeine + 架构迁移
│ ├── model/
│ │ ├── ActiveSession.java ← 活跃会话 (arenaId, worldName, structureId, origin*)
│ │ ├── SessionHistory.java ← 历史记录 (structureId, highestLevel, ...)
│ │ ├── MobSpawnRule.java ← record(type + profile)
│ │ ├── MobSpawnState.java ← 生成状态计数器
│ │ └── SpawnProfile.java ← 6 种生成节奏枚举
│ ├── service/
│ │ ├── MobService.java ← 战斗循环、波次、访客(区域作用域)
│ │ ├── WorldService.java ← 实用服务(批量区块操作)
│ │ ├── StructureService.java ← 委托给 StructureType 接口
│ │ └── PlayerService.java ← 床搜索 + 传送
│ ├── structure/
│ │ ├── StructureType.java ← 结构接口 (id/displayName/placeOffsets/scan/...)
│ │ ├── PostProcessStep.java ← 后处理步骤接口
│ │ ├── SpawnPointFinder.java ← 出生点查找器接口
│ │ ├── StructureRegistry.java ← 结构注册表
│ │ ├── builtin/
│ │ │ ├── TrialChambersStructureType.java
│ │ │ └── WoodlandMansionStructureType.java
│ │ ├── postprocess/
│ │ │ ├── BeardifierShellStep.java ← 使用原版 Beardifier 算法生成高斯衰减基岩/屏障外壳
│ │ │ └── ClearBelowStructureStep.java ← 将延伸至虚空层的方块清除为空气
│ │ └── spawnpoint/
│ │ └── BedNearSpawnerFinder.java
│ └── world/
│ ├── VoidGenerator.java ← 完全空的 ChunkGenerator
│ ├── AcquiredArena.java ← record(arenaId, strategyId, world, worldName, regionBounds, arenaCenter)
│ ├── WorldStrategy.java ← 世界策略接口
│ └── strategy/
│ ├── PerPlayerWorldStrategy.java ← 每位玩家专属一个世界
│ └── SharedWorldStrategy.java ← 共享世界 + 网格分配(默认)
└── resources/
├── paper-plugin.yml ← 插件清单
├── config.yml ← 默认配置
├── messages-en.yml ← 英文消息
└── messages-zh-tw.yml ← 繁体中文消息
开发命令
# 编译
./gradlew compileJava
# 生成 fat jar (build/libs/DungeonTrials-1.0-SNAPSHOT.jar)
./gradlew shadowJar
# 启动 Paper 26.1.2 测试服务器(2GB 堆内存,自动同意 EULA)
./gradlew runServer
⚠️ 无测试套件 — 验证通过成功构建完成。
构建配置亮点
plugins {
id("java-library")
id("com.gradleup.shadow") version "9.4.2"
id("xyz.jpenilla.run-paper") version "3.0.2"
}
java { toolchain.languageVersion = JavaLanguageVersion.of(25) }
build { dependsOn(shadowJar) }
named<Jar>("jar") { enabled = false } // 禁用默认 jar
shadowJar { archiveClassifier.set("") } // 输出文件名 = DungeonTrials-1.0-SNAPSHOT.jar
runServer {
minecraftVersion("26.1.2")
jvmArgs("-Xms2G", "-Xmx2G", "-Dcom.mojang.eula.agree=true")
}
processResources {
filesMatching("paper-plugin.yml") { expand(mapOf("version" to version)) }
}
插件清单 paper-plugin.yml
name: DungeonTrials
version: '${version}' # 由 processResources 替换为 1.0-SNAPSHOT
main: org.swim.dungeonTrials.DungeonTrials
loader: org.swim.dungeonTrials.DungeonTrialsLoader
api-version: '26.1.2'
load: POSTWORLD # 在默认世界加载完成后启用
authors: [ Swim ]
架构概览
┌──────────────────────────────────────────────────────────────┐
│ DungeonTrials (主类) │
│ · onEnable / onDisable │
│ · 注册并处理 12 个 /dt 子命令 │
│ · 注册 11 个 @EventHandler │
└────┬────────────┬──────────────┬──────────────┬──────────────┘
│ │ │ │
▼ ▼ ▼ ▼
ConfigManager DatabaseMgr WorldStrategy MobService
(配置+i18n) (SQLite) (世界生命周期) (波次+访问者模式)
▲ ▲
│ │
StructureService PlayerService
(放置+扫描) (床搜索+传送)
▲
│
StructureRegistry → StructureType
(试炼密室等)
启动时的初始化顺序
ConfigManager.load() — 读取配置文件,并为缺失的键合并 i18n 翻译。
DatabaseManager.init() — 连接 SQLite,启用 WAL 模式,并通过 PRAGMA user_version 执行自动迁移。
- 实例化
WorldService → StructureRegistry(注册内置的 TrialChambersStructureType)→ StructureService → MobService。
- 实例化
WorldStrategy(默认为 SharedWorldStrategy;切换需修改 DungeonTrials.createWorldStrategy() 中的代码),并将其注入到 MobService。
- 执行
registerEvents(this) + registerCommands()。
- 在延迟 1 秒后执行异步孤儿清理(共享模式下清除 gridId 和数据库记录;玩家独立模式下删除世界文件夹)。
禁用/卸载阶段
cancelTasks(this)
mobService.endAll() — 将所有活跃会话标记为 SHUTDOWN。
- 执行最终的孤儿清理。
worldStrategy.shutdown()(等待最多 30s 以完成玩家独立模式的 IO 线程;共享模式下视为空操作)。
databaseManager.close() — 等待最多 10s 以完成数据库线程。
命令系统
绕过 plugin.yml 声明,使用 Bukkit.getCommandMap().register(...) 动态注册命令。
子命令概览
| 命令 |
用法 |
权限 |
start [1-5] [structure] |
开始地牢会话。 |
— |
next [1-5] |
提升等级(仅限地牢内的所有者;可指定 1-5 中的任意目标等级)。 |
— |
stay |
拒绝升级并停留在当前等级。 |
— |
exit |
离开地牢。 |
— |
stats |
查看个人历史记录(显示最近 20 次会话)。 |
— |
invite <player> |
邀请访客。 |
— |
visit <owner> |
接受邀请进入地牢。 |
— |
decline |
拒绝邀请。 |
— |
leave |
访客离开地牢。 |
— |
kick <visitor> |
所有者踢出访客。 |
— |
infinite |
接受进入无限模式。 |
— |
end |
拒绝无限模式(停止生成怪物)。 |
— |
reload |
重新加载配置文件。 |
dungeontrials.admin |
标签补全
- 第一个参数:列出所有可用的子命令。
start / next 的第二个参数:建议 1, 2, 3, 4, 5。
invite/visit/kick 的第二个参数:评估为 null(委托给 Bukkit 提供在线玩家列表)。
start 的第三个参数:建议 StructureRegistry 中注册的所有结构 ID(默认为 trial_chambers)。
配置文件
config.yml
levels:
1:
clear-requirement: 6
mobs:
- type: ZOMBIE
profile: BASIC
2:
clear-requirement: 12
mobs:
- type: ZOMBIE
profile: BASIC
- type: SKELETON
profile: BASIC
# ... L3-L5 ...
settings:
main-world: overworld # 离开地牢时返回的目标世界
locale: "zh-tw" # default | en | zh-tw | ...
default-structure: trial_chambers # /dt start 命令默认使用的结构 ID
6 种生成画像 (SpawnProfile)
| 画像 |
间隔 |
总上限(n) |
模拟上限(n) |
用途 |
DEFAULT |
40t (2.0s) |
n+4 |
max(1,(n+1)/2+1) |
通用低压力填充物 |
JUVENILE |
20t (1.0s) |
n+4 |
max(1,(n+3)/2) |
较弱的次要怪物 |
BASIC |
20t (1.0s) |
n+4 |
max(1,(n+4)/2) |
主力部队 |
HEAVY |
20t (1.0s) |
n+8 |
max(1,(n+6)/2) |
重甲/坦克型怪物 |
SLOW_RANGED |
160t (8.0s) |
n+4 |
n+2 |
慢速远程攻击者 |
VEX |
20t (1.0s) |
n+3 |
max(1,(n+3)/2) |
swarm 类型怪物 |
n = 当前位于世界网格内的活跃非旁观者玩家数量,每 tick 重新计算。
动态难度缩放
等级 ≤ 5 : 倍率 = 1.0
等级 ≥ 6, 单人模式 : 在等级 5 之上,每级增加 +0.10 强度
等级 ≥ 6, 多人模式 : 每增加一名玩家(>1),额外增加 +0.05 强度(累加到等级修正值上)
simCap / totalCap 的计算使用乘法(四舍五入到最接近的整数),而 intervalTicks 使用除法(向下取整,最低硬限制为 5 ticks)。
全局硬上限 MAX_ALIVE = 30 始终具有绝对优先级。
默认难度曲线
| L |
清除条件 |
怪物配置 |
| 1 |
6 |
ZOMBIE × BASIC |
| 2 |
12 |
+ SKELETON × BASIC |
| 3 |
18 |
+ BREEZE × BASIC |
| 4 |
30 |
+ CAVE_SPIDER × HEAVY |
| 5 |
48 |
+ SLIME × BASIC, BREEZE → JUVENILE, SKELETON → SLOW_RANGED |
等级 6+ 自动扩展:clear-requirement 每级增加 12,继承 Level 5 的怪物配置列表。
生成与波次 (MobService)
触发条件
PlayerMoveEvent (hasChangedBlock = true)
AND 存在活跃会话
AND 距起点距离 > distanceThreshold
→ startWaveCycle()
逐刻生成逻辑
int alive = state.values().stream().mapToInt(s -> s.aliveCount).sum();
if (alive >= MAX_ALIVE) return; // 全局硬限制 30
double mult = levelIntensityMultiplier(level, n);
int simCap = max(1, round(profile.simultaneousCap(n) * mult));
int totalCap = max(0, round(profile.totalCap(n) * mult));
int interval = max(5, round(profile.intervalTicks() / mult));
// 随机打乱规则顺序,以避免连续生成相同的怪物
for (MobSpawnRule rule : shuffled) {
if (s.aliveCount >= simCap) continue;
if (s.totalSpawned >= totalCap) continue;
if (tick < s.nextSpawnTick) continue;
if (alive >= MAX_ALIVE) return;
Player target = pickRandomPlayer(world);
Entity entity = spawnMob(world, target.getLocation(), rule.entityType());
// 10 次尝试:使用随机角度、从 3 到 maxSpawnRadius 的随机半径以及 y ±3 查找有效的站立位置
// 跳过标记为 TUFF_BRICKS 的位置并避免狭窄的 1×1 空间
}
消失调度
每 60 ticks(3 秒)执行一次评估。距离竞技场内所有玩家超过 32 格的怪物会自动移除。
等级进度
满足击杀数 (kills ≥ clearRequirement)
AND 被杀死的怪物属于当前等级的配置
AND !infinite
AND !awaitingInfiniteChoice
→ 发送消息提示“前进到第 {next} 级?”
[YES] 点击 → /dt next {next} → advanceLevel
[NO] 点击 → /dt stay → declineLevelUp (重置击杀数为 0)
→ 如果 cleared Level 5: 清除所有怪物,停止生成,并将状态更改为 awaitingInfiniteChoice
[YES] 点击 → /dt infinite → enterInfiniteMode (从 L6 开始的无限循环)
[NO] 点击 → /dt end → declineInfiniteMode (永久停止怪物生成)
访客系统
-
房主端:/dt invite <player> → 注册到 pendingInvites[visitor] = owner。
-
访客端:收到邀请通知,附带可点击的 [Join][Decline] 文本按钮。
-
/dt visit <owner> → 验证 maxVisitors,缓存原始重生点,并将访客传送到指定的床。
-
/dt decline → 清除待处理的邀请并通知房主。
-
房主可以发出 /dt kick <visitor> 强制将访客返回其原始重生点。
-
当房主触发 endSession 时,kickAllVisitors 执行以将所有当前访客返回其原始重生点。
-
当访客触发 endSession 时,仅清除其自身的访客状态 而不影响房主的会话。
事件处理
| 事件 |
动作 |
PlayerMoveEvent |
方块改变 + 距原点距离 > 阈值 → 触发生成波次。 |
EntityDeathEvent |
在 onKill 中注册跟踪 + 清除生成跟踪引用。 |
EntityRemoveFromWorldEvent |
Paper 专属事件;清除生成跟踪引用。 |
PlayerDeathEvent |
执行 endSession("DIED")。 |
PlayerQuitEvent |
执行 endSession("QUIT") + 清除访客状态(利用 tryBeginEnd 防止重入问题)。 |
PlayerJoinEvent |
应用 applyPendingRespawn(恢复离线期间存储的缓存重生点)。 |
PlayerKickEvent |
执行 endSession("KICKED")。 |
PlayerChangedWorldEvent |
玩家离开地牢世界 → 执行 endSession("LEFT")(绕过传送)。 |
PlayerRespawnEvent |
如果重生目标指向地牢世界内部 → 将其覆盖为缓存的原始重生点。 |
PlayerInteractEvent |
在地牢世界中点击床 → 取消(防止覆盖原始出生位置)。 |
防止重入
public boolean tryBeginEnd(UUID uuid) { return ending.add(uuid); }
public void endEnd(UUID uuid) { ending.remove(uuid); }
使用 ConcurrentHashMap.newKeySet() 作为乐观锁,确保在 PlayerQuitEvent 期间的内部触发不会通过嵌套的 PlayerChangedWorldEvent 意外导致重复的 endSession 执行。
数据库 (DatabaseManager)
v2 架构 (自 1.1 起)
arenas (
arena_id TEXT PRIMARY KEY, -- 玩家模式的 uuid;共享模式的 "shared:gx:gz"
strategy_id TEXT NOT NULL, -- "per-player" 或 "shared"
world_name TEXT NOT NULL,
owner_uuid TEXT NOT NULL,
structure_id TEXT NOT NULL, -- trial_chambers / 未来扩展
created_at INTEGER NOT NULL,
last_used INTEGER NOT NULL
)
active_sessions (
player_uuid TEXT PRIMARY KEY,
arena_id TEXT NOT NULL, -- 映射到 arenas.arena_id
world_name TEXT NOT NULL,
structure_id TEXT NOT NULL,
current_level INTEGER NOT NULL DEFAULT 1,
kills INTEGER NOT NULL DEFAULT 0,
start_time INTEGER NOT NULL,
origin_x/y/z REAL NOT NULL
)
session_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
player_uuid TEXT NOT NULL,
structure_id TEXT NOT NULL, -- 用于运行统计跟踪(例如:试炼密室计数)
highest_level INTEGER NOT NULL,
total_kills INTEGER NOT NULL,
duration_seconds INTEGER NOT NULL,
completed_at INTEGER NOT NULL,
reason TEXT NOT NULL
)
架构迁移
使用 PRAGMA user_version 自动检测版本,以执行从 v0/v1 到 v2 的升级:
- 0 → 2:从废弃的
worlds 表中读取数据以构建 arenas(注入 strategy_id,将 structure_id 默认值设为 'trial_chambers',并将原始 world_uuid 映射为 arena_id)。
- 重命名
active_sessions 中的列(world_uuid → arena_id,添加 world_name)并删除孤立记录。
- 向
session_history 追加 structure_id 字段(回填默认值为 'trial_chambers')。
- 1 → 2:遵循类似的策略,因为它已经符合更新后的结构,主要侧重于回填缺失的字段。
连接配置
PRAGMA journal_mode=WAL — 并发处理读写操作。
PRAGMA busy_timeout=3000 — 设置 3 秒的忙超时时间。
PRAGMA user_version — 跟踪架构版本。
异步模型
- 专用的守护线程
DungeonTrials-DB 处理所有 SQL 语句。
- 数据库写操作立即返回,而读查询使用
CompletableFuture 进行包装。
getPlayerHistoryAsync 利用 Caffeine 缓存(上限为 50 条条目,空闲过期时间为 30 分钟),在随后的数据库写入时失效。
孤立识别查询
SELECT a.arena_id FROM arenas a
LEFT JOIN active_sessions s ON a.arena_id = s.arena_id
WHERE s.player_uuid IS NULL
- 单人模式:卸载与孤立竞技场匹配的世界,并删除其对应的文件目录。
- 共享模式:将孤立竞技场的 gridId 回收至池中,并删除其数据库记录(父世界保持加载状态)。
国际化
加载序列
1. 从 jar 内部加载 fallback messages-en.yml(defaultMessages)。
2. 如果本地磁盘上不存在该文件 → 从 jar 资源中复制它。
3. 将 defaultMessages 中缺失的键追加到活动配置映射中(仅引入缺失的键,保留自定义用户输入不变)。
4. 如果在回填过程中进行了调整 → 将修改刷新回磁盘存储。
区域设置解析规则
分配给 "default" | "en" | "english" | 空字符串 "" 的区域设置 → 映射到 messages-en.yml
任何其他输入 → 映射到 messages-{locale}.yml(例如:"messages-zh-tw.yml")
占位符
使用 {name} 占位符模式(避免直接在文本中使用原始 MiniMessage 标签,以防止与标准 <...> 标签发生解析冲突):
configManager.getMessage("command.invite.sent", "target", "Steve");
// 替换 {target} → Steve → 通过 MiniMessage.deserialize 处理 → 返回 Component
交互式按钮(MiniMessage 点击事件)
"<gold>达到 {kills} 次击杀!进入第 {next} 层?</gold>
<click:run_command:/dt next {next}><green>[是]</green></click>
<click:run_command:/dt stay><red>[否]</red></click>"
结构放置
接口职责
StructureType 接口包含结构的所有可变参数(id、displayName、namespacedId、placeX/Y/ZOffset、platformSize、keepLoadedRadius、spawnerBlocks、unsafeSpawnFloors、postProcessSteps、spawnPointFinder)。
StructureService.placeStructure(world, player, type, arenaCenter, onComplete) 作为结构生成的统一外部入口点,在内部委托给绑定在 StructureType 接口下的组件执行步骤。
放置流程图
1. 强制加载围绕 arenaCenter 且涵盖 keepLoadedRadius 区域的区块。
2. 让出执行权 1 秒(允许区块生成最终完成)。
3. 访问 NMS API:level.registryAccess().lookupOrThrow(Registries.STRUCTURE).get(Identifier.parse(type.namespacedId())) 以获取 Holder<Structure> 和 Structure 实例。
4. 执行 structure.generate(...):同步构建 StructureStart 对象。
- 评估原版 findGenerationPoint + 扩展 jigsaw 池。
- 计算真正的 BoundingBox(结合由 terrain_adaptation encapsulate 导出的 +12 膨胀值)。
5. 在相交于 BoundingBox 的每个区块上调用 start.placeInChunk(...) 以物理放置方块。
6. 扫描 BoundingBox 边界,归类与 spawnerBlocks 匹配的刷怪笼位置。
7. 执行链式 type.postProcessSteps():顺序处理 BeardifierShellStep(ENCAPSULATE 外壳,高斯衰减)→ ClearBelowStructureStep(清除至 AIR 方块,仅限于林地府邸)。
⚠️ 结构生成直接利用 NMS API(通过 paperweight-userdev 提供的 mojang-mapped NMS 类路径),而不是使用原始的 place structure 控制台命令。它同时直接触发原版 Structure.generate + StructureStart.placeInChunk,从而原生地确保真实的 BoundingBox(包括封装膨胀)。
Dungeon Trials
Minecraft Paper Plugin — Automatically generates trial dungeons, wave-based mob spawning, 5-level progression, and an optional infinite mode.
Introduction
Dungeon Trials is a Paper server-side "Trial Dungeon" plugin. When a player executes /dt start, the system generates an isolated trial dungeon (by default, using a shared world grid where each dungeon is assigned a grid cell), automatically places the vanilla Minecraft Trial Chambers structure, and initiates a combat loop consisting of wave-based mob spawning + level progression. Players can advance levels by meeting requirements (or manually upgrade inside the dungeon via /dt next). After clearing level 5, players can opt into the infinite mode.
Core Features
- Solo / Co-op — Owners can invite visitors to their dungeon (up to
settings.max-visitors, default is 3).
- 5 Defined Levels (Levels 6 and above use implicit configurations, with
clear-requirement increasing by 12 per level).
- Wave-based Spawning — Triggered when a player moves beyond a distance of
DISTANCE_THRESHOLD=5 blocks from the starting point.
- Dynamic Difficulty Scaling — Automatically scales up spawn intensity for levels 6+ and multiplayer sessions.
- Persistence — SQLite (WAL) + Caffeine cache, ensuring records are preserved across server restarts.
- i18n — Supports English + Traditional Chinese, configurable via
settings.locale.
- BossBar Progress — Real-time display of kill progress with a 3-tier color system (Green / Yellow / Red).
- Orphan Cleanup — Automatically scans for residual worlds during startup and disabling phases.
Tech Stack
| Item |
Version / Description |
| Minecraft |
Paper 26.1.2 |
| Java |
25 (locked via toolchain) |
| Build Tool |
Gradle 9.5.1 (configuration-cache enabled) |
| Shadow JAR |
9.4.2 |
| Development Plugin |
xyz.jpenilla.run-paper 3.0.2 |
| Package |
org.swim.dungeonTrials |
| Maven group |
org.swim |
| Version |
1.0-SNAPSHOT |
| Persistence |
SQLite (WAL) + Caffeine Cache |
| Internationalization |
MiniMessage (Adventure API) + Custom YAML |
| Annotations |
Lombok (@Getter) + JSpecify (@NonNull) |
| Permission Compatibility |
LuckPerms API 5.5 (downloaded at runtime) |
Dependency Resolution Mechanism
All runtime dependencies (sqlite-jdbc, caffeine, luckperms-api) are declared as compileOnly and are not shaded into the fat jar. Instead, DungeonTrialsLoader implements Paper's PluginLoader interface to dynamically download them from Maven Central via MavenLibraryResolver during the classloader(...) stage.
Advantage: The jar size remains extremely small, and dependency deduplication is handled by Paper.
Disadvantage: The server requires an internet connection during its initial startup.
Project Structure
src/main/
├── java/org/swim/dungeonTrials/
│ ├── DungeonTrials.java ← Main Plugin Class
│ ├── DungeonTrialsLoader.java ← Paper PluginLoader
│ ├── config/
│ │ ├── ConfigManager.java ← Configuration + i18n
│ │ └── LevelConfig.java ← record
│ ├── database/
│ │ └── DatabaseManager.java ← SQLite + Caffeine + schema migration
│ ├── model/
│ │ ├── ActiveSession.java ← Active session (arenaId, worldName, structureId, origin*)
│ │ ├── SessionHistory.java ← Historical records (structureId, highestLevel, ...)
│ │ ├── MobSpawnRule.java ← record(type + profile)
│ │ ├── MobSpawnState.java ← Spawn state counter
│ │ └── SpawnProfile.java ← 6 types of spawn rhythm enum
│ ├── service/
│ │ ├── MobService.java ← Combat loop, waves, visitors (region-scoped)
│ │ ├── WorldService.java ← Utility service (batch block operations)
│ │ ├── StructureService.java ← Delegates to StructureType interface
│ │ └── PlayerService.java ← Bed searching + teleportation
│ ├── structure/
│ │ ├── StructureType.java ← Structure interface (id/displayName/placeOffsets/scan/...)
│ │ ├── PostProcessStep.java ← Post-processing step interface
│ │ ├── SpawnPointFinder.java ← Spawn point finder interface
│ │ ├── StructureRegistry.java ← Structure registry
│ │ ├── builtin/
│ │ │ ├── TrialChambersStructureType.java
│ │ │ └── WoodlandMansionStructureType.java
│ │ ├── postprocess/
│ │ │ ├── BeardifierShellStep.java ← Generates a Gaussian-decay bedrock/barrier shell using vanilla Beardifier algorithm
│ │ │ └── ClearBelowStructureStep.java ← Clears blocks extending down to the void layer into air
│ │ └── spawnpoint/
│ │ └── BedNearSpawnerFinder.java
│ └── world/
│ ├── VoidGenerator.java ← Completely empty ChunkGenerator
│ ├── AcquiredArena.java ← record(arenaId, strategyId, world, worldName, regionBounds, arenaCenter)
│ ├── WorldStrategy.java ← World strategy interface
│ └── strategy/
│ ├── PerPlayerWorldStrategy.java ← One dedicated world per player
│ └── SharedWorldStrategy.java ← Shared world + grid allocation (Default)
└── resources/
├── paper-plugin.yml ← Plugin manifest
├── config.yml ← Default configuration
├── messages-en.yml ← English messages
└── messages-zh-tw.yml ← Traditional Chinese messages
Development Commands
# Compile
./gradlew compileJava
# Generate fat jar (build/libs/DungeonTrials-1.0-SNAPSHOT.jar)
./gradlew shadowJar
# Start Paper 26.1.2 test server (2GB heap, auto-agree to EULA)
./gradlew runServer
⚠️ No Test Suite — Verification is completed via successful builds.
Build Configuration Highlights
plugins {
id("java-library")
id("com.gradleup.shadow") version "9.4.2"
id("xyz.jpenilla.run-paper") version "3.0.2"
}
java { toolchain.languageVersion = JavaLanguageVersion.of(25) }
build { dependsOn(shadowJar) }
named<Jar>("jar") { enabled = false } // Disable default jar
shadowJar { archiveClassifier.set("") } // Output name = DungeonTrials-1.0-SNAPSHOT.jar
runServer {
minecraftVersion("26.1.2")
jvmArgs("-Xms2G", "-Xmx2G", "-Dcom.mojang.eula.agree=true")
}
processResources {
filesMatching("paper-plugin.yml") { expand(mapOf("version" to version)) }
}
Plugin Manifest paper-plugin.yml
name: DungeonTrials
version: '${version}' # Replaced with 1.0-SNAPSHOT by processResources
main: org.swim.dungeonTrials.DungeonTrials
loader: org.swim.dungeonTrials.DungeonTrialsLoader
api-version: '26.1.2'
load: POSTWORLD # Enabled after default worlds have loaded
authors: [ Swim ]
Architecture Overview
┌──────────────────────────────────────────────────────────────┐
│ DungeonTrials (Main) │
│ · onEnable / onDisable │
│ · 12 /dt sub-command registrations & handling │
│ · 11 @EventHandler registrations │
└────┬────────────┬──────────────┬──────────────┬──────────────┘
│ │ │ │
▼ ▼ ▼ ▼
ConfigManager DatabaseMgr WorldStrategy MobService
(Config+i18n) (SQLite) (World Lifecycle)(Wave+Visitor)
▲ ▲
│ │
StructureService PlayerService
(Placement+Scan) (Bed Search+Teleport)
▲
│
StructureRegistry → StructureType
(Trial Chambers, etc.)
Initialization Order at Startup
ConfigManager.load() — Reads the config and merges missing keys for i18n.
DatabaseManager.init() — Connects to SQLite, enables WAL, and performs automatic migrations via PRAGMA user_version.
- Instantiates
WorldService → StructureRegistry (registers the built-in TrialChambersStructureType) → StructureService → MobService.
- Instantiates
WorldStrategy (defaults to SharedWorldStrategy; switching requires modifying the code in DungeonTrials.createWorldStrategy()) and injects it into MobService.
- Executes
registerEvents(this) + registerCommands().
- Performs asynchronous orphan cleanup after a 1-second delay (clears gridIds and DB records in shared mode; deletes world folders in per-player mode).
Disabling / Unloading Phase
cancelTasks(this)
mobService.endAll() — Marks all active sessions with SHUTDOWN.
- Performs a final orphan cleanup.
worldStrategy.shutdown() (waits up to 30s for the per-player IO thread; treated as a no-op for shared mode).
databaseManager.close() — Waits up to 10s for the DB thread.
Command System
Bypasses plugin.yml declarations and dynamically registers commands using Bukkit.getCommandMap().register(...).
Sub-commands Overview
| Command |
Usage |
Permission |
start [1-5] [structure] |
Starts a dungeon session. |
— |
next [1-5] |
Advances the level (restricted to the owner inside the dungeon; can specify any target level from 1-5). |
— |
stay |
Rejects the level advancement and stays at the current level. |
— |
exit |
Leaves the dungeon. |
— |
stats |
Checks personal history (displays the last 20 sessions). |
— |
invite <player> |
Invites a visitor. |
— |
visit <owner> |
Accepts an invitation to enter a dungeon. |
— |
decline |
Declines an invitation. |
— |
leave |
Visitor leaves the dungeon. |
— |
kick <visitor> |
Owner kicks a visitor. |
— |
infinite |
Accepts entering the infinite mode. |
— |
end |
Declines the infinite mode (stops spawning mobs). |
— |
reload |
Reloads the configuration file. |
dungeontrials.admin |
Tab Completion
- First argument: Lists all available sub-commands.
- Second argument for
start / next: Suggests 1, 2, 3, 4, 5.
- Second argument for
invite/visit/kick: Evaluates to null (delegated to Bukkit to provide online player lists).
- Third argument for
start: Suggests all structure IDs registered in StructureRegistry (default is trial_chambers).
Configuration Files
config.yml
levels:
1:
clear-requirement: 6
mobs:
- type: ZOMBIE
profile: BASIC
2:
clear-requirement: 12
mobs:
- type: ZOMBIE
profile: BASIC
- type: SKELETON
profile: BASIC
# ... L3-L5 ...
settings:
main-world: overworld # Target world when exiting the dungeon
locale: "zh-tw" # default | en | zh-tw | ...
default-structure: trial_chambers # Default structure ID for /dt start
6 SpawnProfile
| Profile |
interval |
totalCap(n) |
simCap(n) |
Usage |
DEFAULT |
40t (2.0s) |
n+4 |
max(1,(n+1)/2+1) |
General low-pressure filler |
JUVENILE |
20t (1.0s) |
n+4 |
max(1,(n+3)/2) |
Weaker secondary mobs |
BASIC |
20t (1.0s) |
n+4 |
max(1,(n+4)/2) |
Main force |
HEAVY |
20t (1.0s) |
n+8 |
max(1,(n+6)/2) |
Heavy armor / tank mobs |
SLOW_RANGED |
160t (8.0s) |
n+4 |
n+2 |
Slow ranged attackers |
VEX |
20t (1.0s) |
n+3 |
max(1,(n+3)/2) |
Swarm type mobs |
n = Number of active, non-spectator players currently inside the world grid, re-calculated every tick.
Dynamic Difficulty Scaling
level ≤ 5 : Multiplier = 1.0
level ≥ 6, Solo : Adds +0.10 intensity per level above 5
level ≥ 6, Co-op : Adds an additional +0.05 intensity per additional player (>1) (accumulated onto the level modifier)
simCap / totalCap calculations use multiplication (rounded to the nearest integer), while intervalTicks uses division (rounded down, with a hard minimum floor of 5 ticks).
The global hard ceiling MAX_ALIVE = 30 always takes absolute priority.
Default Difficulty Curve
| L |
clear |
Mob Configurations |
| 1 |
6 |
ZOMBIE × BASIC |
| 2 |
12 |
+ SKELETON × BASIC |
| 3 |
18 |
+ BREEZE × BASIC |
| 4 |
30 |
+ CAVE_SPIDER × HEAVY |
| 5 |
48 |
+ SLIME × BASIC, BREEZE → JUVENILE, SKELETON → SLOW_RANGED |
Level 6+ automatic extension: clear-requirement increases by 12 per level, inheriting the mob configuration list from Level 5.
Spawning and Waves (MobService)
Trigger Conditions
PlayerMoveEvent (hasChangedBlock = true)
AND Active session exists
AND Distance from starting point > distanceThreshold
→ startWaveCycle()
Per-tick Spawning Logic
int alive = state.values().stream().mapToInt(s -> s.aliveCount).sum();
if (alive >= MAX_ALIVE) return; // Global hard limit of 30
double mult = levelIntensityMultiplier(level, n);
int simCap = max(1, round(profile.simultaneousCap(n) * mult));
int totalCap = max(0, round(profile.totalCap(n) * mult));
int interval = max(5, round(profile.intervalTicks() / mult));
// Shuffles the rules order randomly to avoid spawning identical mobs consecutively
for (MobSpawnRule rule : shuffled) {
if (s.aliveCount >= simCap) continue;
if (s.totalSpawned >= totalCap) continue;
if (tick < s.nextSpawnTick) continue;
if (alive >= MAX_ALIVE) return;
Player target = pickRandomPlayer(world);
Entity entity = spawnMob(world, target.getLocation(), rule.entityType());
// 10 attempts: finds a valid standing position using random angles, random radii from 3 to maxSpawnRadius, and y ±3
// Skips positions marked with TUFF_BRICKS and avoids confined 1×1 spaces
}
Despawn Scheduling
Executes an evaluation every 60 ticks (3 seconds). Mobs that are further than 32 blocks away from all players inside the arena are automatically removed.
Level Progression
Kill count met (kills ≥ clearRequirement)
AND Killed mob belongs to the current level's configurations
AND !infinite
AND !awaitingInfiniteChoice
→ Sends a message prompting "Advance to Level {next}?"
[YES] clicked → /dt next {next} → advanceLevel
[NO] clicked → /dt stay → declineLevelUp (resets kills to 0)
→ If Level 5 is cleared: Clears all mobs, stops spawning, and changes state to awaitingInfiniteChoice
[YES] clicked → /dt infinite → enterInfiniteMode (infinite loop starting from L6)
[NO] clicked → /dt end → declineInfiniteMode (stops mob spawning permanently)
Visitor System
-
Owner side: /dt invite <player> → Registers into pendingInvites[visitor] = owner.
-
Visitor side: Receives invitation notice accompanied by clickable [Join][Decline] text buttons.
-
/dt visit <owner> → Validates maxVisitors, caches the original respawn location, and teleports the visitor to the designated bed.
-
/dt decline → Wipes the pending invitation and notifies the owner.
-
Owners can issue /dt kick <visitor> to forcibly return visitors back to their original respawn points.
-
When an owner triggers endSession, kickAllVisitors executes to return all current visitors back to their original respawn points.
-
When a visitor triggers endSession, it only clears their own visitor status without affecting the owner's session.
Event Handling
| Event |
Action |
PlayerMoveEvent |
Block changed + distance from origin > threshold → Triggers spawn wave. |
EntityDeathEvent |
Registers tracking inside onKill + purges spawn tracking references. |
EntityRemoveFromWorldEvent |
Paper-exclusive event; purges spawn tracking references. |
PlayerDeathEvent |
Executes endSession("DIED"). |
PlayerQuitEvent |
Executes endSession("QUIT") + clears visitor states (utilizes tryBeginEnd to prevent re-entrancy issues). |
PlayerJoinEvent |
Applies applyPendingRespawn (restores cached respawn points stored while offline). |
PlayerKickEvent |
Executes endSession("KICKED"). |
PlayerChangedWorldEvent |
Player steps out of a dungeon world → Executes endSession("LEFT") (teleportation is bypassed). |
PlayerRespawnEvent |
If the respawn destination target points inside a dungeon world → Overrides it to the cached original respawn point. |
PlayerInteractEvent |
Clicking on beds inside a dungeon world → Cancelled (prevents overriding original spawn positions). |
Re-entrancy Prevention
public boolean tryBeginEnd(UUID uuid) { return ending.add(uuid); }
public void endEnd(UUID uuid) { ending.remove(uuid); }
Uses ConcurrentHashMap.newKeySet() as an optimistic lock, ensuring that internal triggers during a PlayerQuitEvent do not inadvertently cause duplicate endSession executions via a nested PlayerChangedWorldEvent.
Database (DatabaseManager)
v2 Schema (Since 1.1)
arenas (
arena_id TEXT PRIMARY KEY, -- uuid for per-player mode; "shared:gx:gz" for shared mode
strategy_id TEXT NOT NULL, -- "per-player" or "shared"
world_name TEXT NOT NULL,
owner_uuid TEXT NOT NULL,
structure_id TEXT NOT NULL, -- trial_chambers / future expansions
created_at INTEGER NOT NULL,
last_used INTEGER NOT NULL
)
active_sessions (
player_uuid TEXT PRIMARY KEY,
arena_id TEXT NOT NULL, -- maps to arenas.arena_id
world_name TEXT NOT NULL,
structure_id TEXT NOT NULL,
current_level INTEGER NOT NULL DEFAULT 1,
kills INTEGER NOT NULL DEFAULT 0,
start_time INTEGER NOT NULL,
origin_x/y/z REAL NOT NULL
)
session_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
player_uuid TEXT NOT NULL,
structure_id TEXT NOT NULL, -- utilized for run statistics tracking (e.g., Trial Chambers count)
highest_level INTEGER NOT NULL,
total_kills INTEGER NOT NULL,
duration_seconds INTEGER NOT NULL,
completed_at INTEGER NOT NULL,
reason TEXT NOT NULL
)
Schema Migration
Automatically detects versions using PRAGMA user_version to perform upgrades from v0/v1 to v2:
- 0 → 2: Reads data from the obsolete
worlds table to construct arenas (injects strategy_id, sets structure_id default to 'trial_chambers', maps the original world_uuid to arena_id).
- Renames columns in
active_sessions (world_uuid → arena_id, adds world_name) and removes orphaned records.
- Appends the
structure_id field to session_history (backfilled with a default value of 'trial_chambers').
- 1 → 2: Follows a similar strategy since it already matches the updated structure, focusing primarily on backfilling missing fields.
Connection Configurations
PRAGMA journal_mode=WAL — Concurrently handles read and write operations.
PRAGMA busy_timeout=3000 — Sets a 3-second busy timeout.
PRAGMA user_version — Tracks schema versions.
Asynchronous Model
- A dedicated daemon thread
DungeonTrials-DB handles all SQL statements.
- Database write operations return immediately, while read queries are wrapped using
CompletableFuture.
getPlayerHistoryAsync utilizes a Caffeine cache (capped at 50 entries, with a 30-minute idle expiration period), invalidated upon subsequent database writes.
Orphan Identification Query
SELECT a.arena_id FROM arenas a
LEFT JOIN active_sessions s ON a.arena_id = s.arena_id
WHERE s.player_uuid IS NULL
- Per-player mode: The world matching an orphaned arena is unloaded and its corresponding file directory is deleted.
- Shared mode: The gridId of the orphaned arena is recycled back into the pool and its DB record is deleted (the parent world remains loaded).
Internationalization
Loading Sequence
1. Loads fallback messages-en.yml from inside the jar (defaultMessages).
2. If the local file does not exist on disk → Copies it from the jar resources.
3. Appends missing keys from defaultMessages into the active configuration map (only introduces missing keys, leaving custom user entries untouched).
4. If adjustments were made during backfilling → Flushes modifications back to disk storage.
Locale Resolution Rules
locale assigned to "default" | "en" | "english" | empty string "" → maps to messages-en.yml
Any other inputs → maps to messages-{locale}.yml (e.g., "messages-zh-tw.yml")
Placeholders
Uses the {name} placeholder pattern (avoids using raw MiniMessage tags directly within text to prevent parsing conflicts with standard <...> tags):
configManager.getMessage("command.invite.sent", "target", "Steve");
// Swaps out {target} → Steve → Processes via MiniMessage.deserialize → Returns Component
Interactive Buttons (MiniMessage Click Events)
"<gold>Reached {kills} kills! Advance to Level {next}?</gold>
<click:run_command:/dt next {next}><green>[YES]</green></click>
<click:run_command:/dt stay><red>[NO]</red></click>"
Structure Placement
Interface Responsibilities
The StructureType interface contains all mutable parameters for a structure (id, displayName, namespacedId, placeX/Y/ZOffset, platformSize, keepLoadedRadius, spawnerBlocks, unsafeSpawnFloors, postProcessSteps, spawnPointFinder).
StructureService.placeStructure(world, player, type, arenaCenter, onComplete) serves as the unified external entry point for structure generation, delegating steps internally to components bound under the StructureType interface.
Placement Flow Diagram
1. Forcibly loads chunks encompassing the keepLoadedRadius area surrounding arenaCenter.
2. Yields execution for 1 second (allows chunk generations to finalize).
3. Accesses NMS APIs: level.registryAccess().lookupOrThrow(Registries.STRUCTURE).get(Identifier.parse(type.namespacedId())) to retrieve Holder<Structure> and Structure instances.
4. Executes structure.generate(...): Synchronously builds a StructureStart object.
- Evaluates vanilla findGenerationPoint + expands jigsaw pools.
- Computes the true BoundingBox (incorporating the +12 inflate derived from terrain_adaptation encapsulate).
5. Invokes start.placeInChunk(...) across every chunk intersecting the BoundingBox to physically place blocks.
6. Scans across the BoundingBox boundary to catalog spawner locations matching spawnerBlocks.
7. Executes the chained type.postProcessSteps(): sequentially processes BeardifierShellStep (ENCAPSULATE shell, Gaussian decay) → ClearBelowStructureStep (purges blocks to AIR, restricted to Woodland Mansions).
⚠️ Structure generation leverages NMS APIs directly (provided via the mojang-mapped NMS classpath via paperweight-userdev) instead of using the raw place structure console command. It directly triggers vanilla Structure.generate + StructureStart.placeInChunk simultaneously, securing the authentic BoundingBox (including encapsulate inflate) natively.
评论 0
登录后参与评分
还没有评论,来抢沙发吧