UI提升,进入能跑阶段

This commit is contained in:
2026-09-24 22:55:46 +08:00
parent afb343aa49
commit 5f1be65512
47 changed files with 4645 additions and 354 deletions
+3
View File
@@ -19,3 +19,6 @@ logs/
# Game Assets # Game Assets
assets/ assets/
# Others
.workbuddy/
+182 -7
View File
@@ -17,7 +17,7 @@ Godot 客户端当前已具备:
- Godot 4.7 .NET / C# 工程与 `src/` 目录结构; - Godot 4.7 .NET / C# 工程与 `src/` 目录结构;
- `GameSession`、`BattleStore`、`AssetCatalog`、`UiRouter` 和 `GameSettings` 五个 Autoload; - `GameSession`、`BattleStore`、`AssetCatalog`、`UiRouter` 和 `GameSettings` 五个 Autoload;
- WebSocket 与 Mock 传输层; - WebSocket 与 Mock 传输层;
- 默认连接地址 `ws://localhost:11030/ws/solo`; - 默认连接地址 `ws://localhost:12030/ws/solo`;
- `system.ping` / `system.pong` 心跳; - `system.ping` / `system.pong` 心跳;
- `gaming.start`、`gaming.state`、`gaming.request`、`gaming.action` 等真实协议消息; - `gaming.start`、`gaming.state`、`gaming.request`、`gaming.action` 等真实协议消息;
- 角色选择、基础行动、技能、物品、目标和逻辑格决策的初步控件; - 角色选择、基础行动、技能、物品、目标和逻辑格决策的初步控件;
@@ -27,8 +27,11 @@ Godot 客户端当前已具备:
当前端到端验证结果: 当前端到端验证结果:
```text ```text
SOLO_SMOKE_OK game=<gameId> round=0 characters=2 units=2 SOLO_SMOKE_OK dialogFits=true clickableList=true clickSubmits=true game=<gameId> round=0 characters=10 units=10
SOLO_VERTICAL_OK game=<gameId> moves=1 attackTargetSubmitted=true rejectionRecovered=true units=2 SOLO_VERTICAL_OK game=<gameId> moves=32 attackTargetSubmitted=true rejectionRecovered=true attackAttempts=1 attackCancelled=0 attackReachableRounds=1 attackGateVerified=True preciseAttackSignal=true continueObserved=true units=2
SOLO_RECONNECT_OK game=<gameId> reconnected=true attempts=1 serverRunningDuringDrop=true resumeSent=true staleDecisionCleared=true snapshotsAfterResume=1 stateMatchesServer=true units=2
PHASE_C_DECISIONS_OK quotas=true details=true attackReachability=true inquiry=true continue=true cancellation=true shapePreview=true
PHASE_E_OK diff=true animator=true cancellation=true ground=true hudLayout=true
``` ```
### 执行进度 ### 执行进度
@@ -36,14 +39,29 @@ SOLO_VERTICAL_OK game=<gameId> moves=1 attackTargetSubmitted=true rejectionRecov
- [x] 阶段 A:`UnitView`、按 GUID 实例协调、格子定位、阵营/行动者/HP/淘汰/AI 托管显示; - [x] 阶段 A:`UnitView`、按 GUID 实例协调、格子定位、阵营/行动者/HP/淘汰/AI 托管显示;
- [x] 阶段 B 基础:合法格集合高亮、单位直接点击选择目标、提交前确认; - [x] 阶段 B 基础:合法格集合高亮、单位直接点击选择目标、提交前确认;
- [x] 阶段 B 完整:移动与普攻的真实端到端竖切回归、服务器拒绝后的决策恢复; - [x] 阶段 B 完整:移动与普攻的真实端到端竖切回归、服务器拒绝后的决策恢复;
- [ ] 阶段 C:完整决策类型与行动配额; - [x] 阶段 C:完整决策类型与行动配额;
- [ ] 阶段 D:断线恢复; - [x] 阶段 D:断线恢复;
- [ ] 阶段 E:动画、日志、结算与输入完善。 - [x] 阶段 E:动画、日志、结算与输入完善。
阶段 A 已通过真实 Solo WebAPI 冒烟测试:权威快照含 2 名角色时,`UnitsLayer` 生成且仅生成 2 个 `UnitView`。 阶段 A 已通过真实 Solo WebAPI 冒烟测试:权威快照含 2 名角色时,`UnitsLayer` 生成且仅生成 2 个 `UnitView`。
阶段 B 已通过真实 Solo WebAPI 竖切测试:客户端可通过合法格完成移动、通过点击单位提交普通攻击;提交期间会锁定重复输入,取消会发送协议取消意图,非法格被服务器拒绝后可以恢复并继续选择。 阶段 B 已通过真实 Solo WebAPI 竖切测试:客户端可通过合法格完成移动、通过点击单位提交普通攻击;提交期间会锁定重复输入,取消会发送协议取消意图,非法格被服务器拒绝后可以恢复并继续选择。
阶段 C 已通过真实 Solo WebAPI 竖切测试(`--solo-vertical-smoke-test`,连跑 5 次全绿)与静态协议自检(`--phase-c-smoke-test`):配额门控、技能/物品详情、`Inquiry` 三种输入、`Continue` 与范围形状预览均按服务端字段解析;真实对局中移动、拒绝恢复、普通攻击与 `Continue` 串通在同一条链路上(`continueObserved=true`)。
阶段 C 落地时确立了「权威服务器原则」的三条客户端铁律:
1. 客户端不推算射程、合法性或可选目标 —— 合法性只来自 `TargetGrid.gridIds` / `Targets.targets`;
2. `ActionType.enemyOptions` / `enemys` 是引擎在当前位置按「攻击可达 ∪ 施法可达」过滤后的敌人(见 `GamingQueue` 中 `canAttackGrids ∪ canCastGrids` 的过滤),列表为空即普通攻击必被取消,因此按钮直接禁用;
3. 「提交被拒绝」没有回执 —— 服务器不会告诉你「你这个行动不合法」,只能靠**紧邻的那条决策类型**判断:回到 `ActionType` 即取消,否则进入自己的下一步。`DecisionUiRules.DetectCancelledAction` 负责这条判定,`BattleScreen` 据此提示玩家。
注意区分另一种情况:**服务器主动放弃一条挂起决策**(对局结束 / 玩家被接管 / 断线)现在会发 `gaming.resolved { requestId, kind, reason }`,客户端据此立刻收尾,不必再靠超时去猜。
阶段 D 已通过真实断线恢复测试(`--solo-reconnect-smoke-test`):非计划中断(`ClientWebSocket.Abort()`,不发送关闭握手)后客户端按退避重连(1s→2s→4s→8s→15s),重连成功自动补发 `gaming.resume`,服务器把新连接接管回原对局并补发完整快照与待处理决策。测试为了让「客户端画面 == 服务器状态」成为可精确比对的断言,会先用 `gaming.pause` 把服务器冻结,再通过 REST `/api/solo/state` 逐项比对单位集合、格子、血量、淘汰标记与回合数。
阶段 E 已通过静态自检(`--phase-e-smoke-test`)与真实对局回归:快照差分产出移动/受击/治疗/淘汰/复活任务,表现队列可合并、可跳过、有上限且永不阻塞快照接收;战斗日志抽屉、结算页、错误提示条与焦点导航均已接入。
**注意 `BattleScreen` 已拆成两个 partial 文件**:`BattleScreen.cs`(世界 / 单位 / 决策)与 `BattleScreen.Overlays.cs`(覆盖层 / 日志 / 结算 / 表现控制)。新增 UI 相关代码请加到后者。
现有 WebAPI 的 SoloMap 为 `12 × 12`,而美术竖切建议值为 `16 × 12`。客户端不得写死地图尺寸,必须以服务器 `MapDto.length` 与 `MapDto.width` 为准动态构建显示层。 现有 WebAPI 的 SoloMap 为 `12 × 12`,而美术竖切建议值为 `16 × 12`。客户端不得写死地图尺寸,必须以服务器 `MapDto.length` 与 `MapDto.width` 为准动态构建显示层。
## 3. 竖切完成后的玩家流程 ## 3. 竖切完成后的玩家流程
@@ -123,6 +141,10 @@ BattleScreen / UnitView / GridOverlay2D
| `request.kind` | 输入状态机 | 决定当前允许的交互方式 | | `request.kind` | 输入状态机 | 决定当前允许的交互方式 |
| `request.payload.gridIds` | `GridOverlay2D` | 只显示和接受合法格子 | | `request.payload.gridIds` | `GridOverlay2D` | 只显示和接受合法格子 |
| `request.payload.targets` | `UnitView` | 只允许选择合法单位 | | `request.payload.targets` | `UnitView` | 只允许选择合法单位 |
| `ActionType.enemyOptions` / `enemys` | 行动坞 | 当前位置攻击可达 ∪ 施法可达的敌人;为空则禁用普通攻击 |
| `ActionType.dp.quotas` | 行动坞按钮 | 每种行动类型的配额 / 剩余 / 决策点消耗 |
| `request.timeoutMs` | `TimeoutLabel` | 服务器决策倒计时 |
| `state.aiEscalated` | 角色 HUD、`UnitView` | 超时或打转后服务器接管角色的提示 |
服务器目前没有正式的 `stateRevision` 字段。第一阶段按 WebSocket 顺序处理完整快照;正式重连和增量同步前,应在协议中补充单调递增的状态版本。 服务器目前没有正式的 `stateRevision` 字段。第一阶段按 WebSocket 顺序处理完整快照;正式重连和增量同步前,应在协议中补充单调递增的状态版本。
@@ -302,4 +324,157 @@ UnitView (Node2D)
## 11. 下一项开发任务 ## 11. 下一项开发任务
立即进入阶段 A:创建 `UnitView`,并在 `BattleScreen` 中实现按 GUID 对权威快照进行实例协调。第一小步只使用临时剪影和 HP 条,确保角色数量、位置、阵营与当前行动者状态正确,再接入正式人物素材。 竖切 A~E 均已闭环。下一步不再由本计划驱动,候选方向:
1. **接入真实素材**:把 `UnitView` 的占位剪影换成正式角色动画(阶段 E 的补间接口已经就位,只需 `Body` 的 `AnimatedSprite2D` 有帧);
2. **手工竖切回归**:按 §8 的九步流程走一遍,重点看动画积压与 16:9 缩放下 HUD 的表现;
3. **回到 Server-v3**:登录、房间与匹配(本计划明确不包含)。
开工前需要先和服务端对齐两点:
- `gaming.resume` 当前的语义与「旧局不自动挂载」策略(`Program.cs` 的 `/ws/solo` 注释)如何共存;
- 服务器目前没有 `stateRevision`,重连后只能靠完整快照对齐,是否需要先补一个单调递增的状态版本。
## 12. 实施过程中记录的问题
按发现顺序记录,标注归属(服务端 / 客户端 / 测试环境)。已修复的直接写结论,未修复的保留为待办。
### 已修复
| # | 现象 | 根因 | 处理 |
|---|---|---|---|
| 1 | `requireContinue=true` 但收不到 `Continue` | 客户端用曼哈顿距离猜「能否普攻」,敌人只在施法射程内时仍提交,被服务器作废后回到 `ActionType`,连续 4 次同类决策触发防打转护栏 → 玩家被 AI 托管 → `OnTurnEnd` 不再下发 `Continue` | 阶段 C:只按服务器列出的敌列表 + `dp.quotas` 决策,被作废的行动同回合不再重复提交 |
| 2 | 玩家点了普攻却毫无反馈 | 服务器对不可行提交没有拒绝回执 | 阶段 C:`DecisionUiRules.DetectCancelledAction` 按「紧邻的决策类型」判定作废并提示 |
| 3 | 重连后界面可能卡在一条已经作废的决策上 | 服务端 `MarkDisconnected` / `EscalatePlayerToAI` 只清 `_pending`,不清 `_pendingRequests`,`AttachSink` 会把历史请求一并补发(`SoloGameSession.cs:216/261` 对比 `197-209`) | **两层都修了**:客户端记录已答复的 `requestId` 忽略重复项(`BattleStore`);服务端后续实现 `DropPendingDecisions` 时在兜底解决的三处一并清掉 `_pendingRequests`(见 §13-4 第 9 条),并改发 `gaming.resolved` 通知客户端 —— 重连后不再补发死决策 |
| 4 | 重连后决策没有倒计时 | `AttachSink` 补发请求时只带 `requestId/kind/payload`,丢了 `timeoutMs` | 客户端如实显示「重连后无倒计时」;**建议服务端补上该字段** |
### 待办(未修复)
- **表现与权威不一致(客户端)**:`GreyboxMap2D._Draw` 硬编码了 4 个掩体(`(5,4) (6,4) (10,7) (11,7)`),与服务端 `MapDto` 无关。当前 SoloMap 是 `12 × 12`,`(10,7)` / `(11,7)` 会被画成服务器上并不存在的掩体。要么让服务端下发格子属性,要么先删掉硬编码。详见 §13-3。
- **同一种子不可复现(宿主)**:根因已定位在 `FunGame.Testing-v3/WebAPI/Services/SoloGameSession.cs` 的 6 处 `Random.Shared`,详见 §13-1。
- **`ActionType` 阶段缺普攻可达的精确信号**:敌人仅落在施法射程内时客户端无法预判,每回合会白提交一次普攻(现由客户端提示兜底)。修法与等价性证明见 §13-2。
### 测试环境(不涉及产品,但会浪费排查时间)
- 本机 Bash 工具的 PATH 是坏的(`dirname` / `ls` / `head` 全部 not found),每条命令前要 `export PATH="/usr/bin:/bin:/mingw64/bin:$PATH"`。
- PowerShell 工具不回显 stdout,只能看 exit code;要看输出必须走 Bash。
- 把多个 Godot 无头测试串在同一个 shell 循环里会超出工具超时被 SIGTERM,而管道缓冲会让**全部输出丢失**(看起来像「什么都没跑」)。逐个跑,或用 `run_in_background`。
- `GD.PushWarning` 会打印完整 C# 调用栈,测试输出噪音很大;过滤时用 `grep -E "^(SOLO_|PHASE_)"`。
- Godot 的 `CreateTween` 要求节点在场景树内;静态自检里故意不入树的 `BattleAnimator` 必须在用例结束时 `Free()`,否则退出时报 `ObjectDB instance was leaked`。
## 13. 三条遗留问题的修复优先级排序
排序依据:**先修「让度量本身不可信」的问题,再修「体验/协议不精确」的问题,最后修「纯表现」的问题。**
> **状态:三条全部已实现并通过回归**(验证结果见本节末尾)。修复过程中另外挖出 4 个问题,其中 2 个是真实产品缺陷,见 §13-4。
| 顺序 | 问题 | 优先级 | 难度 | 归属仓库 | 一句话理由 |
|---|---|---|---|---|---|
| 1 | 同一种子不可复现 | P0 | 低 | FunGame.Testing-v3 | 它让「回归通过/失败」无法区分改动效果与抽签结果 |
| 2 | `ActionType` 缺普攻可达信号 | P1 | 低-中 | Testing-v3 + osm-game | 消除每回合一次白提交与客户端猜算,且能顺带让 #1 的度量更干净 |
| 3 | 灰盒地图与权威不一致 | P2 | 极低 | osm-game | 纯表现、无玩法影响,4 个子问题里 3 个当前触发不了 |
### 13-1(P0)同一种子不可复现 —— 根因已定位
**不是**「客户端决策时序」也**不是**「队列里某个未受种子控制的输入」。`Seed` 确实传进了 `GamingQueue`(`GamingQueue.cs:421-422` 用 `Seed` 构造 `Random`),问题在于**开局装配整段发生在队列之外,用的是进程级 `Random.Shared`**:
| 行号 | 代码 | 后果 |
|---|---|---|
| `SoloGameSession.cs:313` | `.OrderBy(_ => Random.Shared.Next())` + `Take(CharacterCount)` | **每局抽到的角色及其顺序都不同** —— 测试又取 `Characters.FirstOrDefault()`,等于每局随机换人 |
| `SoloGameSession.cs:665` | `FunGameService.Skills.OrderBy(_ => Random.Shared.Next()).Take(3)` | 每局随机 3 个技能 |
| `SoloGameSession.cs:672` | `CommonPassiveSkills...Take(3)` | 每局随机 3 个被动 |
| `SoloGameSession.cs:679` | `CommonSuperSkills...Take(3)` | 每局随机 3 个爆发技 |
| `SoloGameSession.cs:394` | `free[Random.Shared.Next(free.Count)]` | 出生格随机 |
| `SoloGameSession.cs:651` | `BuildTeams` 里的洗牌 | 团队模式分队随机(本测试 `teamMode=false`,暂不触发) |
补充证据:`Character.Random => GamingQueue?.Random ?? Random.Shared`(`Character.cs:30`),而 `PrepareCharacters`(`:315`)跑在 `character.NormalAttack.GamingQueue = queue`(`:389`)**之前** → 这段里任何走实体的随机都退化成 `Random.Shared`。
**修法**:`RunGame` 开头建一个 `Random rng = new(options.Seed ?? Random.Shared.Next());`,把上述 6 处换成 `rng`,并给 `PrepareCharacters` 加一个 `Random` 参数;同时把 `character.NormalAttack.GamingQueue = queue` 提到装配之前,让实体自身的随机回退也吃到种子。
**验收**:同 `Seed` 连跑 3 次,`SOLO_VERTICAL_OK` 里的 `moves` / `attackAttempts` 必须完全一致。
**实施结果**:`SoloGameSession.RunGame` 开头建 `Random rng = new(options.Seed ?? Random.Shared.Next())`,6 处 `Random.Shared` 全部换成 `rng`(`PrepareCharacters` / `BuildTeams` 增加 `Random` 参数)。同种子连跑 3 次结果:`moves=15 attackAttempts=0 attackReachableRounds=0` —— **逐字一致**(修复前同 seed 会出现 `moves` 1 与 4、`attackAttempts` 1 与 13)。
### 13-2(P1)`ActionType` 缺普攻可达信号
**现状口径**:`GamingQueue.cs:1261` 交给 `OnDecideAction` 的 `enemys` 是「攻击可达 ∪ 施法可达」,而 `SoloGameSession` 把它原样当 `enemys` / `enemyOptions` 下发(`:817-819`)。所以客户端只能判断「有没有敌人」,判断不了「打不打得着」。
**等价性证明**:引擎真正选普攻目标前会再用 ATR 收窄一次 ——
`GamingQueue.cs:1578-1585`:
```csharp
attackRange = _map.GetGridsByRange(realGrid, character.ATR, true);
enemys = [.. enemys.Where(attackRange.SelectMany(g => g.Characters).Contains)];
```
**修法(不需要改 FunGame.Core)**:在 `OnDecideAction` 里用同一个公开接口复现这一步,作为新字段下发:
```csharp
Grid? actorGrid = _map?.GetCharacterCurrentGrid(actor);
HashSet<Character> inAttackRange = actorGrid is null
? []
: [.. _map!.GetGridsByRange(actorGrid, actor.ATR, true).SelectMany(g => g.Characters)];
// payload 新增:attackTargets = ctx.Enemys.Where(inAttackRange.Contains).Select(c => ToTargetOption(c, actor))
```
客户端 `ActionTypePayload` 加 `AttackTargets`,普攻按钮门控与回归测试都改用它 → 白提交消失(`attackAttempts` 应恒为 1)。
**成本/风险**:`GetGridsByRange` 是 O(range²),但 `SoloMap` 已覆写把 range 压到 `(12-1)+(12-1)=22`(`SoloGameSession.cs:1506-1510`),每回合一次,可忽略。
**实施结果**:服务端在 `OnDecideAction` 里下发 `attackTargets`(`TargetOption` 列表)与 `canNormalAttack`;客户端 `ActionTypePayload` 增加两个可空字段,`DecisionUiRules.IsNormalAttackReachable` 统一口径(严格口径优先,旧服务端退回宽口径),`BattleScreen` 与回归测试都改用它。真实对局中抓到的字段组合证实了修复的必要性:
```text
payload kind=ActionType actorGrid=69 atr=3 enemys=1 enemyOptions=1 attackTargets=0 canNormalAttack=False
```
`enemys=1` 而 `attackTargets=0` —— 旧客户端看到前者就会提交普通攻击并被服务器作废,正是白提交的来源,现在被精确排除。
**门控的真实验证**:回归测试原先「打一次就不再移动」,导致敌人永远进不了 ATR、门控验证不到。改成「先保证走一步 → 能打就打 → 打不着继续靠近」后,真实局面里拿到了
`attackReachableRounds=1 attackAttempts=1 attackCancelled=0 attackGateVerified=True`:
服务器说可达 → 客户端据此提交普通攻击 → 进入选目标阶段且**零作废**,门控闭环。连跑 3 次结果逐字一致。
### 13-3(P2)灰盒地图与权威不一致
拆成 4 个独立子问题,**只有 1a 今天可见**:
| 子问题 | 现状 | 今天能否触发 |
|---|---|---|
| 1a 硬编码 4 个掩体 | 协议里根本没有掩体概念(`GridDto` 只有 `Id/X/Y/Z/Color/Characters`,计划 §10 明确不含掩体规则),纯装饰 | ✅ 能(画出不存在的掩体,误导玩家) |
| 1b 从不消费 `grid.color` | 全代码库没有任何地方给 `Grid.Color` 赋值 → 全图都是默认 `Gray` | ❌ 消费了也不改画面,只是协议诚实性 |
| 1c 地面绘制忽略 `grid.Z` | 单位位置**已经**用了 Z(`BattleScreen.cs:999/1034`),但地面始终按 Z=0 画 | ❌ `SoloMap.Height = 1` |
| 1d 地面按 `0..Length × 0..Width` 稠密矩形绘制,不读服务器坐标 | 与 `GridOverlay2D` 用服务器坐标的做法不一致 | ❌ 当前 `GameMap.Load` 就是稠密矩形且从 (0,0) 起 |
**建议**:把 `GreyboxMap2D` 的地面改成「按 `map.grids` 的真实坐标 + `color` 逐格绘制」(与 `GridOverlay2D` 同源),一次消掉 1a/1b/1d;1c 属于多层地形,留给后续阶段,先加注释说明。**最小改动版**:只删掉 `DrawCover(...)` 四行。
**实施结果**:采用了「按 `map.grids` 逐格绘制」的方案,一次消掉 1a/1b/1d:
- `GreyboxMap2D` 改为 `SetMap(SoloMapDto?)`,只画服务器给的格子,删掉全部硬编码掩体;
- 格心用 `grid.Z` 抬升(顺手消掉 1c 的隐患,与单位位置的算法一致);
- 服务器显式给过颜色时叠 45% 着色,默认 `Gray`(= `Grid.Color` 初始值,全图皆然)时保留灰盒棋盘配色;
- `GridOverlay2D` 的坐标表升级为 `Vector3I`,高亮与地面、单位共用同一个高度;
- `PhaseESmokeTest` 新增 `ground=true` 断言:稀疏地图(2 个格)只能画出 2 个格,设地图尺寸不会凭空造格。
### 13-4 修这三条时新发现的问题
按发现顺序,**已修**:
| # | 问题 | 归属 | 影响 | 处理 |
|---|---|---|---|---|
| 5 | 回归测试把毫秒传给了以「秒」为单位的等待函数:`DecisionTimeoutMs = 45_000` | osm-game(测试) | 每次等待实际是 **12.5 小时**。服务器一旦停止下发决策(对局结束/玩家被托管),测试就永远挂着 —— 这才是「卡死几分钟」的真凶,与客户端无关 | 常量改名为 `DecisionTimeoutSeconds = 20.0`;并区分「服务端主动静默」与故障:`!_store.IsStarted` 或等不到下一条决策时优雅收尾 |
| 6 | 日志抽屉逐行 `AppendText` 到开了 `fit_content` 的 `RichTextLabel` | osm-game(**真实缺陷**) | 每次追加都会重排整段文本,长局(几千行)退化成 O(n²),足以把主循环卡住到「连 SceneTreeTimer 都不再触发」 | 改为「关闭时只打脏标记、打开时一次性 `Text` 赋值」,节流 250ms,只渲染最后 500 行 |
| 7 | `WebSocketTransport.SendAsync` 没有超时 | osm-game(**真实缺陷**) | 半死连接(对端不再读取)会让 `SendAsync` 永久不返回,把界面/测试挂死 | 发送 10s 超时、关闭握手 5s 超时;超时即 `Abort()` 交给自动重连 |
| 8 | 冒烟测试缺少故障可见性 | osm-game(测试基建) | godot 的 `GD.Print` 走 C stdio,重定向到文件/管道时是块缓冲;进程被 SIGTERM 时输出**整段丢失**,只剩引擎启动那几行,表现为「什么都没跑」 | 新增 `SoloTrace`(托管 stderr,不带缓冲)+ 300s 看门狗 + 2s 主循环心跳;断言失败先写 stderr 再写 stdout |
| 9 | 服务端放弃挂起决策时不通知客户端 | 两端(**真实缺陷**) | 对局结束 / 玩家被托管 / 断线后,客户端只能靠超时判断「为什么轮到我却什么都没发生」;更糟的是被兜底解决的 requestId 会留在 `_pendingRequests` 里,重连时被当作「仍在等待」重新补发,玩家看到一条回执早已无效的死决策 | 实现两端早已声明、服务端却从未发送的 `gaming.resolved`:`SoloGameSession.DropPendingDecisions(reason)` 在**托管 / 断线 / 收尾**三处发出 `{ requestId, kind, reason }` 并清掉本地记录(顺手从源头修掉 §12 记的那条);客户端 `BattleStore` 收到即清掉对应决策、写日志、弹提示,并暴露 `DroppedDecisionCount` 供测试判断「不必再等」;重连时客户端主动丢弃属于旧连接的挂起决策 |
| 10 | 选人弹窗「点不动」 | osm-game(**实机体验缺陷**,玩家实测发现) | 详情文本是整张角色说明书(几十行),而弹窗是**没有上限的 `CenterContainer` + 只在 tscn 里给了一个最小尺寸**:面板高度完全由内容决定,长文本把它顶到视口之外,确认/取消按钮随之落到屏幕外;同时候选用的是**下拉框**(一次只显示一项),10 个角色看起来「根本没有能点的地方」 | 三处一起改:① 面板改为按视口比例锚定(16%~84% × 8%~92%),不再由内容决定高度;② 详情放进 `ScrollContainer`(`size_flags_vertical=3`),长文本自己滚;③ 选项 > 3 个时改用 `ItemList` 可点击列表并置于详情上方,≤3 个才用下拉框。另外初始焦点给选择器而不是确认键(避免误按回车确定「10 选 1」的第一项);`SoloConnectionSmokeTest` 新增 `dialogFits` / `clickableList` 断言,用 10 个候选的真实对局把这条钉死。修复后实测:`panel=(307,86) 1305×907`、`list=(307,132) 1305×394 items=10`、`confirm=(968,945) 140×48`、`viewport=1920×1080` |
| 11 | 选完角色点确认没反应(玩家实测第二报) | osm-game(**实弹缺陷**) | 确认处理里留着一句为下拉框写的守卫 `if (_dialogValues.Count == 0 \|\| _decisionOptions.Selected < 0) return;`。走列表路径时那个下拉框已被 `Clear()` 并隐藏,`Selected` **恒为 -1** → 点确认静默返回,什么都不发生。上一轮五条回归全绿也没抓到,因为测试都是直接调 `BattleStore.SubmitDecisionAsync`,完全绕过了 GUI | 守卫改为只看 `_dialogValues.Count`,选中项一律从当前生效的控件读(列表 → `GetSelectedItems()`,下拉框 → `Selected`)。同时补上真正的 GUI 回归:`SOLO_SMOKE` 现在会在列表里**选第 2 个候选**(故意不选第一个)再**触发确认按钮的 `pressed` 信号**,并断言服务器开局的角色**就是所选的那个**——把断言临时改回旧守卫可复现出「点击确认后没有继续:dialogVisible=True」 |
| 12 | 候选 guid 与开局状态 guid 不是同一套 | **服务端**(FunGame.Testing-v3,**待办**) | `SelectCharacter` 候选下发的 guid 与开局后 `state.characters[].guid` **同名不同 guid**(同一角色两个 guid 空间)。服务端按对象/名字选中,对局本身正常;但任何「拿候选 guid 去状态里找角色」的客户端逻辑都会落空。`SOLO_SMOKE` 因此按**名字**断言(`guidConsistent=false` 会打进 trace 供追踪) | 未修。需要在服务端确认候选列表与队列内部角色实例是否被复制成不同对象(`Character.Copy()` 理论上保留 `Guid`,实测不成立),归一到同一个 guid 空间 |
**踩坑记录(诊断顺序,可复用)**:心跳仍在跳 ⇒ 主循环健康、是 await 链的问题;心跳停 ⇒ 主循环卡死。这一次就是靠「心跳继续但无新决策」把范围从「客户端卡死」收窄到「等待函数超时单位写错」。
**11 条已修 + 1 条服务端待办。** 第 10/11 条都是玩家跑实机客户端发现的 —— 五条 headless 回归全绿也照样漏,
因为「能不能点」是版面问题、而「点了有没有用」是 GUI 逻辑问题 —— 两者都测不到逻辑断言里:
前者要**量几何**(面板是否在视口内、按钮是否可见、列表是否可点),
后者要**真的走一遍界面**(在列表里选一项 → 触发确认 → 校验服务端用的就是所选的那个)。
现在 `--solo-smoke-test` 这两层都覆盖了,且已验证它能把旧 bug 复现出来。 第 5~9 条是修前三条的副产品:其中 #6 / #7 / #9 是**真实产品缺陷**(会影响真人玩家,不只是测试)。回归的收尾方式也从「靠 20s 超时」变成「收到作废通知立刻收尾」,竖切回归单轮耗时由 40s+ 降到 12s。
+9 -5
View File
@@ -1,5 +1,10 @@
; Engine configuration file. ; Engine configuration file.
; Edit this file through the Godot editor when possible. ; It's best edited using the editor UI and not directly,
; since the parameters that go here are not all obvious.
;
; Format:
; [section] ; section goes between []
; param=value ; assign values to parameters
config_version=5 config_version=5
@@ -19,8 +24,8 @@ GameSettings="*res://src/Autoload/GameSettings.cs"
[display] [display]
window/size/viewport_width=1920 window/size/viewport_width=1280
window/size/viewport_height=1080 window/size/viewport_height=720
window/size/window_width_override=1280 window/size/window_width_override=1280
window/size/window_height_override=720 window/size/window_height_override=720
window/stretch/mode="canvas_items" window/stretch/mode="canvas_items"
@@ -37,5 +42,4 @@ locale/fallback="zh_CN"
renderer/rendering_method="gl_compatibility" renderer/rendering_method="gl_compatibility"
renderer/rendering_method.mobile="gl_compatibility" renderer/rendering_method.mobile="gl_compatibility"
environment/defaults/default_clear_color=Color(0.027, 0.039, 0.055, 1) environment/defaults/default_clear_color=Color(0.165, 0.235, 0.294, 1)
+93 -3
View File
@@ -31,6 +31,14 @@ public partial class BattleStore : Node
[Signal] [Signal]
public delegate void GameFinishedEventHandler(string winnerName); public delegate void GameFinishedEventHandler(string winnerName);
/// <summary>重连后完成恢复流程(已发出 gaming.resume,或在无进行中对局时直接返回)。</summary>
[Signal]
public delegate void ConnectionRecoveredEventHandler();
/// <summary>服务器单方面放弃了一条挂起决策(对局结束 / 接管 / 断线)。</summary>
[Signal]
public delegate void DecisionDroppedEventHandler(string requestId, string reason);
private GameSession _session = null!; private GameSession _session = null!;
private bool _submissionInFlight; private bool _submissionInFlight;
@@ -41,16 +49,25 @@ public partial class BattleStore : Node
public string? GameId { get; private set; } public string? GameId { get; private set; }
public bool IsStarted { get; private set; } public bool IsStarted { get; private set; }
public bool IsWaitingForStart { get; private set; } public bool IsWaitingForStart { get; private set; }
public bool IsResuming { get; private set; }
public long LastPongTimestamp { get; private set; } public long LastPongTimestamp { get; private set; }
public bool IsSubmittingDecision => _submissionInFlight; public bool IsSubmittingDecision => _submissionInFlight;
/// <summary>服务器放弃过的决策数;测试用它判断「不必再等这条决策」,而不是干等到超时。</summary>
public int DroppedDecisionCount { get; private set; }
public string? LastDroppedRequestId { get; private set; }
public string? LastDropReason { get; private set; }
private readonly List<string> _logLines = []; private readonly List<string> _logLines = [];
private readonly HashSet<string> _answeredRequestIds = new(StringComparer.Ordinal);
public override void _Ready() public override void _Ready()
{ {
_session = GetNode<GameSession>("/root/GameSession"); _session = GetNode<GameSession>("/root/GameSession");
_session.MessageReceived += OnMessageReceived; _session.MessageReceived += OnMessageReceived;
_session.SessionError += OnSessionError; _session.SessionError += OnSessionError;
_session.Reconnected += OnSessionReconnected;
} }
public async Task StartGameAsync(SoloStartOptions? options = null) public async Task StartGameAsync(SoloStartOptions? options = null)
@@ -76,6 +93,7 @@ public partial class BattleStore : Node
} }
_submissionInFlight = true; _submissionInFlight = true;
_answeredRequestIds.Add(decision.RequestId);
PendingDecision = null; PendingDecision = null;
SetSelectionMode(BattleSelectionMode.WaitingServer); SetSelectionMode(BattleSelectionMode.WaitingServer);
EmitSignal(SignalName.DecisionChanged); EmitSignal(SignalName.DecisionChanged);
@@ -123,6 +141,47 @@ public partial class BattleStore : Node
{ {
_session.MessageReceived -= OnMessageReceived; _session.MessageReceived -= OnMessageReceived;
_session.SessionError -= OnSessionError; _session.SessionError -= OnSessionError;
_session.Reconnected -= OnSessionReconnected;
}
}
/// <summary>
/// 重连成功后的恢复流程:对局还在跑就发 <c>gaming.resume</c>,
/// 服务器会把这条新连接接管到仍在运行的对局上,并补发完整快照与仍在等待的决策请求。
/// 若本局已经结束(或根本没开局),只通知界面刷新,不发 resume。
/// </summary>
private async void OnSessionReconnected()
{
// 上一个连接的挂起决策已经作废:服务端在断线时就用 null 兜底解决了它(引擎早已继续走),
// 正确行为是等服务器重新下发,而不是让界面继续显示一条回执无效的死决策。
if (PendingDecision is not null)
{
AppendLog(["[客户端] 重连后丢弃上一个连接遗留的挂起决策。"]);
PendingDecision = null;
SetSelectionMode(BattleSelectionMode.Watching);
EmitSignal(SignalName.DecisionChanged);
}
if (string.IsNullOrEmpty(GameId) || !IsStarted)
{
EmitSignal(SignalName.ConnectionRecovered);
return;
}
IsResuming = true;
try
{
AppendLog(["[客户端] 连接已恢复,发送 gaming.resume 请求接管本局。"]);
await _session.ResumeSoloGameAsync();
}
catch (Exception exception)
{
EmitSignal(SignalName.ProtocolError, $"重连后恢复对局失败:{exception.Message}");
}
finally
{
IsResuming = false;
EmitSignal(SignalName.ConnectionRecovered);
} }
} }
@@ -208,20 +267,50 @@ public partial class BattleStore : Node
} }
case SoloMessageTypes.GamingRequest: case SoloMessageTypes.GamingRequest:
PendingDecision = envelope.Data.Deserialize<SoloDecisionRequest>(ProtocolJson.Options); {
ApplyDecisionMode(PendingDecision?.Kind); var request = envelope.Data.Deserialize<SoloDecisionRequest>(ProtocolJson.Options);
if (request is null)
{
break;
}
// 重连时服务器会补发「仍在等待」的决策请求,但它同时会把断线那一刻已被兜底解决的旧请求
// 一起补发(SoloGameSession.MarkDisconnected 只清 _pending,不清 _pendingRequests)。
// 我们已经回答过的 requestId 必然属于作废的那批,直接忽略,否则界面会卡在一条死决策上。
if (_answeredRequestIds.Contains(request.RequestId))
{
AppendLog([$"[客户端] 忽略重连后补发的已作废决策({request.Kind})。"]);
break;
}
PendingDecision = request;
ApplyDecisionMode(request.Kind);
EmitSignal(SignalName.DecisionChanged); EmitSignal(SignalName.DecisionChanged);
break; break;
}
case SoloMessageTypes.GamingResolved: case SoloMessageTypes.GamingResolved:
{ {
var resolved = envelope.Data.Deserialize<SoloResolvedEvent>(ProtocolJson.Options); var resolved = envelope.Data.Deserialize<SoloResolvedEvent>(ProtocolJson.Options);
if (PendingDecision?.RequestId == resolved?.RequestId) if (resolved is null || string.IsNullOrEmpty(resolved.RequestId))
{
break;
}
DroppedDecisionCount++;
LastDroppedRequestId = resolved.RequestId;
LastDropReason = resolved.Reason;
AppendLog(
[$"[客户端] 服务器放弃决策({resolved.Kind}):{resolved.Reason}"]);
if (PendingDecision?.RequestId == resolved.RequestId)
{ {
PendingDecision = null; PendingDecision = null;
SetSelectionMode(BattleSelectionMode.Watching); SetSelectionMode(BattleSelectionMode.Watching);
EmitSignal(SignalName.DecisionChanged); EmitSignal(SignalName.DecisionChanged);
} }
EmitSignal(SignalName.DecisionDropped, resolved.RequestId, resolved.Reason);
break; break;
} }
@@ -298,6 +387,7 @@ public partial class BattleStore : Node
IsStarted = false; IsStarted = false;
IsWaitingForStart = false; IsWaitingForStart = false;
_logLines.Clear(); _logLines.Clear();
_answeredRequestIds.Clear();
_submissionInFlight = false; _submissionInFlight = false;
SetSelectionMode(BattleSelectionMode.Watching); SetSelectionMode(BattleSelectionMode.Watching);
} }
+222 -34
View File
@@ -14,10 +14,18 @@ public enum SessionState
Faulted Faulted
} }
/// <summary>
/// WebSocket 生命周期 + 心跳 + 退避重连。只负责「连接」这一层:
/// 重连成功后发出 <see cref="ReconnectedEventHandler"/>,是否要 <c>gaming.resume</c>
/// 由 <see cref="BattleStore"/> 按对局状态决定(会话层不该知道对局的存在)。
/// </summary>
public partial class GameSession : Node public partial class GameSession : Node
{ {
private const ulong HeartbeatIntervalMs = 15_000; private const ulong HeartbeatIntervalMs = 15_000;
/// <summary>重连退避:1s → 2s → 4s → 8s → 之后固定 15s。</summary>
private static readonly double[] ReconnectBackoffSeconds = [1, 2, 4, 8, 15];
[Signal] [Signal]
public delegate void StateChangedEventHandler(int state); public delegate void StateChangedEventHandler(int state);
@@ -27,34 +35,53 @@ public partial class GameSession : Node
[Signal] [Signal]
public delegate void SessionErrorEventHandler(string message); public delegate void SessionErrorEventHandler(string message);
/// <summary>重连成功:新连接已建立,可以补发 gaming.resume 并等待服务器补发快照。</summary>
[Signal]
public delegate void ReconnectedEventHandler();
private readonly ConcurrentQueue<string> _incomingMessages = new(); private readonly ConcurrentQueue<string> _incomingMessages = new();
private readonly ConcurrentQueue<Exception> _incomingErrors = new(); private readonly ConcurrentQueue<Exception> _incomingErrors = new();
private readonly ConcurrentQueue<string> _pendingNotices = new();
private readonly ConcurrentQueue<SessionState> _pendingStates = new(); private readonly ConcurrentQueue<SessionState> _pendingStates = new();
private IGameTransport? _transport; private IGameTransport? _transport;
private int _sequence; private int _sequence;
private ulong _nextHeartbeatAt; private ulong _nextHeartbeatAt;
private bool _intentionalDisconnect; private bool _intentionalDisconnect;
private bool _transportLost;
private Exception? _transportFault;
private bool _reconnectScheduled;
private bool _reconnectInFlight;
private ulong _nextReconnectAtMs;
private int _reconnectAttempt;
public SessionState State { get; private set; } = SessionState.Disconnected; public SessionState State { get; private set; } = SessionState.Disconnected;
public Uri? Endpoint { get; private set; } public Uri? Endpoint { get; private set; }
/// <summary>关闭后 <see cref="AbortConnection"/> 与自动重连都不再生效(测试用 Mock 时仍可开启)。</summary>
public bool AutoReconnect { get; set; } = true;
public int ReconnectAttempt => _reconnectAttempt;
public bool IsReconnecting => State == SessionState.Reconnecting;
public string? LastNotice { get; private set; }
/// <summary>距离下一次重连尝试的剩余秒数(0 表示正在连接)。供重连遮罩显示倒计时。</summary>
public double SecondsUntilReconnect
{
get
{
if (!_reconnectScheduled)
{
return 0;
}
var now = Time.GetTicksMsec();
return now >= _nextReconnectAtMs ? 0 : (_nextReconnectAtMs - now) / 1000.0;
}
}
public override void _Process(double delta) public override void _Process(double delta)
{ {
while (_pendingStates.TryDequeue(out var state)) DrainQueues();
{
SetState(state);
}
while (_incomingMessages.TryDequeue(out var message))
{
EmitSignal(SignalName.MessageReceived, message);
}
while (_incomingErrors.TryDequeue(out var exception))
{
SetState(SessionState.Faulted);
EmitSignal(SignalName.SessionError, exception.Message);
}
if (State == SessionState.Connected && Time.GetTicksMsec() >= _nextHeartbeatAt) if (State == SessionState.Connected && Time.GetTicksMsec() >= _nextHeartbeatAt)
{ {
@@ -64,6 +91,12 @@ public partial class GameSession : Node
ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
}); });
} }
if (_reconnectScheduled && !_reconnectInFlight && Time.GetTicksMsec() >= _nextReconnectAtMs)
{
_reconnectScheduled = false;
_ = AttemptReconnectAsync();
}
} }
public async Task<bool> ConnectAsync( public async Task<bool> ConnectAsync(
@@ -75,16 +108,14 @@ public partial class GameSession : Node
Endpoint = endpoint; Endpoint = endpoint;
_intentionalDisconnect = false; _intentionalDisconnect = false;
_sequence = 0; _sequence = 0;
_reconnectAttempt = 0;
_reconnectScheduled = false;
_reconnectInFlight = false;
SetState(SessionState.Connecting); SetState(SessionState.Connecting);
_transport = useMock ? new MockTransport() : new WebSocketTransport();
_transport.MessageReceived += OnMessageReceived;
_transport.Faulted += OnTransportFaulted;
_transport.Closed += OnTransportClosed;
try try
{ {
await _transport.ConnectAsync(endpoint, cancellationToken); await OpenTransportAsync(endpoint, useMock, cancellationToken);
_nextHeartbeatAt = Time.GetTicksMsec() + HeartbeatIntervalMs; _nextHeartbeatAt = Time.GetTicksMsec() + HeartbeatIntervalMs;
_pendingStates.Enqueue(SessionState.Connected); _pendingStates.Enqueue(SessionState.Connected);
return true; return true;
@@ -130,16 +161,48 @@ public partial class GameSession : Node
public async Task DisconnectAsync() public async Task DisconnectAsync()
{ {
_intentionalDisconnect = true; _intentionalDisconnect = true;
if (_transport is not null) _reconnectScheduled = false;
{ _reconnectInFlight = false;
DetachTransport(_transport); _reconnectAttempt = 0;
await _transport.DisposeAsync(); _transportLost = false;
_transportFault = null;
var transport = _transport;
_transport = null; _transport = null;
if (transport is not null)
{
DetachTransport(transport);
await DisposeQuietlyAsync(transport);
} }
SetState(SessionState.Disconnected); SetState(SessionState.Disconnected);
} }
/// <summary>
/// 强制中断连接(不握手),用于验证断线恢复或清理已卡死的 socket。
/// 与 <see cref="DisconnectAsync"/> 的区别:这属于「非计划中断」,会触发自动重连。
/// </summary>
public void AbortConnection()
{
if (_transport is null || _intentionalDisconnect)
{
return;
}
_transport.Abort();
}
/// <summary>跳过当前的退避等待,让下一次重连尝试立刻发生(遮罩上的「立即重连」按钮)。</summary>
public void RequestImmediateReconnect()
{
if (!_reconnectScheduled)
{
return;
}
_nextReconnectAtMs = Time.GetTicksMsec();
}
public override void _ExitTree() public override void _ExitTree()
{ {
if (_transport is not null) if (_transport is not null)
@@ -148,6 +211,122 @@ public partial class GameSession : Node
} }
} }
private async Task OpenTransportAsync(Uri endpoint, bool useMock, CancellationToken cancellationToken)
{
var stale = _transport;
_transport = null;
if (stale is not null)
{
// 旧连接已经死了,关掉它但不等它(半死 socket 的 CloseAsync 可能永久挂起)。
DetachTransport(stale);
_ = DisposeQuietlyAsync(stale);
}
_transport = useMock ? new MockTransport() : new WebSocketTransport();
_transport.MessageReceived += OnMessageReceived;
_transport.Faulted += OnTransportFaulted;
_transport.Closed += OnTransportClosed;
await _transport.ConnectAsync(endpoint, cancellationToken);
}
private async Task AttemptReconnectAsync()
{
if (Endpoint is null || _reconnectInFlight)
{
return;
}
_reconnectInFlight = true;
try
{
await OpenTransportAsync(Endpoint, useMock: false, CancellationToken.None);
_reconnectAttempt = 0;
_nextHeartbeatAt = Time.GetTicksMsec() + HeartbeatIntervalMs;
SetState(SessionState.Connected);
EmitSignal(SignalName.Reconnected);
}
catch (Exception exception)
{
_transportFault = exception;
ScheduleReconnect(exception.Message);
}
finally
{
_reconnectInFlight = false;
}
}
private void ScheduleReconnect(string reason)
{
if (_intentionalDisconnect || Endpoint is null)
{
SetState(SessionState.Disconnected);
return;
}
_reconnectAttempt = Math.Min(_reconnectAttempt + 1, 1_000);
var delay = BackoffSeconds(_reconnectAttempt);
_nextReconnectAtMs = Time.GetTicksMsec() + (ulong)(delay * 1_000);
_reconnectScheduled = true;
SetState(SessionState.Reconnecting);
if (!string.IsNullOrWhiteSpace(reason))
{
_pendingNotices.Enqueue(
$"连接中断({reason}),{delay:0.#}s 后进行第 {_reconnectAttempt} 次重连……");
}
}
private static double BackoffSeconds(int attempt)
{
var index = Math.Clamp(attempt - 1, 0, ReconnectBackoffSeconds.Length - 1);
return ReconnectBackoffSeconds[index];
}
private void DrainQueues()
{
while (_pendingStates.TryDequeue(out var state))
{
SetState(state);
}
while (_incomingMessages.TryDequeue(out var message))
{
EmitSignal(SignalName.MessageReceived, message);
}
if (_transportLost)
{
_transportLost = false;
var reason = _transportFault?.Message;
_transportFault = null;
if (_intentionalDisconnect || !AutoReconnect || Endpoint is null)
{
SetState(SessionState.Disconnected);
}
else
{
ScheduleReconnect(reason ?? "连接已关闭");
}
}
while (_incomingErrors.TryDequeue(out var exception))
{
LastNotice = exception.Message;
EmitSignal(SignalName.SessionError, exception.Message);
if (_intentionalDisconnect || !AutoReconnect || Endpoint is null)
{
SetState(SessionState.Faulted);
}
}
while (_pendingNotices.TryDequeue(out var notice))
{
LastNotice = notice;
EmitSignal(SignalName.SessionError, notice);
}
}
private async Task SendEnvelopeAsync<T>(string type, T data, CancellationToken cancellationToken = default) private async Task SendEnvelopeAsync<T>(string type, T data, CancellationToken cancellationToken = default)
{ {
if (_transport is null || !_transport.IsConnected) if (_transport is null || !_transport.IsConnected)
@@ -174,15 +353,13 @@ public partial class GameSession : Node
private void OnMessageReceived(string message) => _incomingMessages.Enqueue(message); private void OnMessageReceived(string message) => _incomingMessages.Enqueue(message);
private void OnTransportFaulted(Exception exception) => _incomingErrors.Enqueue(exception); private void OnTransportFaulted(Exception exception)
{
_transportFault = exception;
_transportLost = true;
}
private void OnTransportClosed() private void OnTransportClosed() => _transportLost = true;
{
if (!_intentionalDisconnect)
{
_pendingStates.Enqueue(SessionState.Disconnected);
}
}
private void DetachTransport(IGameTransport transport) private void DetachTransport(IGameTransport transport)
{ {
@@ -191,6 +368,18 @@ public partial class GameSession : Node
transport.Closed -= OnTransportClosed; transport.Closed -= OnTransportClosed;
} }
private static async Task DisposeQuietlyAsync(IGameTransport transport)
{
try
{
await transport.DisposeAsync();
}
catch (Exception)
{
// 旧连接已断,释放失败不影响重连。
}
}
private void SetState(SessionState state) private void SetState(SessionState state)
{ {
if (State == state) if (State == state)
@@ -202,4 +391,3 @@ public partial class GameSession : Node
EmitSignal(SignalName.StateChanged, (int)state); EmitSignal(SignalName.StateChanged, (int)state);
} }
} }
+10 -2
View File
@@ -7,9 +7,11 @@ public partial class GameSettings : Node
private const string MasterVolumeKey = "master_volume"; private const string MasterVolumeKey = "master_volume";
private const string NetworkSection = "network"; private const string NetworkSection = "network";
private const string SoloServerUrlKey = "solo_server_url"; private const string SoloServerUrlKey = "solo_server_url";
private const string DefaultSoloServerUrl = "ws://localhost:12030/ws/solo";
private const string PreviousDefaultSoloServerUrl = "ws://localhost:11030/ws/solo";
public float MasterVolume { get; private set; } = 1.0f; public float MasterVolume { get; private set; } = 1.0f;
public string SoloServerUrl { get; private set; } = "ws://localhost:11030/ws/solo"; public string SoloServerUrl { get; private set; } = DefaultSoloServerUrl;
public override void _Ready() public override void _Ready()
{ {
@@ -17,7 +19,13 @@ public partial class GameSettings : Node
if (config.Load(SettingsPath) == Error.Ok) if (config.Load(SettingsPath) == Error.Ok)
{ {
MasterVolume = (float)config.GetValue(AudioSection, MasterVolumeKey, 1.0f); MasterVolume = (float)config.GetValue(AudioSection, MasterVolumeKey, 1.0f);
SoloServerUrl = (string)config.GetValue(NetworkSection, SoloServerUrlKey, SoloServerUrl); SoloServerUrl = (string)config.GetValue(NetworkSection, SoloServerUrlKey, DefaultSoloServerUrl);
if (SoloServerUrl == PreviousDefaultSoloServerUrl)
{
SoloServerUrl = DefaultSoloServerUrl;
config.SetValue(NetworkSection, SoloServerUrlKey, SoloServerUrl);
config.Save(SettingsPath);
}
} }
ApplyAudioSettings(); ApplyAudioSettings();
+10
View File
@@ -142,6 +142,8 @@ public sealed record SoloGameState
public SoloMapDto? Map { get; init; } public SoloMapDto? Map { get; init; }
public IReadOnlyList<SoloCharacterDto> Characters { get; init; } = []; public IReadOnlyList<SoloCharacterDto> Characters { get; init; } = [];
public IReadOnlyList<SoloQueueEntryDto> Queue { get; init; } = []; public IReadOnlyList<SoloQueueEntryDto> Queue { get; init; } = [];
public IReadOnlyDictionary<string, IReadOnlyList<string>> RoundRewards { get; init; }
= new Dictionary<string, IReadOnlyList<string>>();
[JsonPropertyName("playerDP")] public SoloDecisionPointsDto? PlayerDp { get; init; } [JsonPropertyName("playerDP")] public SoloDecisionPointsDto? PlayerDp { get; init; }
public string? PlayerGuid { get; init; } public string? PlayerGuid { get; init; }
public string? CurrentActorGuid { get; init; } public string? CurrentActorGuid { get; init; }
@@ -166,10 +168,18 @@ public sealed record SoloStartEvent
public SoloGameState? State { get; init; } public SoloGameState? State { get; init; }
} }
/// <summary>
/// 服务器对一条挂起决策的最终交代。
/// <para>既用于正常回答,也用于「服务器单方面放弃这条决策」(对局结束 / 接管 / 断线)——
/// 后者让客户端不必靠超时去猜「为什么轮到我却什么都没发生」。</para>
/// </summary>
public sealed record SoloResolvedEvent public sealed record SoloResolvedEvent
{ {
public string RequestId { get; init; } = string.Empty; public string RequestId { get; init; } = string.Empty;
public string Kind { get; init; } = string.Empty; public string Kind { get; init; } = string.Empty;
/// <summary>放弃原因;正常回答时为空。</summary>
public string Reason { get; init; } = string.Empty;
} }
public sealed record SoloOverEvent public sealed record SoloOverEvent
+14
View File
@@ -50,6 +50,8 @@ public sealed record TargetOption
public double Hp { get; init; } public double Hp { get; init; }
public double MaxHp { get; init; } public double MaxHp { get; init; }
public long GridId { get; init; } public long GridId { get; init; }
public bool IsSelf { get; init; }
public bool IsTeammate { get; init; }
} }
public sealed record TargetsPayload public sealed record TargetsPayload
@@ -79,6 +81,18 @@ public sealed record ActionTypePayload
public IReadOnlyList<string> Teammates { get; init; } = []; public IReadOnlyList<string> Teammates { get; init; } = [];
public IReadOnlyList<TargetOption> EnemyOptions { get; init; } = []; public IReadOnlyList<TargetOption> EnemyOptions { get; init; } = [];
public IReadOnlyList<TargetOption> TeammateOptions { get; init; } = []; public IReadOnlyList<TargetOption> TeammateOptions { get; init; } = [];
/// <summary>
/// 普攻可达目标:严格按 ATR 算出的敌人子集,即「现在不移动就能打到的人」。
/// <para>为空 ⇒ 提交普通攻击必然被服务器作废(引擎在选普攻目标前会用同一口径再收窄一次),
/// 客户端应直接禁用按钮,而不是让玩家白提交一轮。</para>
/// <para>为 <c>null</c> 表示服务端没有下发该字段(旧版服务端),此时只能退回
/// <see cref="EnemyOptions"/> 的宽口径(攻击可达 ∪ 施法可达)判断,那是不够精确的必要条件。</para>
/// </summary>
public IReadOnlyList<TargetOption>? AttackTargets { get; init; }
/// <summary>普通攻击是否真的可达,等价于 <see cref="AttackTargets"/> 非空;为 null 表示旧版服务端。</summary>
public bool? CanNormalAttack { get; init; }
} }
public sealed record SkillSelectionPayload public sealed record SkillSelectionPayload
+112 -1
View File
@@ -11,9 +11,14 @@ public partial class PhaseCDecisionSmokeTest : Node
try try
{ {
VerifyActionPayload(); VerifyActionPayload();
VerifyAttackReachability();
VerifyInquiryPayload(); VerifyInquiryPayload();
VerifyContinuePayload();
VerifyCancellationDetection();
VerifyShapePreview(); VerifyShapePreview();
GD.Print("PHASE_C_DECISIONS_OK quotas=true details=true inquiry=true shapePreview=true"); GD.Print(
"PHASE_C_DECISIONS_OK quotas=true details=true attackReachability=true inquiry=true "
+ "continue=true cancellation=true shapePreview=true");
GetTree().Quit(0); GetTree().Quit(0);
} }
catch (Exception exception) catch (Exception exception)
@@ -63,6 +68,54 @@ public partial class PhaseCDecisionSmokeTest : Node
} }
} }
/// <summary>
/// 普攻可达判定必须「优先服务端的严格口径 attackTargets,旧服务端再退回宽口径」——
/// 反过来(或无脑相信 enemyOptions)就会在「敌人只在施法射程内」时误开放按钮,
/// 让玩家白提交一轮;而完全不回退又会让旧服务端的按钮永久禁用。
/// </summary>
private static void VerifyAttackReachability()
{
var enemyInCastRangeOnly = new ActionTypePayload
{
EnemyOptions = [new TargetOption { Guid = "e" }]
};
if (DecisionUiRules.IsNormalAttackReachable(enemyInCastRangeOnly) != true)
{
throw new InvalidOperationException("缺 attackTargets 时应退回 enemyOptions 的宽口径。");
}
var preciseUnreachable = new ActionTypePayload
{
EnemyOptions = [new TargetOption { Guid = "e" }],
AttackTargets = []
};
if (DecisionUiRules.IsNormalAttackReachable(preciseUnreachable) != false)
{
throw new InvalidOperationException(
"enemyOptions 非空但 attackTargets 为空时必须判定为不可达(这正是白提交的来源)。");
}
var preciseReachable = new ActionTypePayload
{
AttackTargets = [new TargetOption { Guid = "e" }]
};
if (DecisionUiRules.IsNormalAttackReachable(preciseReachable) != true)
{
throw new InvalidOperationException("attackTargets 非空应判定为可达。");
}
var noEnemies = new ActionTypePayload { AttackTargets = [] };
if (DecisionUiRules.IsNormalAttackReachable(noEnemies) != false)
{
throw new InvalidOperationException("没有任何敌人信息时应判定为不可达。");
}
if (DecisionUiRules.IsNormalAttackReachable(null) is not null)
{
throw new InvalidOperationException("没有负载时应返回 null(未知)而不是猜。");
}
}
private static void VerifyInquiryPayload() private static void VerifyInquiryPayload()
{ {
const string json = """ const string json = """
@@ -81,6 +134,64 @@ public partial class PhaseCDecisionSmokeTest : Node
} }
} }
/// <summary>
/// Continue 的协议形状静态覆盖:真实对局里是否下发 Continue 取决于服务器流程(需要玩家回合正常结束
/// 且未被 AI 托管),所以这里独立校验字段与倒计时,真实链路由 SoloVerticalSliceSmokeTest 观察记录。
/// </summary>
private static void VerifyContinuePayload()
{
const string json = """
{"requestId":"cont-1","kind":"Continue","timeoutMs":30000,
"payload":{"actorGuid":"actor","message":"本回合已结束,查看日志后点击继续. . ."}}
""";
var request = JsonSerializer.Deserialize<SoloDecisionRequest>(json, ProtocolJson.Options)
?? throw new InvalidOperationException("Continue request could not be deserialized.");
var payload = request.ReadPayload<ContinuePayload>();
if (request.Kind != SoloDecisionKinds.Continue
|| request.TimeoutMs != 30000
|| payload is null
|| string.IsNullOrWhiteSpace(payload.Message))
{
throw new InvalidOperationException("Continue payload fields were not preserved.");
}
}
/// <summary>
/// 服务器对"提交了但不可行"的行动没有拒绝回执,客户端只能靠紧邻的决策类型判断是否被作废。
/// 这里把这套判定钉死:正常链路不得误报,回到行动菜单才算取消。
/// </summary>
private static void VerifyCancellationDetection()
{
// 可行链路:后续决策是自己的下一步 —— 不能报错
var acceptedCases = new (string Action, string Next)[]
{
("Move", SoloDecisionKinds.TargetGrid),
("NormalAttack", SoloDecisionKinds.Targets),
("PreCastSkill", SoloDecisionKinds.Skill),
("UseItem", SoloDecisionKinds.Item),
("EndTurn", SoloDecisionKinds.ActionType)
};
foreach (var (action, next) in acceptedCases)
{
if (DecisionUiRules.DetectCancelledAction(action, next) is not null)
{
throw new InvalidOperationException($"False cancellation reported for {action} -> {next}.");
}
}
// 被作废:直接回到行动菜单
if (DecisionUiRules.DetectCancelledAction("NormalAttack", SoloDecisionKinds.ActionType) is not { } attackReason
|| !attackReason.Contains("普通攻击", StringComparison.Ordinal))
{
throw new InvalidOperationException("Cancelled normal attack was not surfaced to the player.");
}
if (DecisionUiRules.DetectCancelledAction("Move", SoloDecisionKinds.ActionType) is not { } moveReason
|| !moveReason.Contains("移动", StringComparison.Ordinal))
{
throw new InvalidOperationException("Cancelled move was not surfaced to the player.");
}
}
private static void VerifyShapePreview() private static void VerifyShapePreview()
{ {
var map = new SoloMapDto var map = new SoloMapDto
@@ -0,0 +1 @@
uid://ciew5mtwvhy7u
+338
View File
@@ -0,0 +1,338 @@
using OSM.Client.Contracts;
using OSM.Client.Screens.Battle;
using OSM.Client.Units;
using OSM.Client.World;
namespace OSM.Client.Diagnostics;
/// <summary>
/// 阶段 E 的静态自检:快照差分、表现队列行为、HUD 版面。
/// <para>不连服务器,纯离线校验表现层规则——真实对局里的表现由 <c>--solo-vertical-smoke-test</c>
/// 与 <c>--solo-reconnect-smoke-test</c> 覆盖。</para>
/// </summary>
public partial class PhaseESmokeTest : Node
{
private PackedScene _unitViewScene = null!;
private int _skips;
public override void _Ready()
{
_unitViewScene = GD.Load<PackedScene>("res://src/Units/UnitView.tscn");
_ = RunAsync();
}
private async Task RunAsync()
{
try
{
VerifySnapshotDiff();
VerifyAnimatorQueue();
VerifyGreyboxGround();
// Control 的版面在首帧之后才结算,等两帧再量。
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var hudChecked = VerifyHudLayout();
GD.Print(
"PHASE_E_OK diff=true animator=true cancellation=true ground=true "
+ $"hudLayout={hudChecked.ToString().ToLowerInvariant()}");
GetTree().Quit(0);
}
catch (Exception exception)
{
GD.PushError($"PHASE_E_FAILED {exception.Message}");
GetTree().Quit(1);
}
}
// ==================== 快照差分 ====================
private static IReadOnlyList<BattleAnimationRequest> Build(
SoloGameState? previous,
SoloGameState? current) => BattleSnapshotDiff.Build(previous, current);
private static void VerifySnapshotDiff()
{
if (Build(null, State(("a", 1, 100, false))).Count != 0)
{
throw new InvalidOperationException("首帧不应产生补间任务。");
}
RequireSingle(Build(State(("a", 1, 100, false)), State(("a", 2, 100, false))), BattleAnimationKind.Move);
// 同格子 + 掉血 = 纯受击,量值就是权威血量差
var hit = RequireSingle(Build(State(("a", 1, 100, false)), State(("a", 1, 73, false))), BattleAnimationKind.Hit);
if (Math.Abs(hit.Magnitude - 27) > 0.001)
{
throw new InvalidOperationException($"受击量值应为 27,实际 {hit.Magnitude}。");
}
var heal = RequireSingle(Build(State(("a", 1, 40, false)), State(("a", 1, 55, false))), BattleAnimationKind.Heal);
if (Math.Abs(heal.Magnitude - 15) > 0.001)
{
throw new InvalidOperationException($"治疗量值应为 15,实际 {heal.Magnitude}。");
}
// 致命一击:先受击再淘汰,顺序不能反
var kill = Build(State(("a", 5, 30, false)), State(("a", 5, 0, true)));
if (kill.Count != 2
|| kill[0].Kind != BattleAnimationKind.Hit
|| kill[1].Kind != BattleAnimationKind.Eliminate)
{
throw new InvalidOperationException(
$"致命一击应产生 [Hit, Eliminate],实际 [{string.Join(",", kill.Select(item => item.Kind))}]。");
}
var respawn = Build(State(("a", 5, 0, true)), State(("a", 9, 100, false)));
if (!respawn.Any(item => item.Kind == BattleAnimationKind.Respawn))
{
throw new InvalidOperationException("复活应产生 Respawn 任务。");
}
// 中途出现的单位(召唤/新入场)直接以权威状态现身,不补间
if (Build(State(("a", 1, 100, false)), State(("a", 1, 100, false), ("b", 3, 50, false))).Count != 0)
{
throw new InvalidOperationException("新出现的单位不应补间。");
}
// 移动 + 受击同时发生:两条都要有
var mixed = Build(State(("a", 1, 100, false)), State(("a", 4, 90, false)));
if (mixed.Count != 2
|| mixed[0].Kind != BattleAnimationKind.Move
|| mixed[1].Kind != BattleAnimationKind.Hit)
{
throw new InvalidOperationException(
$"移动+受击应产生 [Move, Hit],实际 [{string.Join(",", mixed.Select(item => item.Kind))}]。");
}
}
private static BattleAnimationRequest RequireSingle(
IReadOnlyList<BattleAnimationRequest> requests,
BattleAnimationKind expected)
{
if (requests.Count != 1 || requests[0].Kind != expected)
{
throw new InvalidOperationException(
$"期望只有一条 {expected},实际 [{string.Join(",", requests.Select(item => item.Kind))}]。");
}
return requests[0];
}
private static SoloGameState State(
params (string Guid, long GridId, double Hp, bool Eliminated)[] characters)
{
return new SoloGameState
{
GameId = "phase-e",
Round = 1,
Characters = characters
.Select(entry => new SoloCharacterDto
{
Guid = entry.Guid,
GridId = entry.GridId,
Hp = entry.Hp,
MaxHp = 100,
IsEliminated = entry.Eliminated
})
.ToArray()
};
}
// ==================== 表现队列 ====================
private void VerifyAnimatorQueue()
{
var animator = new BattleAnimator();
// 故意不进场景树:手动推进 _Process,静态自检才具备确定性。
var unit = _unitViewScene.Instantiate<UnitView>();
AddChild(unit);
unit.ApplySnapshot(
new SoloCharacterDto { Guid = "a", Hp = 60, MaxHp = 100, GridId = 1 },
isFriendly: true,
isCurrentActor: false,
isSelectable: false,
worldPosition: new Vector2(100, 100));
animator.Initialize(_ => unit);
animator.SkipCalled += _ => _skips++;
animator.Submit(
[new BattleAnimationRequest("a", BattleAnimationKind.Move, 0)],
_ => new Vector2(200, 100));
if (animator.PendingCount != 1)
{
throw new InvalidOperationException($"入队后应只有 1 条待播任务,实际 {animator.PendingCount}。");
}
if (!animator.TakesOverPosition("a"))
{
throw new InvalidOperationException("有待播 Move 时表现层必须接管位置。");
}
if (animator.TakesOverHp("a"))
{
throw new InvalidOperationException("只有 Move 时不应接管血条。");
}
// 同棋子连续移动要合并(否则快速连招会把队列堆满过期补间)
animator.Submit(
[new BattleAnimationRequest("a", BattleAnimationKind.Move, 0)],
_ => new Vector2(300, 100));
if (animator.PendingCount != 1 || animator.MergedTasks != 1)
{
throw new InvalidOperationException(
$"连续移动应合并成 1 条,实际 {animator.PendingCount} 条 / 合并 {animator.MergedTasks} 次。");
}
// 血量任务与移动任务互不干扰
animator.Submit(
[new BattleAnimationRequest("a", BattleAnimationKind.Hit, 40)],
_ => new Vector2(300, 100));
if (animator.PendingCount != 2 || !animator.TakesOverPosition("a") || !animator.TakesOverHp("a"))
{
throw new InvalidOperationException("受击任务应独立入队,并同时接管血条。");
}
// 推进到队列排空:表现层必须能收敛,不能有卡住的任务
for (var step = 0; step < 400 && animator.IsBusy; step++)
{
animator._Process(0.05);
}
if (animator.IsBusy)
{
throw new InvalidOperationException("表现队列没有在合理步数内排空。");
}
if (unit.Position.DistanceTo(new Vector2(300, 100)) > 0.5)
{
throw new InvalidOperationException(
$"移动结束后棋子应停在权威位置 (300,100),实际 {unit.Position}。");
}
// 积压:超过上限必须自动丢弃并要求对齐,而不是无限堆积
var skipsBefore = _skips;
var backlog = Enumerable.Range(0, 80)
.Select(index => new BattleAnimationRequest($"unit-{index}", BattleAnimationKind.Move, 0))
.ToArray();
animator.Submit(backlog, _ => new Vector2(10, 10));
if (animator.IsBusy)
{
throw new InvalidOperationException("积压时应全部丢弃并请求对齐。");
}
if (_skips <= skipsBefore)
{
throw new InvalidOperationException("积压丢弃必须发出 SkipCalled,外部才会重新对齐权威快照。");
}
// 手动跳过
skipsBefore = _skips;
animator.Submit(
[new BattleAnimationRequest("a", BattleAnimationKind.Move, 0)],
_ => new Vector2(200, 200));
animator.SkipAll("手动跳过");
if (animator.IsBusy || _skips <= skipsBefore)
{
throw new InvalidOperationException("手动跳过必须清空队列并发出 SkipCalled。");
}
// 这个 animator 故意没进场景树,得自己释放,否则 Godot 退出时会报 ObjectDB 泄漏。
animator.Free();
}
// ==================== 灰盒地面(只画服务器真实存在的格子) ====================
/// <summary>
/// 地面必须严格由权威地图数据驱动:稀疏地图只画那几个格,不按 Length×Width 铺满,
/// 也不画协议里并不存在的掩体(旧实现硬编码了 4 个掩体)。
/// </summary>
private void VerifyGreyboxGround()
{
var ground = new GreyboxMap2D();
AddChild(ground);
var sparseMap = new SoloMapDto
{
Length = 12,
Width = 12,
Grids =
[
new SoloGridDto { Id = 7, X = 3, Y = 1, Z = 0, Color = "Gray" },
new SoloGridDto { Id = 8, X = 3, Y = 2, Z = 1, Color = "Red" }
]
};
ground.SetMap(sparseMap);
if (ground.DrawnGrids.Count != 2)
{
throw new InvalidOperationException(
$"地面应只画服务器给的 2 个格,实际 {ground.DrawnGrids.Count} 个。");
}
// 再设一次尺寸不能凭空造出格子(旧实现按 MapSize 铺满矩形)
ground.SetMapSize(new Vector2I(12, 12));
if (ground.DrawnGrids.Count != 2)
{
throw new InvalidOperationException("设置地图尺寸不应产生协议外的格子。");
}
ground.SetMap(null);
if (ground.DrawnGrids.Count != 0)
{
throw new InvalidOperationException("传 null 应清空地面。");
}
ground.QueueFree();
}
// ==================== HUD 版面(16:9 缩放) ====================
private bool VerifyHudLayout()
{
var viewportSize = GetViewport().GetVisibleRect().Size;
if (viewportSize.X < 320 || viewportSize.Y < 240)
{
GD.PushWarning($"PHASE_E_HUD_SKIPPED 视口过小({viewportSize}),跳过版面检查。");
return false;
}
var battle = GetNode("/root/Main/BattleScreen");
var layout = battle.GetNode<Control>("HudLayer/SafeArea/Layout");
var dock = layout.GetNode<Control>("BottomRightActionDock");
var context = layout.GetNode<Control>("BottomContextBar");
var characterPanel = layout.GetNode<Control>("BottomLeftCharacterPanel");
var viewportRect = new Rect2(Vector2.Zero, viewportSize);
// 操作按钮必须完整落在视口内(窗口缩到 16:9 的最小尺寸时也不能被裁掉)
string[] buttons =
[
"MoveButton", "AttackButton", "SkillButton", "SuperSkillButton",
"ItemButton", "HideGridButton", "EndTurnButton", "LogButton"
];
foreach (var name in buttons)
{
var rect = dock.GetNode<Control>($"ActionGrid/{name}").GetGlobalRect();
if (!viewportRect.Encloses(rect))
{
throw new InvalidOperationException(
$"操作按钮 {name} 超出视口:{rect} 不在 {viewportRect} 内。");
}
}
var dockRect = dock.GetGlobalRect();
var contextRect = context.GetGlobalRect();
var characterRect = characterPanel.GetGlobalRect();
if (dockRect.Intersects(contextRect))
{
throw new InvalidOperationException($"操作坞与上下文栏重叠:{dockRect} ∩ {contextRect}。");
}
if (dockRect.Intersects(characterRect))
{
throw new InvalidOperationException($"操作坞与角色面板重叠:{dockRect} ∩ {characterRect}。");
}
if (contextRect.Intersects(characterRect))
{
throw new InvalidOperationException($"上下文栏与角色面板重叠:{contextRect} ∩ {characterRect}。");
}
return true;
}
}
+1
View File
@@ -0,0 +1 @@
uid://cqfkviv3hgsw2
+186 -9
View File
@@ -8,6 +8,7 @@ public partial class SoloConnectionSmokeTest : Node
private GameSession _session = null!; private GameSession _session = null!;
private BattleStore _store = null!; private BattleStore _store = null!;
public override void _Ready() public override void _Ready()
{ {
_session = GetNode<GameSession>("/root/GameSession"); _session = GetNode<GameSession>("/root/GameSession");
@@ -19,7 +20,7 @@ public partial class SoloConnectionSmokeTest : Node
{ {
try try
{ {
var endpoint = new Uri("ws://localhost:11030/ws/solo"); var endpoint = new Uri("ws://localhost:12030/ws/solo");
if (!await _session.ConnectAsync(endpoint)) if (!await _session.ConnectAsync(endpoint))
{ {
throw new InvalidOperationException("WebSocket connection failed."); throw new InvalidOperationException("WebSocket connection failed.");
@@ -28,7 +29,9 @@ public partial class SoloConnectionSmokeTest : Node
await WaitUntilAsync(() => _session.State == SessionState.Connected, 5.0); await WaitUntilAsync(() => _session.State == SessionState.Connected, 5.0);
await _store.StartGameAsync(new SoloStartOptions await _store.StartGameAsync(new SoloStartOptions
{ {
CharacterCount = 2, // 与客户端默认一致:10 个候选角色 —— 选人弹窗里塞的是最长的详情文本,
// 布局问题(撑出窗口、按钮点不到)必须在这个规模下才能暴露。
CharacterCount = 10,
TeamMode = false, TeamMode = false,
TeamSize = 1, TeamSize = 1,
MaxRound = 1, MaxRound = 1,
@@ -42,14 +45,13 @@ public partial class SoloConnectionSmokeTest : Node
await WaitUntilAsync( await WaitUntilAsync(
() => _store.PendingDecision?.Kind == SoloDecisionKinds.SelectCharacter, () => _store.PendingDecision?.Kind == SoloDecisionKinds.SelectCharacter,
10.0); 10.0);
await VerifyDecisionDialogFitsAsync();
var character = _store.PendingDecision! // 真正「点」一次:选第 2 个候选(故意不选第一个,防止「永远提交第 0 项」这类错),
.ReadPayload<SelectCharacterPayload>()? // 再用真实鼠标事件点确认。这一步是为了覆盖「界面能不能把选择送出去」——
.Characters // 之前的断言只看版面,测试又是直接调 BattleStore 提交,于是确认按钮里的守卫写错也照样全绿。
.FirstOrDefault() await ClickThroughCharacterSelectionAsync();
?? throw new InvalidOperationException("Server returned no selectable characters.");
await _store.SubmitDecisionAsync(new { characterGuid = character.Guid });
await WaitUntilAsync( await WaitUntilAsync(
() => _store.Snapshot is { GameId.Length: > 0, Characters.Count: > 0 }, () => _store.Snapshot is { GameId.Length: > 0, Characters.Count: > 0 },
10.0); 10.0);
@@ -58,7 +60,7 @@ public partial class SoloConnectionSmokeTest : Node
5.0); 5.0);
GD.Print( GD.Print(
$"SOLO_SMOKE_OK game={_store.Snapshot!.GameId} " $"SOLO_SMOKE_OK dialogFits=true clickableList=true clickSubmits=true game={_store.Snapshot!.GameId} "
+ $"round={_store.Snapshot.Round} characters={_store.Snapshot.Characters.Count} " + $"round={_store.Snapshot.Round} characters={_store.Snapshot.Characters.Count} "
+ $"units={GetTree().GetNodesInGroup("battle_unit").Count}"); + $"units={GetTree().GetNodesInGroup("battle_unit").Count}");
@@ -74,6 +76,181 @@ public partial class SoloConnectionSmokeTest : Node
} }
} }
/// <summary>
/// 决策弹窗必须「看得到、点得到」:整块面板与确认按钮都要落在视口内。
/// <para>详情文本是整张角色说明书(几十行),历史上它把没有任何上限的居中弹窗撑到超出窗口,
/// 确认/取消按钮被顶到屏幕外,玩家表现为「弹窗打不开也点不动」。
/// 现在详情在 ScrollContainer 里滚动、面板按视口比例定位,这条断言就是防它退化。</para>
/// </summary>
private async Task VerifyDecisionDialogFitsAsync()
{
// 容器排版在下一帧才结算。
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var dialog = GetNode<Control>("/root/Main/BattleScreen/OverlayLayer/DecisionDialog");
if (!dialog.Visible)
{
throw new InvalidOperationException("SelectCharacter 决策没有弹出决策弹窗。");
}
var panel = dialog.GetNode<Control>("DialogPanel");
var confirm = dialog.GetNode<Button>("DialogPanel/DialogContent/DialogButtons/ConfirmButton");
var info = dialog.GetNode<Control>("DialogPanel/DialogContent/InfoScroll");
var list = dialog.GetNode<ItemList>("DialogPanel/DialogContent/ChoiceList");
var dropdown = dialog.GetNode<OptionButton>("DialogPanel/DialogContent/Options");
var viewportRect = new Rect2(Vector2.Zero, GetViewport().GetVisibleRect().Size);
// 候选多时必须给可点击列表:下拉框一次只显示一项,玩家会以为「这里没东西可点」。
if (!list.Visible || dropdown.Visible)
{
throw new InvalidOperationException(
$"候选 {list.ItemCount} 个时应使用可点击列表(list.Visible={list.Visible} / Options.Visible={dropdown.Visible})。");
}
if (list.ItemCount < 10)
{
throw new InvalidOperationException($"候选列表应有 10 个角色,实际 {list.ItemCount}。");
}
if (list.GetGlobalRect().Size.Y < 60)
{
throw new InvalidOperationException($"候选列表高度过小({list.GetGlobalRect().Size.Y}),基本看不到候选。");
}
if (!viewportRect.Encloses(panel.GetGlobalRect()))
{
throw new InvalidOperationException(
$"决策弹窗超出视口:panel={panel.GetGlobalRect()} viewport={viewportRect}");
}
if (!viewportRect.Encloses(confirm.GetGlobalRect()))
{
throw new InvalidOperationException(
$"确认按钮不在视口内(点不到):confirm={confirm.GetGlobalRect()} viewport={viewportRect}");
}
if (confirm.Disabled)
{
throw new InvalidOperationException("选人弹窗的确认按钮不应是禁用状态。");
}
if (info.GetGlobalRect().Size.Y <= 0)
{
throw new InvalidOperationException("详情区高度为 0:长文本没有可滚动的区域。");
}
SoloTrace.Step(
$"dialog panel={panel.GetGlobalRect()} confirm={confirm.GetGlobalRect()} "
+ $"list={list.GetGlobalRect()} items={list.ItemCount} info={info.GetGlobalRect()} "
+ $"viewport={viewportRect}");
}
/// <summary>
/// 走完整的 GUI 路径完成选人:在列表里选第 2 个候选 → 真实鼠标点击确认 → 校验服务器真的用这个角色开局。
/// </summary>
private async Task ClickThroughCharacterSelectionAsync()
{
var dialog = GetNode<Control>("/root/Main/BattleScreen/OverlayLayer/DecisionDialog");
var list = dialog.GetNode<ItemList>("DialogPanel/DialogContent/ChoiceList");
var confirm = dialog.GetNode<Button>("DialogPanel/DialogContent/DialogButtons/ConfirmButton");
var options = _store.PendingDecision!
.ReadPayload<SelectCharacterPayload>()?
.Characters
?? throw new InvalidOperationException("选人负载为空。");
if (options.Count < 2)
{
throw new InvalidOperationException($"选人候选不足 2 个({options.Count}),无法验证「选中的就是生效的」。");
}
var expected = options[1];
list.Select(1);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
SoloTrace.Step($"dialog list selected index=1 guid={expected.Guid} name={expected.DisplayName}");
SoloTrace.Step(
$"candidates=[{string.Join(" | ", options.Select((option, index) => $"{index}:{option.Guid[..8]}"))}] "
+ $"pickedByList=[{string.Join(",", list.GetSelectedItems())}] listItems={list.ItemCount}");
await ClickControlAsync(confirm);
// 点击必须真的把决策提交出去,并且服务器开局用的就是「我点的那个」。
if (!await WaitForAsync(
() => !dialog.Visible && _store.Snapshot?.PlayerGuid is { Length: > 0 },
6.0))
{
throw new InvalidOperationException(
$"点击确认后没有继续:dialogVisible={dialog.Visible} "
+ $"playerGuid={_store.Snapshot?.PlayerGuid ?? "none"} "
+ $"pendingKind={_store.PendingDecision?.Kind ?? "none"}");
}
// 按「名字」判定,而不是按 guid:服务端下发的候选 guid 与开局状态里的 guid 目前不是同一套
// (同一个角色、同名不同 guid,见 docs §13-4 第 11 条),按 guid 断言会把一个服务端问题
// 误报成界面问题。玩家视角的保证是「我点的是谁,开局就是谁」。
var player = _store.Snapshot!.Characters
.FirstOrDefault(character => character.Guid == _store.Snapshot.PlayerGuid);
if (player is null)
{
throw new InvalidOperationException(
$"服务器给的 playerGuid={_store.Snapshot.PlayerGuid} 不在场上角色里:"
+ $"[{string.Join(", ", _store.Snapshot.Characters.Select(c => $"{c.Guid[..8]}:{c.DisplayName}"))}]");
}
if (!string.Equals(player.DisplayName, expected.DisplayName, StringComparison.Ordinal))
{
throw new InvalidOperationException(
$"选中的角色没有生效:点的是「{expected.DisplayName}」,服务器开局的是「{player.DisplayName}」。");
}
var guidConsistent = string.Equals(player.Guid, expected.Guid, StringComparison.Ordinal);
SoloTrace.Step(
$"selection applied: picked=\"{expected.DisplayName}\" serverPlayer=\"{player.DisplayName}\" "
+ $"guidConsistent={guidConsistent} "
+ (guidConsistent ? string.Empty : $"(payloadGuid={expected.Guid[..8]} stateGuid={player.Guid[..8]})"));
SoloTrace.Step($"dialog confirm clicked, playerGuid={_store.Snapshot.PlayerGuid}");
}
/// <summary>
/// 触发按钮的 <c>pressed</c> 信号 —— 真实点击最终也是走到这里,所以它覆盖的是
/// 「界面上的选择能不能真的送出去」这段处理逻辑(本轮 bug 就藏在这里)。
/// <para><b>已知限制</b>:headless(dummy 驱动)下 <c>Input.ParseInputEvent</c> 与
/// <c>Viewport.PushInput</c> 都进不了 GUI 命中链路(实测 <c>GuiGetHoveredControl()</c> 恒为 none),
/// 所以「鼠标能否命中按钮」这一层无法在这里覆盖,由 <see cref="VerifyDecisionDialogFitsAsync"/>
/// 的几何断言(按钮必须在视口内、列表必须可见可点)+ 手工验证兜底。</para>
/// </summary>
private async Task ClickControlAsync(Control control)
{
if (control is BaseButton button)
{
button.EmitSignal(BaseButton.SignalName.Pressed);
}
else
{
throw new InvalidOperationException($"只有按钮支持模拟点击,收到 {control.GetType().Name}。");
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
SoloTrace.Step($"clicked {control.GetPath()}");
}
private async Task<bool> WaitForAsync(Func<bool> predicate, double timeoutSeconds)
{
var startedAt = Time.GetTicksMsec();
var timeoutMs = timeoutSeconds * 1_000.0;
while (!predicate())
{
if (Time.GetTicksMsec() - startedAt >= timeoutMs)
{
return false;
}
await ToSignal(GetTree().CreateTimer(0.05), SceneTreeTimer.SignalName.Timeout);
}
return true;
}
private async Task WaitUntilAsync(Func<bool> predicate, double timeoutSeconds) private async Task WaitUntilAsync(Func<bool> predicate, double timeoutSeconds)
{ {
var startedAt = Time.GetTicksMsec(); var startedAt = Time.GetTicksMsec();
@@ -0,0 +1 @@
uid://be5sbseuje44n
+411
View File
@@ -0,0 +1,411 @@
using System.Net.Http;
using System.Text.Json;
using OSM.Client.Autoload;
using OSM.Client.Contracts;
namespace OSM.Client.Diagnostics;
/// <summary>
/// 阶段 D:断线恢复的真实回归。
/// <para>流程:连接 → 开局 → 选人 → 移动 → <b>暂停</b>(把服务器冻结在一个确定状态上,便于精确比对)
/// → 强制中断 socket(不握手)→ 校验服务器仍在运行 → 自动重连 → 补发 <c>gaming.resume</c>
/// → 比对「客户端恢复后的快照」与「服务器当前状态」是否逐项一致。</para>
/// <para>为什么先暂停:服务器在断线期间会继续推进对局(AI 托管),不冻结的话
/// 「客户端画面 == 服务器状态」这条断言永远在追一个移动目标。暂停由服务端闸门实现
/// (<c>SoloGameSession.SetPaused</c>),冻结后两侧读到的都是同一个权威状态。</para>
/// </summary>
public partial class SoloReconnectSmokeTest : Node
{
private const string SoloEndpoint = "ws://localhost:12030/ws/solo";
private const string StateEndpoint = "http://localhost:12030/api/solo/state";
private const double HpEpsilon = 0.000001;
private GameSession _session = null!;
private BattleStore _store = null!;
private SoloTestDriver _driver = null!;
// Godot 也有一个 HttpClient 类型,这里必须写全名消歧。
private readonly System.Net.Http.HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(15) };
private int _reconnectedSignals;
private int _snapshotsAfterResume;
private int _snapshotCounter;
private bool _countingSnapshots;
public override void _Ready()
{
_session = GetNode<GameSession>("/root/GameSession");
_store = GetNode<BattleStore>("/root/BattleStore");
_driver = new SoloTestDriver(_store, this);
_session.Reconnected += OnReconnected;
_store.SnapshotChanged += OnSnapshotChanged;
_ = RunAsync();
}
private void OnReconnected() => _reconnectedSignals++;
private void OnSnapshotChanged(int envelopeSequence)
{
_snapshotCounter++;
if (_countingSnapshots)
{
_snapshotsAfterResume++;
}
}
private async Task RunAsync()
{
try
{
if (!await _session.ConnectAsync(new Uri(SoloEndpoint)))
{
throw new InvalidOperationException("WebSocket connection failed.");
}
await _driver.WaitOrThrowAsync(() => _session.State == SessionState.Connected, 5.0);
await _store.StartGameAsync(new SoloStartOptions
{
CharacterCount = 2,
TeamMode = false,
TeamSize = 1,
MaxRound = 30,
MaxRespawnTimes = 0,
MaxScoreToWin = 0,
// 决策超时给足,避免测试期间服务器自己把挂起决策超时兜底掉
DecisionTimeoutSeconds = 60,
RequireContinue = false,
RoundDelayMs = 0,
DropItemsIntervalSeconds = 0,
Seed = 20260919
});
var decision = await _driver.AwaitDecisionAsync(10.0);
if (decision.Kind != SoloDecisionKinds.SelectCharacter)
{
throw new InvalidOperationException($"Expected SelectCharacter, got {decision.Kind}.");
}
var character = decision.ReadPayload<SelectCharacterPayload>()?
.Characters
.FirstOrDefault()
?? throw new InvalidOperationException("Server returned no selectable characters.");
decision = await _driver.SubmitAndAwaitNextAsync(
decision,
new { characterGuid = character.Guid },
15.0)
?? throw new InvalidOperationException(
"Server dropped the decision right after character selection.");
var gameId = _store.GameId
?? throw new InvalidOperationException("Server did not report a gameId.");
await _driver.WaitOrThrowAsync(
() => _store.Snapshot is { Map: not null } snapshot
&& snapshot.Characters.Count > 1,
15.0);
var moves = await AdvanceOnceAsync(decision);
if (moves == 0)
{
throw new InvalidOperationException(
"Reconnect test did not complete a movement before dropping the connection.");
}
// ---- 冻结服务器,拿到一个两侧可比对的权威状态 ----
await _session.SetPausedAsync(true);
await _driver.WaitOrThrowAsync(() => _store.Snapshot?.Paused == true, 10.0);
var serverBefore = await ReadServerStateAsync();
AssertGameMatches(serverBefore, gameId, expectRunning: true, expectPaused: true);
AssertClientMatchesServer("断线前", serverBefore, _store.Snapshot);
var pendingRequestId = _store.PendingDecision?.RequestId;
var dropCounter = _snapshotCounter;
// ---- 强制中断:不握手,模拟网络被拔掉 ----
_countingSnapshots = true;
_session.AbortConnection();
await _driver.WaitOrThrowAsync(() => _session.IsReconnecting, 5.0);
var reconnectAttempt = _session.ReconnectAttempt;
if (reconnectAttempt < 1)
{
throw new InvalidOperationException("Automatic reconnect was not scheduled after the drop.");
}
// 验收 1:断线后服务器继续运行,且还是同一局
var serverDuringDrop = await ReadServerStateAsync();
AssertGameMatches(serverDuringDrop, gameId, expectRunning: true, expectPaused: true);
// ---- 自动重连 + gaming.resume ----
await _driver.WaitOrThrowAsync(() => _session.State == SessionState.Connected, 45.0);
if (_reconnectedSignals < 1)
{
throw new InvalidOperationException("Reconnect succeeded but no Reconnected signal was raised.");
}
await _driver.WaitOrThrowAsync(() => _snapshotsAfterResume > 0, 15.0);
await _driver.WaitOrThrowAsync(() => _snapshotCounter > dropCounter, 5.0);
// 断线那一刻挂起的决策在服务端已被兜底解决(MarkDisconnected 用 null 放了 TCS),
// 引擎随后照常推进 —— 因此重连后**不应**把它当作「仍在等待」重新补发,
// 否则玩家会看到一条回执早已无效的死决策。正确行为是:客户端丢掉它 / 收到作废通知。
var staleDecisionCleared = pendingRequestId is null
|| await _driver.WaitAsync(
() => _store.PendingDecision?.RequestId != pendingRequestId,
15.0);
if (!staleDecisionCleared)
{
throw new InvalidOperationException(
"Stale pending decision survived the reconnect; it should be dropped, not re-issued.");
}
if (!string.Equals(_store.GameId, gameId, StringComparison.Ordinal))
{
throw new InvalidOperationException(
$"Client switched games across the reconnect: {_store.GameId} != {gameId}.");
}
var serverAfter = await ReadServerStateAsync();
AssertGameMatches(serverAfter, gameId, expectRunning: true, expectPaused: true);
AssertClientMatchesServer("恢复后", serverAfter, _store.Snapshot);
GD.Print(
$"SOLO_RECONNECT_OK game={gameId} reconnected=true attempts={reconnectAttempt} "
+ "serverRunningDuringDrop=true resumeSent=true staleDecisionCleared=true "
+ $"snapshotsAfterResume={_snapshotsAfterResume} stateMatchesServer=true "
+ $"units={GetTree().GetNodesInGroup("battle_unit").Count}");
await _session.SetPausedAsync(false);
await _session.EndSoloGameAsync();
await _session.DisconnectAsync();
GetTree().Quit(0);
}
catch (Exception exception)
{
GD.PushError($"SOLO_RECONNECT_FAILED {exception.Message}");
await _session.DisconnectAsync();
GetTree().Quit(1);
}
}
/// <summary>用服务器列出的合法格走一步;返回实际完成的移动次数(0 表示没走成)。</summary>
private async Task<int> AdvanceOnceAsync(SoloDecisionRequest decision)
{
var moves = 0;
for (var step = 0; step < 12 && moves == 0; step++)
{
switch (decision.Kind)
{
case SoloDecisionKinds.ActionType:
{
var afterAction = await _driver.SubmitAndAwaitNextAsync(
decision,
new { actionType = "Move" },
30.0);
if (afterAction is null)
{
return moves;
}
decision = afterAction;
break;
}
case SoloDecisionKinds.TargetGrid:
{
var destination = _driver.PickMoveGrid(decision, _store.Snapshot);
if (destination is null)
{
var afterCancel = await _driver.SubmitAndAwaitNextAsync(
decision,
new { cancelled = true },
30.0);
if (afterCancel is null)
{
return moves;
}
decision = afterCancel;
break;
}
var origin = _driver.CurrentPlayerGridId();
var afterMove = await _driver.SubmitAndAwaitNextAsync(
decision,
new { gridId = destination.Value },
30.0);
if (_driver.CurrentPlayerGridId() != origin)
{
moves++;
}
if (afterMove is null)
{
return moves;
}
decision = afterMove;
break;
}
default:
{
var afterDefault = await _driver.SubmitAndAwaitNextAsync(
decision,
new { cancelled = true },
30.0);
if (afterDefault is null)
{
return moves;
}
decision = afterDefault;
break;
}
}
}
return moves;
}
private async Task<JsonElement> ReadServerStateAsync()
{
var json = await _http.GetStringAsync(StateEndpoint);
using var document = JsonDocument.Parse(json);
var root = document.RootElement.Clone();
// /api/solo/state 在读取竞争失败时会退化成只带 note 的诊断响应,这里显式拦下来。
if (!root.TryGetProperty("state", out var state)
|| state.ValueKind != JsonValueKind.Object
|| !state.TryGetProperty("characters", out _))
{
throw new InvalidOperationException($"REST /api/solo/state 未返回可用状态:{json}");
}
return root;
}
private static void AssertGameMatches(
JsonElement serverState,
string expectedGameId,
bool expectRunning,
bool expectPaused)
{
var actualGameId = serverState.TryGetProperty("gameId", out var id) ? id.GetString() : null;
if (!string.Equals(actualGameId, expectedGameId, StringComparison.Ordinal))
{
throw new InvalidOperationException(
$"Server is running a different game: {actualGameId} != {expectedGameId}.");
}
var running = serverState.TryGetProperty("running", out var runningElement)
&& runningElement.GetBoolean();
if (running != expectRunning)
{
throw new InvalidOperationException(
$"Server running={running}, expected {expectRunning} (game {expectedGameId}).");
}
var state = serverState.GetProperty("state");
if (!state.TryGetProperty("paused", out var pausedElement))
{
throw new InvalidOperationException("服务器状态缺少 paused 字段。");
}
var paused = pausedElement.GetBoolean();
if (paused != expectPaused)
{
throw new InvalidOperationException($"Server paused={paused}, expected {expectPaused}.");
}
}
/// <summary>
/// 验收 3:客户端画面与服务器权威状态逐项一致(单位集合、格子、血量、淘汰标记)。
/// </summary>
private void AssertClientMatchesServer(
string phase,
JsonElement serverState,
SoloGameState? clientState)
{
if (clientState is null)
{
throw new InvalidOperationException($"{phase}:客户端没有权威快照可比对。");
}
var serverCharacters = ReadServerCharacters(serverState);
var clientCharacters = clientState.Characters.ToDictionary(
character => character.Guid,
StringComparer.Ordinal);
if (serverCharacters.Count != clientCharacters.Count)
{
throw new InvalidOperationException(
$"{phase}:单位数量不一致,服务器 {serverCharacters.Count} / 客户端 {clientCharacters.Count}。");
}
foreach (var (guid, expected) in serverCharacters)
{
if (!clientCharacters.TryGetValue(guid, out var actual))
{
throw new InvalidOperationException($"{phase}:客户端缺少单位 {guid}。");
}
if (actual.GridId != expected.GridId)
{
throw new InvalidOperationException(
$"{phase}:单位 {guid} 格子不一致,服务器 {expected.GridId} / 客户端 {actual.GridId}。");
}
if (Math.Abs(actual.Hp - expected.Hp) > HpEpsilon)
{
throw new InvalidOperationException(
$"{phase}:单位 {guid} 血量不一致,服务器 {expected.Hp:0.###} / 客户端 {actual.Hp:0.###}。");
}
if (actual.IsEliminated != expected.Eliminated)
{
throw new InvalidOperationException($"{phase}:单位 {guid} 淘汰标记不一致。");
}
}
if (serverState.GetProperty("state").TryGetProperty("round", out var round)
&& round.GetInt32() != clientState.Round)
{
throw new InvalidOperationException(
$"{phase}:回合不一致,服务器 {round.GetInt32()} / 客户端 {clientState.Round}。");
}
}
private static Dictionary<string, (long GridId, double Hp, bool Eliminated)> ReadServerCharacters(
JsonElement serverState)
{
var result = new Dictionary<string, (long, double, bool)>(StringComparer.Ordinal);
var characters = serverState.GetProperty("state").GetProperty("characters");
foreach (var character in characters.EnumerateArray())
{
var guid = character.GetProperty("guid").GetString() ?? string.Empty;
result[guid] = (
character.GetProperty("gridId").GetInt64(),
ReadDouble(character, "hp", "HP"),
character.GetProperty("isEliminated").GetBoolean());
}
return result;
}
private static double ReadDouble(JsonElement element, string primaryName, params string[] alternateNames)
{
if (element.TryGetProperty(primaryName, out var value) && value.TryGetDouble(out var parsed))
{
return parsed;
}
foreach (var name in alternateNames)
{
if (element.TryGetProperty(name, out value) && value.TryGetDouble(out parsed))
{
return parsed;
}
}
throw new InvalidOperationException(
$"服务器状态缺少字段 {primaryName},实际字段:{string.Join(",", element.EnumerateObject().Select(p => p.Name))}");
}
}
@@ -0,0 +1 @@
uid://baa1bucpxv4q5
+124
View File
@@ -0,0 +1,124 @@
using OSM.Client.Autoload;
using OSM.Client.Contracts;
namespace OSM.Client.Diagnostics;
/// <summary>
/// 真实服务器冒烟测试共用的驱动:等待决策、按 requestId 串联提交回执、挑选合法移动格。
/// <para>与客户端主体同样的权威服务器原则:合法性只来自服务器下发的内容
/// (<c>TargetGrid.gridIds</c> / <c>Targets.targets</c>),距离只用于在多个合法项之间排序偏好。</para>
/// </summary>
public sealed class SoloTestDriver(BattleStore store, Node host)
{
public BattleStore Store { get; } = store;
public async Task<SoloDecisionRequest> AwaitDecisionAsync(double timeoutSeconds)
{
await WaitOrThrowAsync(() => Store.PendingDecision is not null, timeoutSeconds);
return Store.PendingDecision!;
}
/// <summary>
/// 提交对 <paramref name="answered"/> 的回执,然后等两种结果之一:
/// <list type="bullet">
/// <item>服务器下发<b>新的</b>决策 —— 返回它;</item>
/// <item>服务器明确放弃这条决策(对局结束 / 接管 / 断线,见 <c>gaming.resolved</c>)—— 返回 null。</item>
/// </list>
/// 按 requestId 串联可以保证既不会重复回答同一条请求,也不会把旧请求当成新请求。
/// </summary>
public async Task<SoloDecisionRequest?> SubmitAndAwaitNextAsync(
SoloDecisionRequest answered,
object payload,
double timeoutSeconds)
{
var droppedBefore = Store.DroppedDecisionCount;
SoloTrace.Step(
$"submit kind={answered.Kind} inFlight={Store.IsSubmittingDecision} "
+ $"pending={Store.PendingDecision?.Kind ?? "none"}");
await Store.SubmitDecisionAsync(payload);
SoloTrace.Step($"submitted kind={answered.Kind}, waiting next decision");
await WaitOrThrowAsync(
() => Store.DroppedDecisionCount > droppedBefore
|| (Store.PendingDecision is { } pending && pending.RequestId != answered.RequestId),
timeoutSeconds);
return Store.PendingDecision is { } next && next.RequestId != answered.RequestId
? next
: null;
}
/// <summary>轮询等待,超时抛异常(用于「必须发生」的条件)。</summary>
public async Task WaitOrThrowAsync(Func<bool> predicate, double timeoutSeconds)
{
if (!await WaitAsync(predicate, timeoutSeconds))
{
throw new TimeoutException($"Timed out after {timeoutSeconds:0.#} seconds.");
}
}
/// <summary>轮询等待,超时返回 false(用于「可能不会发生」的条件)。</summary>
public async Task<bool> WaitAsync(Func<bool> predicate, double timeoutSeconds)
{
var startedAt = Time.GetTicksMsec();
var timeoutMs = timeoutSeconds * 1_000.0;
while (!predicate())
{
if (Time.GetTicksMsec() - startedAt >= timeoutMs)
{
return false;
}
await host.ToSignal(host.GetTree().CreateTimer(0.05), SceneTreeTimer.SignalName.Timeout);
}
return true;
}
public long CurrentPlayerGridId()
{
var state = Store.Snapshot;
return state?.Characters.FirstOrDefault(character => character.Guid == state.PlayerGuid)?.GridId ?? -1;
}
/// <summary>
/// 从服务器给定的合法移动格里挑一个最靠近敌人的。
/// 合法性完全由 <c>gridIds</c> 决定,坐标只用于在多个合法格之间做偏好排序。
/// </summary>
public long? PickMoveGrid(SoloDecisionRequest decision, SoloGameState? state)
{
var allowed = decision.ReadPayload<TargetGridPayload>()?.GridIds ?? [];
if (allowed.Count == 0)
{
return null;
}
if (state?.Map is not { } map)
{
return allowed[0];
}
var grids = map.Grids.ToDictionary(grid => grid.Id);
var enemyGrids = state.Characters
.Where(character => character.Guid != state.PlayerGuid && !character.IsEliminated)
.Select(character => grids.GetValueOrDefault(character.GridId))
.OfType<SoloGridDto>()
.ToArray();
if (enemyGrids.Length == 0)
{
return allowed[0];
}
var playerGridId = CurrentPlayerGridId();
var candidates = allowed
.Where(gridId => gridId != playerGridId && grids.ContainsKey(gridId))
.ToArray();
return candidates.Length == 0
? allowed[0]
: candidates.OrderBy(gridId => enemyGrids.Min(enemy => Manhattan(grids[gridId], enemy))).First();
}
private static int Manhattan(SoloGridDto left, SoloGridDto right)
{
return Math.Abs(left.X - right.X) + Math.Abs(left.Y - right.Y);
}
}
+1
View File
@@ -0,0 +1 @@
uid://dd5did7pqg60u
+20
View File
@@ -0,0 +1,20 @@
namespace OSM.Client.Diagnostics;
/// <summary>
/// 冒烟测试的实时追踪。
/// <para>godot 的 <c>GD.Print</c> 走 C stdio,输出被重定向到文件/管道时是**块缓冲**的:
/// 进程被杀掉(工具超时 SIGTERM)时缓冲区来不及刷盘,日志里只剩引擎启动那几行,
/// 看起来像「什么都没跑」。这里用托管 stderr(默认 AutoFlush,且 C 标准要求 stderr 不带缓冲)
/// 打进度,保证卡死时也能看到最后一步。</para>
/// <para>最终结论仍走 <c>GD.Print</c>,保持 <c>SOLO_*_OK</c> / <c>*_FAILED</c> 可 grep。</para>
/// </summary>
public static class SoloTrace
{
public static void Step(string message)
{
Console.Error.WriteLine($"[trace {DateTime.Now:HH:mm:ss.fff}] {message}");
Console.Error.Flush();
}
public static void Step(string test, string message) => Step($"{test} {message}");
}
+1
View File
@@ -0,0 +1 @@
uid://dmwmdp1jd74ne
+353 -106
View File
@@ -1,33 +1,117 @@
using OSM.Client.Autoload; using OSM.Client.Autoload;
using OSM.Client.Contracts; using OSM.Client.Contracts;
using OSM.Client.Screens.Battle;
namespace OSM.Client.Diagnostics; namespace OSM.Client.Diagnostics;
/// <summary>
/// 阶段 C 真实 /ws/solo 竖切回归:移动、服务器拒绝恢复、普通攻击,并顺带观察 Continue。
/// <para><b>权威服务器原则</b>:客户端不推算射程、合法性或可选目标,只依据服务器下发的内容决策——</para>
/// <list type="bullet">
/// <item><c>ActionType.enemyOptions / enemys</c>:当前位置「攻击可达 ∪ 施法可达」的敌人
/// (见 GamingQueue 中按 canAttackGrids/canCastGrids 过滤后的 enemys)。列表为空时普通攻击
/// 必然被服务器取消,因此不提交。</item>
/// <item><c>ActionType.dp.quotas</c>:该行动类型本回合是否还可用(配额 + 决策点)。</item>
/// <item><c>TargetGrid.gridIds</c> / <c>Targets.targets</c>:唯一合法的格子与目标。</item>
/// </list>
/// <para>服务器对非法提交没有显式回执(<c>gaming.resolved</c> 尚未实现),被作废的行动只能在下一次
/// <c>gaming.request</c> 里看出来:又回到 <c>ActionType</c> 就说明上一个行动无效。所以这里用
/// 「同一回合内不重复提交刚被取消的行动」收敛,而不是让客户端猜距离——重复白提交会撞上服务端防打转
/// 护栏(同类决策连续 4 次 ⇒ 强制 AI 托管并结束回合),连 Continue 一起吃掉。</para>
/// <para>Continue 只记录、不作为通过条件:本局是否真的下发 Continue 取决于该回合是否正常结束且玩家
/// 未被托管;它的协议形状由 <see cref="PhaseCDecisionSmokeTest"/> 静态覆盖。</para>
/// </summary>
public partial class SoloVerticalSliceSmokeTest : Node public partial class SoloVerticalSliceSmokeTest : Node
{ {
// 移动上限给足:种子固定后抽到的两名角色可能开局离得很远,而回归要求真实走到普攻射程内。
// 收敛由「朝敌人移动 + 敌人也朝你来」保证;服务器拒绝移动时会置 _moveCancelled 提前收手。
private const int MaxSteps = 900;
private const int MaxMoves = 80;
private const int MaxSettlingSteps = 12;
/// <summary>核心路径达成后,再给多少步专门去验证「普攻可达门控」(需要敌人真的走进 ATR)。</summary>
private const int MaxGateSettlingSteps = 200;
/// <summary>等服务器下发下一条决策的超时(**秒**)。别写成毫秒 —— 写错就是「永远卡住」。</summary>
private const double DecisionTimeoutSeconds = 20.0;
private const double ShortTimeoutSeconds = 15.0;
private const double TotalTimeoutSeconds = 240.0;
/// <summary>看门狗上限:超过它无论如何都要退出,并留下原因(否则工具只能 SIGTERM,输出全丢)。</summary>
private const double WatchdogSeconds = 300.0;
private GameSession _session = null!; private GameSession _session = null!;
private BattleStore _store = null!; private BattleStore _store = null!;
private SoloTestDriver _driver = null!;
private int _moves; private int _moves;
private int _attackAttempts;
private int _attackCancelledCount;
private int _attackTargetsOffered;
private bool _preciseAttackSignal;
private bool _attackGateVerified;
private bool _attackSubmitted;
private bool _attackCancelled;
private bool _moveCancelled;
private bool _rejectionRecovered; private bool _rejectionRecovered;
private bool _continued; private bool _continueObserved;
private int _lastRound = -1;
private ulong _deadlineMs;
private ulong _nextBeatAtMs;
public override void _Ready() public override void _Ready()
{ {
_session = GetNode<GameSession>("/root/GameSession"); _session = GetNode<GameSession>("/root/GameSession");
_store = GetNode<BattleStore>("/root/BattleStore"); _store = GetNode<BattleStore>("/root/BattleStore");
_driver = new SoloTestDriver(_store, this);
_ = RunAsync(); _ = RunAsync();
_ = WatchdogAsync();
}
/// <summary>
/// 心跳:每 2 秒打一行当前状态。
/// 用途是把「主循环整个卡死」和「某个 await 永远不返回」区分开 ——
/// 心跳停 = 主循环卡死(SceneTreeTimer 也不会触发);心跳继续 = 主循环活着但 await 链断了。
/// </summary>
public override void _Process(double delta)
{
if (Time.GetTicksMsec() < _nextBeatAtMs)
{
return;
}
_nextBeatAtMs = Time.GetTicksMsec() + 2_000;
SoloTrace.Step(
$"beat session={_session.State} pending={_store.PendingDecision?.Kind ?? "none"} "
+ $"inFlight={_store.IsSubmittingDecision} logs={_store.LogLines.Count} "
+ $"units={GetTree().GetNodesInGroup("battle_unit").Count}");
}
/// <summary>
/// 看门狗:正常路径很快就能跑完,卡住时不能让进程一直挂着 ——
/// 挂死会让工具 SIGTERM,而 Godot 失缓冲的 stdout 到时全丢,只剩「什么都没跑」。
/// </summary>
private async Task WatchdogAsync()
{
await ToSignal(GetTree().CreateTimer(WatchdogSeconds), SceneTreeTimer.SignalName.Timeout);
var message = $"SOLO_VERTICAL_FAILED watchdog timed out after {WatchdogSeconds:0}s";
SoloTrace.Step(message);
GD.PushError(message);
GetTree().Quit(1);
} }
private async Task RunAsync() private async Task RunAsync()
{ {
try try
{ {
if (!await _session.ConnectAsync(new Uri("ws://localhost:11030/ws/solo"))) _deadlineMs = Time.GetTicksMsec() + (ulong)(TotalTimeoutSeconds * 1_000);
SoloTrace.Step("connecting");
if (!await _session.ConnectAsync(new Uri("ws://localhost:12030/ws/solo")))
{ {
throw new InvalidOperationException("WebSocket connection failed."); throw new InvalidOperationException("WebSocket connection failed.");
} }
await WaitUntilAsync(() => _session.State == SessionState.Connected, 5.0); await _driver.WaitOrThrowAsync(() => _session.State == SessionState.Connected, 5.0);
await _store.StartGameAsync(new SoloStartOptions await _store.StartGameAsync(new SoloStartOptions
{ {
CharacterCount = 2, CharacterCount = 2,
@@ -37,104 +121,113 @@ public partial class SoloVerticalSliceSmokeTest : Node
MaxRespawnTimes = 0, MaxRespawnTimes = 0,
MaxScoreToWin = 0, MaxScoreToWin = 0,
DecisionTimeoutSeconds = 30, DecisionTimeoutSeconds = 30,
// 协议层确认服务端接收 requireContinue;本局是否真的下发 Continue 由服务器流程决定。
RequireContinue = true, RequireContinue = true,
RoundDelayMs = 0, RoundDelayMs = 0,
DropItemsIntervalSeconds = 0, DropItemsIntervalSeconds = 0,
Seed = 20260919 Seed = 20260919
}); });
await WaitForDecisionAsync(SoloDecisionKinds.SelectCharacter, 10.0); SoloTrace.Step("connected, gaming.start sent, waiting SelectCharacter");
var character = _store.PendingDecision! var decision = await _driver.AwaitDecisionAsync(10.0);
.ReadPayload<SelectCharacterPayload>()? if (decision.Kind != SoloDecisionKinds.SelectCharacter)
{
throw new InvalidOperationException($"Expected SelectCharacter, got {decision.Kind}.");
}
var character = decision.ReadPayload<SelectCharacterPayload>()?
.Characters .Characters
.FirstOrDefault() .FirstOrDefault()
?? throw new InvalidOperationException("Server returned no selectable characters."); ?? throw new InvalidOperationException("Server returned no selectable characters.");
await _store.SubmitDecisionAsync(new { characterGuid = character.Guid }); decision = await _driver.SubmitAndAwaitNextAsync(
decision,
new { characterGuid = character.Guid },
ShortTimeoutSeconds);
await WaitUntilAsync( await _driver.WaitOrThrowAsync(
() => _store.Snapshot is { PlayerGuid.Length: > 0, Characters.Count: > 1, Map: not null }, () => _store.Snapshot is { PlayerGuid.Length: > 0, Characters.Count: > 1, Map: not null },
10.0); ShortTimeoutSeconds);
await WaitUntilAsync( await _driver.WaitOrThrowAsync(
() => GetTree().GetNodesInGroup("battle_unit").Count == _store.Snapshot!.Characters.Count, () => GetTree().GetNodesInGroup("battle_unit").Count == _store.Snapshot!.Characters.Count,
5.0); 5.0);
var attacked = false; SoloTrace.Step($"character selected, entering decision loop");
for (var step = 0; step < 24 && (!attacked || !_continued); step++)
{
await WaitUntilAsync(() => _store.PendingDecision is not null, 45.0);
var decision = _store.PendingDecision!;
switch (decision.Kind)
{
case SoloDecisionKinds.ActionType:
await _store.SubmitDecisionAsync(new
{
actionType = attacked
? "EndTurn"
: _moves == 0
? "Move"
: HasServerAttackTarget(decision) ? "NormalAttack" : "Move"
});
break;
case SoloDecisionKinds.TargetGrid: // 用可空局部变量承载「下一轮要处理的决策」:服务器放弃决策时它会变成 null,循环随之收尾。
if (!_rejectionRecovered) SoloDecisionRequest? current = decision;
var steps = 0;
var settling = 0;
var gateSettling = 0;
while (steps++ < MaxSteps)
{ {
var rejectedRequestId = decision.RequestId; if (Time.GetTicksMsec() >= _deadlineMs)
await _store.SubmitDecisionAsync(new { gridId = long.MaxValue });
await WaitUntilAsync(
() => _store.PendingDecision is not null
&& _store.PendingDecision.RequestId != rejectedRequestId,
10.0);
_rejectionRecovered = true;
}
else
{ {
await SubmitBestMoveAsync(decision); SoloTrace.Step($"SOLO_VERTICAL_DEADLINE reached after {steps} steps");
} GD.PushWarning($"SOLO_VERTICAL_DEADLINE reached after {steps} steps.");
break;
case SoloDecisionKinds.Targets:
{
var target = decision.ReadPayload<TargetsPayload>()?.Targets.FirstOrDefault()
?? throw new InvalidOperationException("Attack request contained no legal target.");
await _store.SubmitDecisionAsync(new { targetGuids = new[] { target.Guid } });
attacked = true;
break; break;
} }
case SoloDecisionKinds.Continue: if (!_store.IsStarted)
await _store.SubmitDecisionAsync(new { cancelled = false }); {
_continued = true; // 对局结束(gaming.over)或玩家被服务器托管:不会再有决策下发,收尾评估即可。
SoloTrace.Step($"server stopped asking for decisions after {steps} steps");
break; break;
}
default: if (IsCorePathSatisfied()
await _store.SubmitDecisionAsync(new { cancelled = true }); && (_continueObserved || ++settling > MaxSettlingSteps)
&& (_attackGateVerified || ++gateSettling > MaxGateSettlingSteps))
{
break; break;
} }
if (current is null)
{
// 服务器放弃/不再下发决策(对局结束、玩家被接管):本轮观测到此为止。
SoloTrace.Step($"server dropped the decision after {steps} steps");
break;
} }
ResetTurnGuards();
SoloTrace.Step(
$"step={steps} kind={current.Kind} moves={_moves} attacks={_attackAttempts} "
+ $"cancelled={_attackCancelledCount} submitted={_attackSubmitted} rejected={_rejectionRecovered}");
current = await TryHandleDecisionAsync(current);
}
SoloTrace.Step($"decision loop exited after {steps} steps");
if (_moves == 0) if (_moves == 0)
{ {
throw new InvalidOperationException("Vertical slice did not complete a movement."); throw new InvalidOperationException("Vertical slice did not complete a movement.");
} }
if (!attacked) if (!_attackSubmitted)
{ {
throw new InvalidOperationException("Vertical slice did not reach an attack target request."); throw new InvalidOperationException(
"Vertical slice did not submit a normal attack on a server-listed target. "
+ $"moves={_moves} attackAttempts={_attackAttempts} "
+ $"attackReachableRounds={_attackTargetsOffered} attackGateVerified={_attackGateVerified} "
+ $"preciseSignal={_preciseAttackSignal} enemyNeverInAtr={_attackTargetsOffered == 0}");
} }
if (!_rejectionRecovered) if (!_rejectionRecovered)
{ {
throw new InvalidOperationException("Vertical slice did not recover from a rejected grid."); throw new InvalidOperationException("Vertical slice did not recover from a rejected grid.");
} }
if (!_continued) if (_preciseAttackSignal && _attackCancelledCount > 0)
{ {
throw new InvalidOperationException("Vertical slice did not complete a Continue decision."); // 服务器下发了严格口径的 attackTargets,却仍有普攻被作废 ⇒ 该信号不可信
throw new InvalidOperationException(
$"Server advertised precise attackTargets but {_attackCancelledCount} normal attack(s) were cancelled.");
} }
GD.Print( var okLine = $"SOLO_VERTICAL_OK game={_store.Snapshot!.GameId} moves={_moves} "
$"SOLO_VERTICAL_OK game={_store.Snapshot!.GameId} moves={_moves} " + "attackTargetSubmitted=true rejectionRecovered=true "
+ $"attackTargetSubmitted=true rejectionRecovered=true " + $"attackAttempts={_attackAttempts} attackCancelled={_attackCancelledCount} "
+ $"continueSubmitted=true " + $"attackReachableRounds={_attackTargetsOffered} attackGateVerified={_attackGateVerified} "
+ $"units={GetTree().GetNodesInGroup("battle_unit").Count}"); + $"preciseAttackSignal={(_preciseAttackSignal ? "true" : "false")} "
+ $"continueObserved={(_continueObserved ? "true" : "false")} "
+ $"units={GetTree().GetNodesInGroup("battle_unit").Count}";
SoloTrace.Step(okLine);
GD.Print(okLine);
await _session.EndSoloGameAsync(); await _session.EndSoloGameAsync();
await _session.DisconnectAsync(); await _session.DisconnectAsync();
@@ -142,73 +235,227 @@ public partial class SoloVerticalSliceSmokeTest : Node
} }
catch (Exception exception) catch (Exception exception)
{ {
// 先写 stderr(不带缓冲),保证即使后面清理步骤卡住、进程被强杀,失败原因也留得下来。
SoloTrace.Step($"SOLO_VERTICAL_FAILED {exception.Message}");
GD.PushError($"SOLO_VERTICAL_FAILED {exception.Message}"); GD.PushError($"SOLO_VERTICAL_FAILED {exception.Message}");
await _session.DisconnectAsync(); await _session.DisconnectAsync();
GetTree().Quit(1); GetTree().Quit(1);
} }
} }
private static bool HasServerAttackTarget(SoloDecisionRequest decision) /// <summary>
/// 处理一条决策;服务器在等待期间不再下发新决策时返回 null(对局结束 / 托管),
/// 让循环优雅收尾而不是干等到超时 —— 这类「服务端主动静默」不是客户端故障。
/// </summary>
private async Task<SoloDecisionRequest?> TryHandleDecisionAsync(SoloDecisionRequest decision)
{ {
var payload = decision.ReadPayload<ActionTypePayload>(); try
return payload is not null {
&& (payload.EnemyOptions.Count > 0 || payload.Enemys.Count > 0); return await HandleDecisionAsync(decision);
}
catch (TimeoutException exception)
{
SoloTrace.Step($"no further decision from server: {exception.Message}");
return null;
}
} }
private async Task SubmitBestMoveAsync(SoloDecisionRequest decision) /// <summary>核心路径:真实移动 + 真实普攻(按服务器给的 Targets)+ 拒绝恢复。</summary>
{ private bool IsCorePathSatisfied() => _moves > 0 && _attackSubmitted && _rejectionRecovered;
var state = _store.Snapshot ?? throw new InvalidOperationException("Missing state before movement.");
var map = state.Map ?? throw new InvalidOperationException("Missing map before movement.");
var player = state.Characters.First(character => character.Guid == state.PlayerGuid);
var grids = map.Grids.ToDictionary(grid => grid.Id);
var enemies = state.Characters
.Where(character => !character.IsPlayer && !character.IsEliminated)
.Where(character => grids.ContainsKey(character.GridId))
.Select(character => grids[character.GridId])
.ToArray();
var allowed = decision.ReadPayload<TargetGridPayload>()?.GridIds ?? [];
var destination = allowed
.Where(gridId => gridId != player.GridId && grids.ContainsKey(gridId))
.Select(gridId => grids[gridId])
.OrderBy(grid => enemies.Length == 0 ? 0 : enemies.Min(enemy => Manhattan(grid, enemy)))
.FirstOrDefault();
if (destination is null) /// <summary>
/// 新回合清除「上一回合学到的不可行动作」:服务器每回合重新给一次机会,
/// 上一回合的攻击/移动被取消不代表这一回合也不行。
/// </summary>
private void ResetTurnGuards()
{
var round = _store.Snapshot?.Round ?? -1;
if (round == _lastRound)
{ {
await _store.SubmitDecisionAsync(new { cancelled = true });
return; return;
} }
var originGridId = player.GridId; _lastRound = round;
await _store.SubmitDecisionAsync(new { gridId = destination.Id }); _attackCancelled = false;
await WaitUntilAsync( _moveCancelled = false;
() => _store.Snapshot?.Characters }
.FirstOrDefault(character => character.Guid == state.PlayerGuid)?.GridId != originGridId,
10.0); private async Task<SoloDecisionRequest?> HandleDecisionAsync(SoloDecisionRequest decision)
{
switch (decision.Kind)
{
case SoloDecisionKinds.ActionType:
return await HandleActionTypeAsync(decision);
case SoloDecisionKinds.TargetGrid:
return await HandleTargetGridAsync(decision);
case SoloDecisionKinds.Targets:
{
var target = decision.ReadPayload<TargetsPayload>()?.Targets.FirstOrDefault()
?? throw new InvalidOperationException("Attack request contained no legal target.");
_attackSubmitted = true;
return await _driver.SubmitAndAwaitNextAsync(
decision,
new { targetGuids = new[] { target.Guid } },
DecisionTimeoutSeconds);
}
case SoloDecisionKinds.Continue:
_continueObserved = true;
return await _driver.SubmitAndAwaitNextAsync(
decision,
new { cancelled = false },
DecisionTimeoutSeconds);
case SoloDecisionKinds.Inquiry:
return await _driver.SubmitAndAwaitNextAsync(
decision,
BuildInquiryReply(decision.ReadPayload<InquiryPayload>()),
DecisionTimeoutSeconds);
default:
// Skill / Item / TargetGrids:本竖切不主动使用,按取消处理,让服务器回到行动菜单。
return await _driver.SubmitAndAwaitNextAsync(decision, new { cancelled = true }, DecisionTimeoutSeconds);
}
}
private async Task<SoloDecisionRequest?> HandleActionTypeAsync(SoloDecisionRequest decision)
{
var payload = decision.ReadPayload<ActionTypePayload>();
// 与 BattleScreen 同一套判定:优先服务端的严格口径 attackTargets(ATR 内可达)。
var attackReachable = DecisionUiRules.IsNormalAttackReachable(payload) == true;
_preciseAttackSignal |= payload?.AttackTargets is not null;
if (attackReachable)
{
_attackTargetsOffered++;
}
var attackQuotaAvailable = DecisionUiRules.IsActionAvailable(payload?.Dp, "NormalAttack");
var canMove = !_moveCancelled && _moves < MaxMoves;
string actionType;
if (canMove && _moves == 0)
{
// 回归要求至少完成一次真实移动,这一步优先。
actionType = "Move";
}
else if (!_attackCancelled && attackReachable && attackQuotaAvailable)
{
// 服务器说「射程内有人」且配额允许 → 打。
// 这既是正常的对局行为,也是「精确口径 → 提交普攻 → 不被作废」这条门控的真实验证。
actionType = "NormalAttack";
}
else if (canMove)
{
// 打不着就继续朝敌人靠近,让下一回合有机会进入 ATR(否则门控永远验证不到)。
actionType = "Move";
}
else
{
actionType = "EndTurn";
}
if (actionType == "NormalAttack")
{
_attackAttempts++;
}
SoloTrace.Step(
$"payload kind=ActionType actorGrid={payload?.ActorGridId} atr={payload?.Atr} "
+ $"enemys={payload?.Enemys.Count} enemyOptions={payload?.EnemyOptions.Count} "
+ $"attackTargets={payload?.AttackTargets?.Count.ToString() ?? "null"} "
+ $"canNormalAttack={payload?.CanNormalAttack?.ToString() ?? "null"} "
+ $"reachable={attackReachable} choose={actionType}");
SoloTrace.Step($"submit actionType={actionType}");
var next = await _driver.SubmitAndAwaitNextAsync(decision, new { actionType }, DecisionTimeoutSeconds);
if (next is null)
{
SoloTrace.Step($"actionType={actionType} -> server dropped the decision");
return null;
}
SoloTrace.Step($"actionType={actionType} -> next kind={next.Kind}");
// 没有拒绝回执:行动被作废的唯一信号是「下一次又要 ActionType」。学到即收敛。
if (attackReachable && actionType == "NormalAttack" && next.Kind == SoloDecisionKinds.Targets)
{
// 服务端说可达 → 我们据此提交 → 真的进了选目标阶段:门控成立
_attackGateVerified = true;
}
if (next.Kind == SoloDecisionKinds.ActionType)
{
if (actionType == "NormalAttack")
{
_attackCancelled = true;
_attackCancelledCount++;
}
else if (actionType == "Move")
{
_moveCancelled = true;
}
}
return next;
}
private async Task<SoloDecisionRequest?> HandleTargetGridAsync(SoloDecisionRequest decision)
{
if (!_rejectionRecovered)
{
// 阶段 B 的拒绝恢复:故意提交服务器不可能认下的格子,确认之后还能回到可提交状态。
_rejectionRecovered = true;
return await _driver.SubmitAndAwaitNextAsync(decision, new { gridId = long.MaxValue }, ShortTimeoutSeconds);
}
var destination = _driver.PickMoveGrid(decision, _store.Snapshot);
if (destination is null)
{
_moveCancelled = true;
return await _driver.SubmitAndAwaitNextAsync(decision, new { cancelled = true }, DecisionTimeoutSeconds);
}
var originGridId = _driver.CurrentPlayerGridId();
var next = await _driver.SubmitAndAwaitNextAsync(
decision,
new { gridId = destination.Value },
DecisionTimeoutSeconds);
if (next is null)
{
return null;
}
// 下一次决策是服务器在应用移动后(先 FlushState 再下发)发出的,快照顺序在协议里保证,
// 因此这里读到的位置就是权威结果。
if (_driver.CurrentPlayerGridId() == originGridId)
{
_moveCancelled = true;
}
else
{
_moves++; _moves++;
} }
private async Task WaitForDecisionAsync(string kind, double timeoutSeconds) return next;
{
await WaitUntilAsync(() => _store.PendingDecision?.Kind == kind, timeoutSeconds);
} }
private async Task WaitUntilAsync(Func<bool> predicate, double timeoutSeconds) private static object BuildInquiryReply(InquiryPayload? payload)
{ {
var startedAt = Time.GetTicksMsec(); if (payload is null || payload.CanCancel)
var timeoutMs = timeoutSeconds * 1_000.0;
while (!predicate())
{ {
if (Time.GetTicksMsec() - startedAt >= timeoutMs) return new { cancel = true };
{
throw new TimeoutException($"Timed out after {timeoutSeconds:0.#} seconds.");
}
await ToSignal(GetTree().CreateTimer(0.05), SceneTreeTimer.SignalName.Timeout);
}
} }
private static int Manhattan(SoloGridDto left, SoloGridDto right) if (!string.IsNullOrEmpty(payload.DefaultChoice))
{ {
return Math.Abs(left.X - right.X) + Math.Abs(left.Y - right.Y); return new { choices = new[] { payload.DefaultChoice } };
}
if (payload.Choices.Count > 0)
{
return new { choices = new[] { payload.Choices[0].Key } };
}
return new { number = payload.DefaultNumber };
} }
} }
@@ -0,0 +1 @@
uid://bhbs0kwpgddu
+1
View File
@@ -0,0 +1 @@
uid://cmv5c85fdafxv
+7
View File
@@ -11,4 +11,11 @@ public interface IGameTransport : IAsyncDisposable
Task ConnectAsync(Uri endpoint, CancellationToken cancellationToken = default); Task ConnectAsync(Uri endpoint, CancellationToken cancellationToken = default);
Task SendAsync(string message, CancellationToken cancellationToken = default); Task SendAsync(string message, CancellationToken cancellationToken = default);
Task DisconnectAsync(CancellationToken cancellationToken = default); Task DisconnectAsync(CancellationToken cancellationToken = default);
/// <summary>
/// 强制中断当前连接:不发送关闭握手,让接收循环以异常收尾并触发 <see cref="Closed"/>。
/// 用途有二:清理已经半死、Send/Receive 永久挂起的 socket;
/// 以及模拟「网络被拔掉」来验证断线恢复(<c>DisconnectAsync</c> 是主动关闭,不会触发自动重连)。
/// </summary>
void Abort();
} }
+12
View File
@@ -29,6 +29,18 @@ public sealed class MockTransport : IGameTransport
return Task.CompletedTask; return Task.CompletedTask;
} }
public void Abort()
{
// 模拟拔网线:置为未连接并抛出 Closed,让上层走自动重连而不是主动断开分支。
var wasConnected = IsConnected;
IsConnected = false;
if (wasConnected)
{
Faulted?.Invoke(new IOException("Mock transport aborted."));
Closed?.Invoke();
}
}
public Task DisconnectAsync(CancellationToken cancellationToken = default) public Task DisconnectAsync(CancellationToken cancellationToken = default)
{ {
var wasConnected = IsConnected; var wasConnected = IsConnected;
+39 -5
View File
@@ -6,6 +6,13 @@ namespace OSM.Client.Networking;
public sealed class WebSocketTransport : IGameTransport public sealed class WebSocketTransport : IGameTransport
{ {
private const int MaxMessageBytes = 4 * 1024 * 1024; private const int MaxMessageBytes = 4 * 1024 * 1024;
/// <summary>单次发送的上限。半死连接(对端不再读取)会让 SendAsync 永久不返回。</summary>
private const int SendTimeoutMs = 10_000;
/// <summary>关闭握手的上限。对端已经消失时 CloseAsync 可能一直等不到回应。</summary>
private const int CloseTimeoutMs = 5_000;
private readonly ClientWebSocket _socket = new(); private readonly ClientWebSocket _socket = new();
private readonly CancellationTokenSource _lifetime = new(); private readonly CancellationTokenSource _lifetime = new();
private Task? _receiveTask; private Task? _receiveTask;
@@ -30,7 +37,27 @@ public sealed class WebSocketTransport : IGameTransport
} }
var bytes = Encoding.UTF8.GetBytes(message); var bytes = Encoding.UTF8.GetBytes(message);
await _socket.SendAsync(bytes, WebSocketMessageType.Text, true, cancellationToken); using var sendTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
sendTimeout.CancelAfter(SendTimeoutMs);
try
{
await _socket.SendAsync(bytes, WebSocketMessageType.Text, true, sendTimeout.Token);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// 连接已经半死:发送迟迟不返回。放弃这条 socket 并交给上层自动重连,
// 而不是把调用方(界面 / 测试)永久挂死在这里。
Abort();
throw new TimeoutException(
$"WebSocket send timed out after {SendTimeoutMs} ms; connection aborted.");
}
}
public void Abort()
{
// 不取消 _lifetime:让接收循环以 WebSocketException 收尾,从而走 Faulted/Closed,
// 上层据此进入自动重连。
_socket.Abort();
} }
public async Task DisconnectAsync(CancellationToken cancellationToken = default) public async Task DisconnectAsync(CancellationToken cancellationToken = default)
@@ -41,14 +68,21 @@ public sealed class WebSocketTransport : IGameTransport
{ {
try try
{ {
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client exit", cancellationToken); using var closeTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
closeTimeout.CancelAfter(CloseTimeoutMs);
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client exit", closeTimeout.Token);
} }
catch (WebSocketException) catch (Exception exception) when (exception is WebSocketException or OperationCanceledException)
{ {
// The Solo endpoint may close immediately after gaming.end. Teardown is // Solo 端点在 gaming.end 之后可能立即断开,此时已经没有关闭握手可做;
// already complete in that case, even if no WebSocket close handshake remains. // 或者对端已经消失、关闭握手永远等不到回应。两种情况都不影响后续清理。
Abort();
} }
} }
else
{
Abort();
}
if (_receiveTask is not null) if (_receiveTask is not null)
{ {
+1 -1
View File
@@ -26,7 +26,7 @@ src/
使用 Godot 4.7 .NET 打开仓库根目录的 `project.godot`。当前客户端会进入灰盒战斗场景,并默认连接: 使用 Godot 4.7 .NET 打开仓库根目录的 `project.godot`。当前客户端会进入灰盒战斗场景,并默认连接:
```text ```text
ws://localhost:11030/ws/solo ws://localhost:12030/ws/solo
``` ```
先启动 `FunGame.Testing-v3/WebAPI`,再在右上角点击“连接”和“开始新局”。客户端目前支持: 先启动 `FunGame.Testing-v3/WebAPI`,再在右上角点击“连接”和“开始新局”。客户端目前支持:
+156
View File
@@ -0,0 +1,156 @@
[gd_resource type="Theme" load_steps=9 format=3]
[sub_resource type="StyleBoxFlat" id="panel"]
bg_color = Color(0.964706, 0.976471, 0.996078, 0.96)
border_width_left = 1
border_width_top = 1
border_width_right = 1
border_width_bottom = 1
border_color = Color(0.705882, 0.796078, 0.886275, 1)
corner_radius_top_left = 14
corner_radius_top_right = 14
corner_radius_bottom_right = 14
corner_radius_bottom_left = 14
shadow_color = Color(0.027451, 0.070588, 0.145098, 0.32)
shadow_size = 8
content_margin_left = 14.0
content_margin_top = 12.0
content_margin_right = 14.0
content_margin_bottom = 12.0
[sub_resource type="StyleBoxFlat" id="button_normal"]
bg_color = Color(0.878431, 0.929412, 0.980392, 1)
border_width_left = 1
border_width_top = 1
border_width_right = 1
border_width_bottom = 1
border_color = Color(0.666667, 0.776471, 0.87451, 1)
corner_radius_top_left = 9
corner_radius_top_right = 9
corner_radius_bottom_right = 9
corner_radius_bottom_left = 9
content_margin_left = 10.0
content_margin_top = 7.0
content_margin_right = 10.0
content_margin_bottom = 7.0
[sub_resource type="StyleBoxFlat" id="button_hover"]
bg_color = Color(0.952941, 0.988235, 1, 1)
border_width_left = 2
border_width_top = 2
border_width_right = 2
border_width_bottom = 2
border_color = Color(0.309804, 0.694118, 0.839216, 1)
corner_radius_top_left = 9
corner_radius_top_right = 9
corner_radius_bottom_right = 9
corner_radius_bottom_left = 9
content_margin_left = 10.0
content_margin_top = 7.0
content_margin_right = 10.0
content_margin_bottom = 7.0
[sub_resource type="StyleBoxFlat" id="button_pressed"]
bg_color = Color(0.74902, 0.882353, 0.952941, 1)
border_width_left = 2
border_width_top = 2
border_width_right = 2
border_width_bottom = 2
border_color = Color(0.243137, 0.572549, 0.737255, 1)
corner_radius_top_left = 9
corner_radius_top_right = 9
corner_radius_bottom_right = 9
corner_radius_bottom_left = 9
content_margin_left = 10.0
content_margin_top = 7.0
content_margin_right = 10.0
content_margin_bottom = 7.0
[sub_resource type="StyleBoxFlat" id="button_disabled"]
bg_color = Color(0.894118, 0.917647, 0.941176, 0.9)
border_width_left = 1
border_width_top = 1
border_width_right = 1
border_width_bottom = 1
border_color = Color(0.788235, 0.831373, 0.87451, 1)
corner_radius_top_left = 9
corner_radius_top_right = 9
corner_radius_bottom_right = 9
corner_radius_bottom_left = 9
content_margin_left = 10.0
content_margin_top = 7.0
content_margin_right = 10.0
content_margin_bottom = 7.0
[sub_resource type="StyleBoxFlat" id="focus"]
draw_center = false
border_width_left = 2
border_width_top = 2
border_width_right = 2
border_width_bottom = 2
border_color = Color(0.768627, 0.615686, 0.337255, 1)
corner_radius_top_left = 10
corner_radius_top_right = 10
corner_radius_bottom_right = 10
corner_radius_bottom_left = 10
[sub_resource type="StyleBoxFlat" id="input"]
bg_color = Color(1, 1, 1, 0.96)
border_width_left = 1
border_width_top = 1
border_width_right = 1
border_width_bottom = 1
border_color = Color(0.690196, 0.784314, 0.878431, 1)
corner_radius_top_left = 8
corner_radius_top_right = 8
corner_radius_bottom_right = 8
corner_radius_bottom_left = 8
content_margin_left = 10.0
content_margin_top = 7.0
content_margin_right = 10.0
content_margin_bottom = 7.0
[sub_resource type="StyleBoxFlat" id="list_selected"]
bg_color = Color(0.807843, 0.921569, 0.972549, 1)
border_width_left = 2
border_width_top = 1
border_width_right = 1
border_width_bottom = 1
border_color = Color(0.352941, 0.686275, 0.835294, 1)
corner_radius_top_left = 5
corner_radius_top_right = 5
corner_radius_bottom_right = 5
corner_radius_bottom_left = 5
[resource]
default_font_size = 18
Button/colors/font_color = Color(0.12549, 0.211765, 0.321569, 1)
Button/colors/font_hover_color = Color(0.062745, 0.286275, 0.423529, 1)
Button/colors/font_pressed_color = Color(0.039216, 0.231373, 0.368627, 1)
Button/colors/font_disabled_color = Color(0.443137, 0.513725, 0.596078, 1)
Button/styles/normal = SubResource("button_normal")
Button/styles/hover = SubResource("button_hover")
Button/styles/pressed = SubResource("button_pressed")
Button/styles/disabled = SubResource("button_disabled")
Button/styles/focus = SubResource("focus")
OptionButton/colors/font_color = Color(0.12549, 0.211765, 0.321569, 1)
OptionButton/colors/font_hover_color = Color(0.062745, 0.286275, 0.423529, 1)
OptionButton/styles/normal = SubResource("button_normal")
OptionButton/styles/hover = SubResource("button_hover")
OptionButton/styles/pressed = SubResource("button_pressed")
OptionButton/styles/disabled = SubResource("button_disabled")
OptionButton/styles/focus = SubResource("focus")
PanelContainer/styles/panel = SubResource("panel")
Label/colors/font_color = Color(0.129412, 0.211765, 0.317647, 1)
LineEdit/colors/font_color = Color(0.129412, 0.211765, 0.317647, 1)
LineEdit/colors/font_placeholder_color = Color(0.443137, 0.513725, 0.596078, 1)
LineEdit/styles/normal = SubResource("input")
LineEdit/styles/focus = SubResource("focus")
SpinBox/colors/font_color = Color(0.129412, 0.211765, 0.317647, 1)
ItemList/colors/font_color = Color(0.129412, 0.211765, 0.317647, 1)
ItemList/colors/font_selected_color = Color(0.054902, 0.211765, 0.337255, 1)
ItemList/styles/panel = SubResource("input")
ItemList/styles/selected = SubResource("list_selected")
ItemList/styles/selected_focus = SubResource("list_selected")
ItemList/styles/focus = SubResource("focus")
RichTextLabel/colors/default_color = Color(0.129412, 0.211765, 0.317647, 1)
+333
View File
@@ -0,0 +1,333 @@
using OSM.Client.Units;
namespace OSM.Client.Screens.Battle;
/// <summary>
/// 表现队列:把 <see cref="BattleSnapshotDiff"/> 产出的任务按顺序播成补间。
/// <para><b>不阻塞快照接收</b>:这里只做「入队 + 每帧推进」,从不 await 网络、从不反向影响 BattleStore。
/// 快照来了就入队,播不完就对丢弃并请求对齐最新权威快照(<see cref="SkipCalledEventHandler"/>),
/// 所以画面可以落后,但永远不会让权威状态等待表现。</para>
/// <para><b>同棋子同类任务合并</b>:一个棋子同时只会有一条待播的 Move / Hit / Heal
/// (新结果直接改写旧任务的目标或叠加伤害),否则快速连招会在队列里堆出一串过期补间,
/// 画面追不上权威状态。</para>
/// <para>重连时同样走 <see cref="SkipAll"/>:断线期间的补间没有播放价值,直接对齐服务器补发的快照。</para>
/// </summary>
public sealed partial class BattleAnimator : Node
{
/// <summary>队列上限:超过即认为表现已经追不上权威状态,丢弃全部待播任务并对齐。</summary>
private const int MaxQueuedTasks = 64;
[Signal]
public delegate void QueueChangedEventHandler();
/// <summary>请求外部把画面重新对齐到最新权威快照(队列被丢弃/跳过时发出)。</summary>
[Signal]
public delegate void SkipCalledEventHandler(string reason);
private readonly LinkedList<AnimationTask> _pending = new();
private AnimationTask? _active;
private Func<string, UnitView?>? _resolveUnit;
private int _droppedTasks;
private int _mergedTasks;
public bool IsBusy => _active is not null || _pending.Count > 0;
public int PendingCount => _pending.Count + (_active is null ? 0 : 1);
public int DroppedTasks => _droppedTasks;
public int MergedTasks => _mergedTasks;
/// <summary>播放速度倍率(1.0 为基准)。</summary>
public double Speed { get; set; } = 1.0;
public void Initialize(Func<string, UnitView?> resolveUnit)
{
_resolveUnit = resolveUnit;
}
/// <summary>
/// 入队一批表现任务。<paramref name="authoritativePosition"/> 取「最新权威快照里该单位应该在的位置」,
/// 起点则用棋子当前实际所在的位置 —— 这样即使中途丢过几帧快照,动画也从画面看到的地方起步,不会瞬移。
/// </summary>
public void Submit(
IReadOnlyList<BattleAnimationRequest> requests,
Func<string, Vector2> authoritativePosition)
{
if (requests.Count == 0)
{
return;
}
var changed = false;
foreach (var request in requests)
{
var unit = _resolveUnit?.Invoke(request.Guid);
if (unit is null)
{
continue;
}
var merged = TryMerge(request, unit, authoritativePosition);
if (merged)
{
_mergedTasks++;
changed = true;
continue;
}
_pending.AddLast(new AnimationTask
{
Guid = request.Guid,
Kind = request.Kind,
Magnitude = request.Magnitude,
Duration = DurationOf(request.Kind),
From = unit.Position,
To = authoritativePosition(request.Guid)
});
changed = true;
}
if (!changed)
{
return;
}
if (_pending.Count > MaxQueuedTasks)
{
// 表现追不上权威状态:全部丢弃并请求对齐,而不是慢慢追一个已经过期很久的画面。
SkipAll("表现积压");
return;
}
EmitSignal(SignalName.QueueChanged);
}
public override void _Process(double delta)
{
if (_active is null && _pending.Count > 0)
{
_active = _pending.First!.Value;
_pending.RemoveFirst();
BeginTask(_active);
EmitSignal(SignalName.QueueChanged);
}
var task = _active;
if (task is null)
{
return;
}
var unit = _resolveUnit?.Invoke(task.Guid);
if (unit is null)
{
// 棋子已经消失(快照里没了),丢弃这条任务。
_active = null;
EmitSignal(SignalName.QueueChanged);
return;
}
task.Elapsed += delta * Math.Clamp(Speed, 0.25, 4.0);
var progress = (float)Math.Clamp(task.Elapsed / task.Duration, 0.0, 1.0);
ApplyFrame(task, unit, progress);
if (progress >= 1.0f)
{
CompleteTask(task, unit);
_active = null;
EmitSignal(SignalName.QueueChanged);
}
}
/// <summary>跳过所有待播表现(手工点击 / 积压 / 重连),请求外部重新对齐权威快照。</summary>
public void SkipAll(string reason)
{
var discarded = PendingCount;
_pending.Clear();
_active = null;
_droppedTasks += discarded;
EmitSignal(SignalName.QueueChanged);
EmitSignal(SignalName.SkipCalled, reason);
}
/// <summary>当前正在播放的任务(供自检/日志),空闲时为 null。</summary>
public BattleAnimationKind? ActiveKind => _active?.Kind;
/// <summary>
/// 该棋子的显示位置此刻是否由表现层接管(有待播或正在播的 Move)。
/// BattleScreen 据此决定要不要把权威坐标直接写进 <c>Position</c>。
/// </summary>
public bool TakesOverPosition(string guid)
{
if (_active is { Kind: BattleAnimationKind.Move } active
&& string.Equals(active.Guid, guid, StringComparison.Ordinal))
{
return true;
}
return _pending.Any(task =>
task.Kind == BattleAnimationKind.Move
&& string.Equals(task.Guid, guid, StringComparison.Ordinal));
}
/// <summary>该棋子的血条数值此刻是否由表现层接管(有待播或正在播的 Hit / Heal 补间)。</summary>
public bool TakesOverHp(string guid)
{
if (_active is { } active
&& active.Kind is BattleAnimationKind.Hit or BattleAnimationKind.Heal
&& string.Equals(active.Guid, guid, StringComparison.Ordinal))
{
return true;
}
return _pending.Any(task =>
task.Kind is BattleAnimationKind.Hit or BattleAnimationKind.Heal
&& string.Equals(task.Guid, guid, StringComparison.Ordinal));
}
private bool TryMerge(
BattleAnimationRequest request,
UnitView unit,
Func<string, Vector2> authoritativePosition)
{
foreach (var task in _pending)
{
if (!string.Equals(task.Guid, request.Guid, StringComparison.Ordinal)
|| task.Kind != request.Kind)
{
continue;
}
MergeTask(task, request, unit, authoritativePosition);
return true;
}
// 正在播放的那条也可以被改写:移动中的单位又接到新目标时直接换终点,不会停下来再起步。
if (_active is not null
&& string.Equals(_active.Guid, request.Guid, StringComparison.Ordinal)
&& _active.Kind == request.Kind)
{
MergeTask(_active, request, unit, authoritativePosition);
return true;
}
return false;
}
private void MergeTask(
AnimationTask task,
BattleAnimationRequest request,
UnitView unit,
Func<string, Vector2> authoritativePosition)
{
switch (request.Kind)
{
case BattleAnimationKind.Move:
// 又移动了:改写终点,起点保持「画面当前位置」,仍然是一条连续的滑行。
task.To = authoritativePosition(request.Guid);
break;
case BattleAnimationKind.Hit:
case BattleAnimationKind.Heal:
// 连击 / 连疗:叠加量值;正在播的那条要按最新权威血量重新挂一次补间,
// 否则它会停在上一帧的目标值上。
task.Magnitude += request.Magnitude;
if (ReferenceEquals(task, _active))
{
ReArmHpTransition(task, unit);
}
break;
default:
// Eliminate / Respawn 重复出现没有意义(同一个状态转折)。
break;
}
}
private static void ReArmHpTransition(AnimationTask task, UnitView unit)
{
var remaining = Math.Max(0.05, task.Duration - task.Elapsed);
unit.PlayHpTransition(FromHp(task, unit), unit.AuthoritativeHp, remaining);
}
private static double FromHp(AnimationTask task, UnitView unit)
{
return task.Kind == BattleAnimationKind.Hit
? unit.AuthoritativeHp + task.Magnitude
: Math.Max(0.0, unit.AuthoritativeHp - task.Magnitude);
}
private void BeginTask(AnimationTask task)
{
var unit = _resolveUnit?.Invoke(task.Guid);
if (unit is null)
{
return;
}
switch (task.Kind)
{
case BattleAnimationKind.Move:
unit.Position = task.From;
break;
case BattleAnimationKind.Hit:
// 血条从「掉血前」补间到权威值,让伤害有因果感;权威值本身早已由快照决定。
unit.PlayHpTransition(FromHp(task, unit), unit.AuthoritativeHp, task.Duration);
unit.FlashDamage();
break;
case BattleAnimationKind.Heal:
unit.PlayHpTransition(FromHp(task, unit), unit.AuthoritativeHp, task.Duration);
unit.FlashHeal();
break;
case BattleAnimationKind.Eliminate:
unit.FlashDamage();
break;
case BattleAnimationKind.Respawn:
unit.FlashHeal();
break;
}
}
private static void ApplyFrame(AnimationTask task, UnitView unit, float progress)
{
if (task.Kind != BattleAnimationKind.Move)
{
return;
}
// 缓出:起步快、收尾稳,战斗单位看起来不带橡皮筋感。
var eased = 1.0f - Mathf.Pow(1.0f - progress, 3.0f);
unit.Position = task.From.Lerp(task.To, eased);
}
private static void CompleteTask(AnimationTask task, UnitView unit)
{
if (task.Kind == BattleAnimationKind.Move)
{
unit.Position = task.To;
}
}
private static double DurationOf(BattleAnimationKind kind) => kind switch
{
BattleAnimationKind.Move => 0.26,
BattleAnimationKind.Hit => 0.36,
BattleAnimationKind.Heal => 0.36,
BattleAnimationKind.Eliminate => 0.5,
BattleAnimationKind.Respawn => 0.32,
_ => 0.3
};
private sealed class AnimationTask
{
public required string Guid { get; init; }
public required BattleAnimationKind Kind { get; init; }
public required double Duration { get; init; }
public required Vector2 From { get; init; }
public double Magnitude { get; set; }
public Vector2 To { get; set; }
public double Elapsed { get; set; }
}
}
+1
View File
@@ -0,0 +1 @@
uid://cboywmujpj5f1
+291
View File
@@ -0,0 +1,291 @@
using OSM.Client.Autoload;
using OSM.Client.Contracts;
namespace OSM.Client.Screens.Battle;
/// <summary>战场常驻信息、可收起的连接区,以及目标列表。</summary>
public partial class BattleScreen
{
private AssetCatalog _assetCatalog = null!;
private Control _connectionPanel = null!;
private Button _connectionToggle = null!;
private Control _actionDock = null!;
private Control _actionGrid = null!;
private Control _targetPicker = null!;
private Label _targetTitle = null!;
private Label _targetHelp = null!;
private VBoxContainer _targetChoices = null!;
private Control _utilityPanel = null!;
private Control _contextBar = null!;
private Control _characterPanel = null!;
private Control _queuePanel = null!;
private HBoxContainer _queueCards = null!;
private Label _rewardLabel = null!;
private bool _connectionExpanded;
private string? _queueSignature;
private readonly Dictionary<string, Button> _targetChoiceButtons = new(StringComparer.Ordinal);
private readonly Dictionary<long, Texture2D?> _portraitCache = [];
private void InitializeBattleHud()
{
const string layout = "HudLayer/SafeArea/Layout/";
_assetCatalog = GetNode<AssetCatalog>("/root/AssetCatalog");
_connectionPanel = GetNode<Control>(layout + "ConnectionPanel");
_connectionToggle = GetNode<Button>(layout + "ConnectionToggleButton");
_connectionToggle.Pressed += () =>
{
_connectionExpanded = !_connectionExpanded;
RefreshHudVisibility();
};
_actionDock = GetNode<Control>(layout + "BottomRightActionDock");
_actionGrid = GetNode<Control>(layout + "BottomRightActionDock/ActionGrid");
_targetPicker = GetNode<Control>(layout + "BottomRightActionDock/TargetPicker");
_targetTitle = GetNode<Label>(layout + "BottomRightActionDock/TargetPicker/TargetTitle");
_targetHelp = GetNode<Label>(layout + "BottomRightActionDock/TargetPicker/TargetHelp");
_targetChoices = GetNode<VBoxContainer>(layout + "BottomRightActionDock/TargetPicker/TargetScroll/TargetChoices");
_utilityPanel = GetNode<Control>(layout + "BattleUtilityPanel");
_contextBar = GetNode<Control>(layout + "BottomContextBar");
_characterPanel = GetNode<Control>(layout + "BottomLeftCharacterPanel");
_queuePanel = GetNode<Control>(layout + "TopTurnQueue");
_queueCards = GetNode<HBoxContainer>(layout + "TopTurnQueue/QueueContent/QueueScroll/QueueCards");
_rewardLabel = GetNode<Label>(layout + "TopLeftMissionPanel/MissionInfo/Reward");
RefreshHudVisibility();
}
private void RefreshHudVisibility()
{
if (_connectionPanel is null)
{
return;
}
var playing = _store.IsStarted;
var disconnected = _session.State != SessionState.Connected;
_connectionToggle.Visible = playing;
_connectionPanel.Visible = !playing || _connectionExpanded || disconnected;
_connectionPanel.AnchorTop = playing ? 0.08f : 0.01f;
_connectionPanel.AnchorBottom = playing ? 0.29f : 0.22f;
_connectionToggle.Text = _connectionPanel.Visible
? "服务器设置 ▲"
: "● 已连接 · 服务器 ▼";
var kind = _store.PendingDecision?.Kind;
var choosingAction = playing && kind == SoloDecisionKinds.ActionType;
var choosingTarget = playing && kind == SoloDecisionKinds.Targets;
_actionDock.Visible = choosingAction || choosingTarget;
_actionDock.AnchorTop = choosingTarget ? 0.41f : 0.50f;
_actionGrid.Visible = choosingAction;
_targetPicker.Visible = choosingTarget;
_contextBar.Visible = playing && kind is (SoloDecisionKinds.ActionType
or SoloDecisionKinds.Targets or SoloDecisionKinds.TargetGrid or SoloDecisionKinds.TargetGrids);
_utilityPanel.Visible = _store.Snapshot is not null;
_characterPanel.Visible = _store.Snapshot?.PlayerGuid is not null;
_queuePanel.Visible = _store.Snapshot?.Queue.Count > 0;
}
private void UpdateTargetPicker(TargetsPayload? payload)
{
foreach (var child in _targetChoices.GetChildren())
{
_targetChoices.RemoveChild(child);
child.QueueFree();
}
_targetChoiceButtons.Clear();
if (payload is null)
{
return;
}
_targetTitle.Text = string.IsNullOrWhiteSpace(payload.SkillName)
? "选择目标"
: $"{payload.SkillName} · 目标";
foreach (var target in payload.Targets)
{
var guid = target.Guid;
var button = new Button
{
CustomMinimumSize = new Vector2(260, 54),
TooltipText = $"{target.DisplayName} · HP {target.Hp:0}/{target.MaxHp:0}"
};
button.Pressed += () => OnUnitClicked(guid);
_targetChoices.AddChild(button);
_targetChoiceButtons[guid] = button;
}
RefreshTargetChoiceStates();
}
private void RefreshTargetChoiceStates()
{
var payload = _store.PendingDecision?.ReadPayload<TargetsPayload>();
if (payload is null)
{
return;
}
var maximum = payload.SelectAll
? payload.Targets.Count
: Math.Min(Math.Max(1, payload.MaxTargets), payload.Targets.Count);
_targetHelp.Text = payload.Targets.Count == 0
? "服务器没有提供可选目标,请取消后重选行动。"
: payload.SelectAll
? $"已自动选中全部 {payload.Targets.Count} 个目标 · 点击下方确认"
: $"已选 {_selectedTargetGuids.Count}/{maximum} · 点击棋子或列表,再按下方确认";
foreach (var target in payload.Targets)
{
if (!_targetChoiceButtons.TryGetValue(target.Guid, out var button))
{
continue;
}
var selected = _selectedTargetGuids.Contains(target.Guid);
var relation = target.IsSelf || target.Guid == payload.ActorGuid
? "自己"
: target.IsTeammate ? "队友" : "敌方";
button.Text = $"{(selected ? "✓" : "○")} {relation} · {target.DisplayName}\nHP {target.Hp:0}/{target.MaxHp:0}";
button.Disabled = payload.SelectAll;
button.Modulate = selected ? new Color(1.0f, 0.92f, 0.68f) : Colors.White;
}
}
private void RenderTurnQueue(SoloGameState state)
{
var characters = state.Characters.ToDictionary(character => character.Guid, StringComparer.Ordinal);
var entries = state.Queue.OrderBy(entry => entry.HardnessTime).ThenBy(entry => entry.Order).ToArray();
var signature = $"{state.GameId}|{state.CurrentActorGuid}|"
+ string.Join("|", entries.Select(entry =>
$"{entry.Guid}:{entry.HardnessTime:R}:{entry.Order}:"
+ (characters.TryGetValue(entry.Guid, out var character) ? $"{character.Hp:R}" : "?")));
if (_queueSignature == signature)
{
return;
}
_queueSignature = signature;
foreach (var child in _queueCards.GetChildren())
{
_queueCards.RemoveChild(child);
child.QueueFree();
}
var order = 0;
foreach (var entry in entries)
{
order++;
characters.TryGetValue(entry.Guid, out var character);
var isPlayer = entry.Guid == state.PlayerGuid;
var isCurrent = entry.Guid == state.CurrentActorGuid;
var card = new PanelContainer
{
CustomMinimumSize = new Vector2(82, 86),
TooltipText = $"#{order} {entry.DisplayName}\n行动硬直 {entry.HardnessTime:0.0}"
+ (character is null ? "" : $"\nHP {character.Hp:0}/{character.MaxHp:0}"),
MouseFilter = Control.MouseFilterEnum.Ignore
};
card.AddThemeStyleboxOverride("panel", new StyleBoxFlat
{
BgColor = isCurrent ? new Color("fff0c9") : isPlayer ? new Color("e7f4ff") : new Color("f5f8ff"),
BorderColor = isCurrent ? new Color("d5a84a") : new Color("bed4e8"),
BorderWidthLeft = 1,
BorderWidthTop = 1,
BorderWidthRight = 1,
BorderWidthBottom = 1,
CornerRadiusTopLeft = 9,
CornerRadiusTopRight = 9,
CornerRadiusBottomLeft = 9,
CornerRadiusBottomRight = 9,
ContentMarginLeft = 4,
ContentMarginTop = 3,
ContentMarginRight = 4,
ContentMarginBottom = 3
});
var column = new VBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore };
column.AddThemeConstantOverride("separation", 1);
card.AddChild(column);
var avatarCenter = new CenterContainer { MouseFilter = Control.MouseFilterEnum.Ignore };
column.AddChild(avatarCenter);
var portrait = character is null ? null : LoadPortrait(character.Id);
if (portrait is not null)
{
avatarCenter.AddChild(new TextureRect
{
Texture = portrait,
CustomMinimumSize = new Vector2(42, 42),
ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize,
StretchMode = TextureRect.StretchModeEnum.KeepAspectCentered,
MouseFilter = Control.MouseFilterEnum.Ignore
});
}
else
{
avatarCenter.AddChild(new Label
{
Text = string.IsNullOrEmpty(entry.DisplayName) ? "?" : entry.DisplayName[..1],
CustomMinimumSize = new Vector2(42, 42),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
MouseFilter = Control.MouseFilterEnum.Ignore
});
}
var name = new Label
{
Text = ShortQueueName(entry.DisplayName),
CustomMinimumSize = new Vector2(72, 0),
HorizontalAlignment = HorizontalAlignment.Center,
ClipText = true,
MouseFilter = Control.MouseFilterEnum.Ignore
};
name.AddThemeFontSizeOverride("font_size", 10);
column.AddChild(name);
var time = new Label
{
Text = $"{entry.HardnessTime:0.0}",
HorizontalAlignment = HorizontalAlignment.Center,
TooltipText = "行动硬直时间",
MouseFilter = Control.MouseFilterEnum.Ignore
};
time.AddThemeFontSizeOverride("font_size", 10);
column.AddChild(time);
_queueCards.AddChild(card);
}
}
private Texture2D? LoadPortrait(long characterId)
{
if (!_portraitCache.TryGetValue(characterId, out var portrait))
{
portrait = characterId is > 0 and <= int.MaxValue
? _assetCatalog.LoadCharacterPortrait((int)characterId)
: null;
_portraitCache[characterId] = portrait;
}
return portrait;
}
private static string ShortQueueName(string displayName)
{
var name = displayName.Split(" - ", 2, StringSplitOptions.None)[0];
var comma = name.LastIndexOfAny([',', ',']);
if (comma >= 0)
{
name = name[(comma + 1)..].Trim();
}
return name.Length > 6 ? name[..6] : name;
}
private void UpdateRoundReward(SoloGameState state)
{
if (state.RoundRewards.TryGetValue(state.Round.ToString(), out var rewards) && rewards.Count > 0)
{
var summary = string.Join("、", rewards.Take(3));
_rewardLabel.Text = $"本回合奖励:{summary}{(rewards.Count > 3 ? "…" : "")}";
_rewardLabel.TooltipText = $"第 {state.Round} 回合奖励:{string.Join("、", rewards)}";
}
else
{
_rewardLabel.Text = "本回合奖励:—";
_rewardLabel.TooltipText = "本回合没有奖励";
}
}
}
@@ -0,0 +1 @@
uid://co75w1xytnbrg
+455
View File
@@ -0,0 +1,455 @@
using OSM.Client.Autoload;
using OSM.Client.Contracts;
namespace OSM.Client.Screens.Battle;
/// <summary>
/// BattleScreen 的覆盖层与表现控制部分:重连遮罩、AI 托管横幅、战斗日志抽屉、结算页、
/// 错误提示条、表现跳过按钮与焦点导航。
/// <para>与 <c>BattleScreen.cs</c>(世界 / 单位 / 决策)分开,避免单文件继续膨胀;
/// 两边通过同名 partial 类共享字段。</para>
/// </summary>
public partial class BattleScreen
{
private const ulong ErrorToastDurationMs = 6_000;
private const ulong NoticeToastDurationMs = 3_000;
private Button _dropButton = null!;
private Button _hideGridButton = null!;
private Button _logButton = null!;
private Button _skipAnimationButton = null!;
private Control _reconnectOverlay = null!;
private Label _reconnectDetail = null!;
private Button _reconnectNowButton = null!;
private Button _reconnectAbortButton = null!;
private Control _aiHostedBanner = null!;
private Control _errorToast = null!;
private Label _toastLabel = null!;
private Control _logDrawer = null!;
private ScrollContainer _logScroll = null!;
private RichTextLabel _logText = null!;
private Button _logCloseButton = null!;
private Control _resultScreen = null!;
private Label _resultWinner = null!;
private Label _resultSummary = null!;
private Button _resultRestartButton = null!;
private Button _resultCloseButton = null!;
private const int MaxRenderedLogLines = 500;
private const ulong LogRefreshIntervalMs = 250;
private int _renderedLogLines;
private bool _logDirty;
private ulong _nextLogRefreshAtMs;
private ulong _toastHideAtMs;
private bool _reconnectOverlayVisible;
private void InitializeOverlays()
{
const string layout = "HudLayer/SafeArea/Layout/";
const string overlay = "OverlayLayer/";
const string reconnect = overlay + "ReconnectOverlay/ReconnectCenter/ReconnectCard/ReconnectContent/";
_dropButton = GetNode<Button>(layout + "ConnectionPanel/ConnectionContent/ConnectionButtons/DropButton");
_hideGridButton = GetNode<Button>(layout + "BattleUtilityPanel/UtilityRow/HideGridButton");
_logButton = GetNode<Button>(layout + "BattleUtilityPanel/UtilityRow/LogButton");
_skipAnimationButton = GetNode<Button>(layout + "BottomContextBar/ContextRow/SkipAnimationButton");
_reconnectOverlay = GetNode<Control>(overlay + "ReconnectOverlay");
_reconnectDetail = GetNode<Label>(reconnect + "ReconnectDetail");
_reconnectNowButton = GetNode<Button>(reconnect + "ReconnectButtons/ReconnectNowButton");
_reconnectAbortButton = GetNode<Button>(reconnect + "ReconnectButtons/ReconnectAbortButton");
_aiHostedBanner = GetNode<Control>(overlay + "AiHostedBanner");
_errorToast = GetNode<Control>(overlay + "ErrorToast");
_toastLabel = GetNode<Label>(overlay + "ErrorToast/ToastPanel/ToastLabel");
_logDrawer = GetNode<Control>(overlay + "BattleLogDrawer");
_logScroll = GetNode<ScrollContainer>(
overlay + "BattleLogDrawer/LogPanel/LogContent/LogScroll");
_logText = GetNode<RichTextLabel>(
overlay + "BattleLogDrawer/LogPanel/LogContent/LogScroll/LogText");
_logCloseButton = GetNode<Button>(
overlay + "BattleLogDrawer/LogPanel/LogContent/LogHeader/LogCloseButton");
_resultScreen = GetNode<Control>(overlay + "ResultScreen");
_resultWinner = GetNode<Label>(
overlay + "ResultScreen/ResultCenter/ResultCard/ResultContent/ResultWinner");
_resultSummary = GetNode<Label>(
overlay + "ResultScreen/ResultCenter/ResultCard/ResultContent/ResultSummary");
_resultRestartButton = GetNode<Button>(
overlay + "ResultScreen/ResultCenter/ResultCard/ResultContent/ResultButtons/ResultRestartButton");
_resultCloseButton = GetNode<Button>(
overlay + "ResultScreen/ResultCenter/ResultCard/ResultContent/ResultButtons/ResultCloseButton");
_dropButton.Pressed += OnDropConnectionPressed;
_logButton.Pressed += OnLogPressed;
_logCloseButton.Pressed += OnLogClosePressed;
_skipAnimationButton.Pressed += OnSkipAnimationPressed;
_reconnectNowButton.Pressed += OnReconnectNowPressed;
_reconnectAbortButton.Pressed += OnReconnectAbortPressed;
_resultRestartButton.Pressed += OnResultRestartPressed;
_resultCloseButton.Pressed += OnResultClosePressed;
}
/// <summary>
/// 键鼠 + 基础手柄焦点导航:2 列的动作坞按行列接线,对话框按钮左右互通。
/// 禁用状态的按钮 Godot 会自动跳过,所以不需要在这里剔除。
/// </summary>
private void SetupFocusNavigation()
{
Button[] dock =
[
_moveButton, _attackButton,
_skillButton, _superSkillButton,
_itemButton, _endTurnButton
];
const int columns = 2;
for (var index = 0; index < dock.Length; index++)
{
var button = dock[index];
button.FocusMode = Control.FocusModeEnum.All;
var column = index % columns;
var row = index / columns;
if (column > 0)
{
button.FocusNeighborLeft = button.GetPathTo(dock[index - 1]);
}
if (column < columns - 1 && index + 1 < dock.Length)
{
button.FocusNeighborRight = button.GetPathTo(dock[index + 1]);
}
if (row > 0)
{
button.FocusNeighborTop = button.GetPathTo(dock[index - columns]);
}
if (row < (dock.Length / columns) - 1)
{
button.FocusNeighborBottom = button.GetPathTo(dock[index + columns]);
}
}
_hideGridButton.FocusNeighborRight = _hideGridButton.GetPathTo(_logButton);
_logButton.FocusNeighborLeft = _logButton.GetPathTo(_hideGridButton);
_decisionConfirm.FocusNeighborLeft = _decisionConfirm.GetPathTo(_decisionCancel);
_decisionCancel.FocusNeighborRight = _decisionCancel.GetPathTo(_decisionConfirm);
_decisionConfirm.FocusNeighborTop = _decisionConfirm.GetPathTo(_decisionOptions);
_resultRestartButton.FocusNeighborRight = _resultRestartButton.GetPathTo(_resultCloseButton);
_resultCloseButton.FocusNeighborLeft = _resultCloseButton.GetPathTo(_resultRestartButton);
_reconnectNowButton.FocusNeighborRight = _reconnectNowButton.GetPathTo(_reconnectAbortButton);
_reconnectAbortButton.FocusNeighborLeft = _reconnectAbortButton.GetPathTo(_reconnectNowButton);
}
public override void _UnhandledInput(InputEvent @event)
{
if (!@event.IsActionPressed("ui_cancel"))
{
return;
}
if (_decisionDialog.Visible && !_decisionCancel.Disabled)
{
OnDialogCancelPressed();
GetViewport().SetInputAsHandled();
return;
}
if (_logDrawer.Visible)
{
_logDrawer.Visible = false;
LogButtonState();
GetViewport().SetInputAsHandled();
return;
}
if (_resultScreen.Visible)
{
_resultScreen.Visible = false;
GetViewport().SetInputAsHandled();
}
}
/// <summary>
/// 重连遮罩与 AI 托管横幅的每帧刷新。放在 _Process 里是因为重连倒计时会一直变,
/// 而且这样就不用给 GameSession 再加一个「倒计时滴答」信号。
/// </summary>
private void UpdateReconnectOverlay()
{
if (_errorToast is not null && _errorToast.Visible && Time.GetTicksMsec() >= _toastHideAtMs)
{
_errorToast.Visible = false;
}
if (_session is null)
{
return;
}
var reconnecting = _session.IsReconnecting;
var faulted = _session.State == SessionState.Faulted;
var shouldShow = reconnecting || faulted;
if (shouldShow != _reconnectOverlayVisible)
{
_reconnectOverlayVisible = shouldShow;
_reconnectOverlay.Visible = shouldShow;
}
if (shouldShow)
{
var attempt = Math.Max(1, _session.ReconnectAttempt);
var remaining = _session.SecondsUntilReconnect;
_reconnectDetail.Text = faulted
? "连接失败。可以立即重试,或放弃并断开。"
: remaining > 0.05
? $"第 {attempt} 次重连将在 {remaining:0.0}s 后开始……"
: $"正在进行第 {attempt} 次重连……";
}
var aiHosted = _store?.Snapshot?.AiEscalated == true;
if (_aiHostedBanner.Visible != aiHosted)
{
_aiHostedBanner.Visible = aiHosted;
}
}
private void OnAnimationQueueChanged() => UpdateSkipButton();
private void OnAnimationSkipCalled(string reason)
{
// 队列被清空后所有棋子都不再被表现层接管,直接重放一次权威快照即可对齐。
ReconcileUnits(_store.Snapshot);
UpdateSkipButton();
if (reason == "表现积压")
{
ShowToast("表现已积压,画面已跳到最新权威快照。", isError: false);
}
}
private void UpdateSkipButton()
{
var busy = _animator.IsBusy;
if (_skipAnimationButton.Visible != busy)
{
_skipAnimationButton.Visible = busy;
}
if (busy)
{
_skipAnimationButton.Text = $"跳过表现 ({_animator.PendingCount})";
}
}
private void ShowToast(string message, bool isError = true)
{
if (_errorToast is null)
{
return;
}
_toastLabel.Text = message;
_errorToast.Visible = true;
_toastHideAtMs = Time.GetTicksMsec()
+ (isError ? ErrorToastDurationMs : NoticeToastDurationMs);
}
private void OnLogSnapshotChanged(int envelopeSequence) => _logDirty = true;
private void OnLogDecisionChanged() => _logDirty = true;
private void OnLogGameFinished(string winnerName) => _logDirty = true;
private void OnLogPressed()
{
_logDrawer.Visible = !_logDrawer.Visible;
LogButtonState();
if (_logDrawer.Visible)
{
RefreshLogDrawer(force: true);
}
}
private void OnLogClosePressed()
{
_logDrawer.Visible = false;
LogButtonState();
}
private void LogButtonState()
{
_logButton.Text = _logDrawer.Visible ? "关闭日志" : "战斗日志";
if (_logDrawer.Visible)
{
_logCloseButton.GrabFocus();
}
}
private void ScrollLogToBottom()
{
_logScroll.ScrollVertical = (int)_logScroll.GetVScrollBar().MaxValue;
}
/// <summary>
/// 日志抽屉刷新:只在抽屉可见时、且最多每 <see cref="LogRefreshIntervalMs"/> 毫秒重建一次。
/// <para><b>不要退回逐行 <c>AppendText</c></b>:RichTextLabel 开了 <c>fit_content</c> 之后,
/// 每次追加都会重新排版整段文本,长局(几千行)下退化成 O(n²),足以把主循环卡住几分钟
/// —— 表现是「客户端整个卡死、连 SceneTreeTimer 都不再触发」,而不是简单的日志变慢。</para>
/// <para>抽屉关闭时只打脏标记,打开时一次性重建,并只渲染最后
/// <see cref="MaxRenderedLogLines"/> 行。</para>
/// </summary>
private void RefreshLogDrawer(bool force = false)
{
if (_logText is null || _store is null)
{
return;
}
if (!force)
{
if (!_logDirty || !_logDrawer.Visible || Time.GetTicksMsec() < _nextLogRefreshAtMs)
{
return;
}
}
var lines = _store.LogLines;
if (!force && lines.Count == _renderedLogLines)
{
_logDirty = false;
return;
}
_logDirty = false;
_renderedLogLines = lines.Count;
_nextLogRefreshAtMs = Time.GetTicksMsec() + LogRefreshIntervalMs;
var start = Math.Max(0, lines.Count - MaxRenderedLogLines);
var builder = new System.Text.StringBuilder();
if (start > 0)
{
builder.Append($"……(已省略较早的 {start} 行)\n");
}
for (var index = start; index < lines.Count; index++)
{
builder.Append(lines[index]).Append('\n');
}
// 一次性赋值 = 只重排一次;逐行追加是这套卡死的根源。
_logText.Text = builder.ToString();
if (_logDrawer.Visible)
{
ScrollLogToBottom();
}
}
private void ShowResultScreen(string winnerName)
{
_resultWinner.Text = string.IsNullOrEmpty(winnerName) ? "对局结束" : $"胜者:{winnerName}";
var state = _store.Snapshot;
_resultSummary.Text = state is null
? "本局没有收到权威快照。"
: $"回合 {state.Round} · 用时 {state.TotalTime:0.0}s · 参战 {state.Characters.Count} 名"
+ (state.GameOver ? " · 服务器已判定结束" : string.Empty);
_resultRestartButton.Disabled = _session.State != SessionState.Connected;
_resultScreen.Visible = true;
_resultRestartButton.GrabFocus();
}
/// <summary>
/// 服务器放弃了一条挂起决策(对局结束 / 接管 / 断线)。
/// 没有这条通知时,界面只能靠超时判断「为什么轮到我却什么都没发生」。
/// </summary>
private void OnDecisionDropped(string requestId, string reason)
{
// 不是断线,保留表现基线:没必要把画面直接对齐重建。
ClearLocalInteraction("服务器放弃决策", resetAnimationBaseline: false);
ShowToast(
string.IsNullOrWhiteSpace(reason)
? "服务器放弃了一条挂起决策。"
: $"服务器放弃决策:{reason}",
isError: false);
}
/// <summary>
/// 清空一切「属于上一个连接」的本地中间状态:选中格、选中目标、对话框、网格高亮,
/// 以及(默认)差分用的上一帧快照 —— 置空后下一帧快照会被当作首帧,直接对齐权威状态而不补间。
/// </summary>
private void ClearLocalInteraction(string reason, bool resetAnimationBaseline = true)
{
_selectedGridId = null;
_selectedTargetGuids.Clear();
_dialogValues.Clear();
_dialogAvailable.Clear();
_dialogDetails.Clear();
_decisionDialog.Visible = false;
_confirmGridButton.Disabled = true;
_gridOverlay.ClearInteraction();
if (resetAnimationBaseline)
{
_previousSnapshot = null;
}
GD.Print($"[界面] 已清除本地选择({reason})。");
}
private void OnDropConnectionPressed()
{
if (_session.State != SessionState.Connected)
{
return;
}
ShowToast("已强制中断连接(不发送关闭握手),等待自动重连……", isError: false);
// 与「断开」不同:这是非计划中断,会自动重连并补发 gaming.resume。
_session.AbortConnection();
}
private void OnReconnectNowPressed()
{
_session.RequestImmediateReconnect();
}
private async void OnReconnectAbortPressed()
{
_session.AutoReconnect = false;
await _session.DisconnectAsync();
UpdateConnectionUi();
}
private async void OnResultRestartPressed()
{
if (_session.State != SessionState.Connected)
{
ShowToast("连接已断开,无法开始新局。");
return;
}
try
{
_resultScreen.Visible = false;
_renderedLogLines = 0;
_logText.Clear();
ClearLocalInteraction("开始新局");
_animator.SkipAll("开始新局");
await _store.StartGameAsync(new SoloStartOptions());
}
catch (Exception exception)
{
ShowToast(exception.Message);
}
}
private void OnResultClosePressed()
{
// 关闭结算页但保留战场,方便查看最后一帧权威状态。
_resultScreen.Visible = false;
UpdateWelcomeUi();
}
private void OnSkipAnimationPressed()
{
_animator.SkipAll("手动跳过");
ShowToast("已跳过表现,画面立即对齐最新权威快照。", isError: false);
}
}
@@ -0,0 +1 @@
uid://cqduufpprpdrt
+357 -56
View File
@@ -7,19 +7,30 @@ namespace OSM.Client.Screens.Battle;
public partial class BattleScreen : Node public partial class BattleScreen : Node
{ {
/// <summary>选项超过这个数量就改用可点击列表,而不是一次只显示一项的下拉框。</summary>
private const int OptionButtonThreshold = 3;
private GameSession _session = null!; private GameSession _session = null!;
private BattleStore _store = null!; private BattleStore _store = null!;
private GameSettings _settings = null!; private GameSettings _settings = null!;
private GridOverlay2D _gridOverlay = null!; private GridOverlay2D _gridOverlay = null!;
private GreyboxMap2D _greyboxMap = null!; private GreyboxMap2D _greyboxMap = null!;
private BattleCameraController _battleCamera = null!;
private string? _framedGameId;
private Node2D _unitsLayer = null!; private Node2D _unitsLayer = null!;
private PackedScene _unitViewScene = null!; private PackedScene _unitViewScene = null!;
private readonly Dictionary<string, UnitView> _unitViews = []; private readonly Dictionary<string, UnitView> _unitViews = [];
private BattleAnimator _animator = null!;
private SoloGameState? _previousSnapshot;
private LineEdit _endpointEdit = null!; private LineEdit _endpointEdit = null!;
private Label _connectionLabel = null!; private Label _connectionLabel = null!;
private Button _connectButton = null!; private Button _connectButton = null!;
private Button _startButton = null!; private Button _startButton = null!;
private Control _welcomePanel = null!;
private Label _welcomeStatus = null!;
private Button _welcomeConnectButton = null!;
private Button _welcomeStartButton = null!;
private Label _roundLabel = null!; private Label _roundLabel = null!;
private Label _objectiveLabel = null!; private Label _objectiveLabel = null!;
private Label _characterName = null!; private Label _characterName = null!;
@@ -28,8 +39,6 @@ public partial class BattleScreen : Node
private Label _dpLabel = null!; private Label _dpLabel = null!;
private Label _contextLabel = null!; private Label _contextLabel = null!;
private Label _timeoutLabel = null!; private Label _timeoutLabel = null!;
private Label _queueActor1 = null!;
private Label _queueActor2 = null!;
private Button _moveButton = null!; private Button _moveButton = null!;
private Button _attackButton = null!; private Button _attackButton = null!;
@@ -43,6 +52,7 @@ public partial class BattleScreen : Node
private Control _decisionDialog = null!; private Control _decisionDialog = null!;
private Label _decisionTitle = null!; private Label _decisionTitle = null!;
private Label _decisionInfo = null!; private Label _decisionInfo = null!;
private ScrollContainer _decisionInfoScroll = null!;
private OptionButton _decisionOptions = null!; private OptionButton _decisionOptions = null!;
private ItemList _decisionChoiceList = null!; private ItemList _decisionChoiceList = null!;
private LineEdit _decisionTextInput = null!; private LineEdit _decisionTextInput = null!;
@@ -53,30 +63,45 @@ public partial class BattleScreen : Node
private readonly List<bool> _dialogAvailable = []; private readonly List<bool> _dialogAvailable = [];
private readonly List<string> _dialogDetails = []; private readonly List<string> _dialogDetails = [];
private string? _dialogDecisionKind; private string? _dialogDecisionKind;
private bool _dialogUsesList;
private bool _dialogMultiSelect;
private string _skillIntent = "normal"; private string _skillIntent = "normal";
private string? _submittedAction;
private ulong _decisionReceivedAtMs; private ulong _decisionReceivedAtMs;
private long? _selectedGridId; private long? _selectedGridId;
private readonly HashSet<string> _selectedTargetGuids = new(StringComparer.Ordinal); private readonly HashSet<string> _selectedTargetGuids = new(StringComparer.Ordinal);
public override void _Ready() public override void _Ready()
{ {
// 单位 Area2D 的 input_event 依赖 Viewport 的物理对象拾取。
GetViewport().PhysicsObjectPicking = true;
_session = GetNode<GameSession>("/root/GameSession"); _session = GetNode<GameSession>("/root/GameSession");
_store = GetNode<BattleStore>("/root/BattleStore"); _store = GetNode<BattleStore>("/root/BattleStore");
_settings = GetNode<GameSettings>("/root/GameSettings"); _settings = GetNode<GameSettings>("/root/GameSettings");
_gridOverlay = GetNode<GridOverlay2D>("BattleWorld/GridOverlay2D"); _gridOverlay = GetNode<GridOverlay2D>("BattleWorld/GridOverlay2D");
_greyboxMap = GetNode<GreyboxMap2D>("BattleWorld/GroundLayer/GreyboxPreview"); _greyboxMap = GetNode<GreyboxMap2D>("BattleWorld/GroundLayer/GreyboxPreview");
_battleCamera = GetNode<BattleCameraController>("BattleCamera");
_unitsLayer = GetNode<Node2D>("BattleWorld/UnitsLayer"); _unitsLayer = GetNode<Node2D>("BattleWorld/UnitsLayer");
_unitViewScene = GD.Load<PackedScene>("res://src/Units/UnitView.tscn"); _unitViewScene = GD.Load<PackedScene>("res://src/Units/UnitView.tscn");
// 表现层:与权威状态解耦的补间队列。它只消费快照差分,绝不反过来影响网络或决策。
_animator = new BattleAnimator { Name = "BattleAnimator" };
AddChild(_animator);
_animator.Initialize(guid => _unitViews.GetValueOrDefault(guid));
_animator.QueueChanged += OnAnimationQueueChanged;
_animator.SkipCalled += OnAnimationSkipCalled;
const string layout = "HudLayer/SafeArea/Layout/"; const string layout = "HudLayer/SafeArea/Layout/";
_endpointEdit = GetNode<LineEdit>(layout + "ConnectionPanel/ConnectionContent/EndpointEdit"); _endpointEdit = GetNode<LineEdit>(layout + "ConnectionPanel/ConnectionContent/EndpointEdit");
_connectionLabel = GetNode<Label>(layout + "ConnectionPanel/ConnectionContent/ConnectionStatus"); _connectionLabel = GetNode<Label>(layout + "ConnectionPanel/ConnectionContent/ConnectionStatus");
_connectButton = GetNode<Button>(layout + "ConnectionPanel/ConnectionContent/ConnectionButtons/ConnectButton"); _connectButton = GetNode<Button>(layout + "ConnectionPanel/ConnectionContent/ConnectionButtons/ConnectButton");
_startButton = GetNode<Button>(layout + "ConnectionPanel/ConnectionContent/ConnectionButtons/StartButton"); _startButton = GetNode<Button>(layout + "ConnectionPanel/ConnectionContent/ConnectionButtons/StartButton");
_welcomePanel = GetNode<Control>(layout + "WelcomePanel");
_welcomeStatus = GetNode<Label>(layout + "WelcomePanel/WelcomeContent/WelcomeStatus");
_welcomeConnectButton = GetNode<Button>(layout + "WelcomePanel/WelcomeContent/WelcomeButtons/WelcomeConnectButton");
_welcomeStartButton = GetNode<Button>(layout + "WelcomePanel/WelcomeContent/WelcomeButtons/WelcomeStartButton");
_roundLabel = GetNode<Label>(layout + "TopLeftMissionPanel/MissionInfo/Round"); _roundLabel = GetNode<Label>(layout + "TopLeftMissionPanel/MissionInfo/Round");
_objectiveLabel = GetNode<Label>(layout + "TopLeftMissionPanel/MissionInfo/Objective"); _objectiveLabel = GetNode<Label>(layout + "TopLeftMissionPanel/MissionInfo/Objective");
_queueActor1 = GetNode<Label>(layout + "TopTurnQueue/QueueRow/Actor1");
_queueActor2 = GetNode<Label>(layout + "TopTurnQueue/QueueRow/Actor2");
_characterName = GetNode<Label>(layout + "BottomLeftCharacterPanel/CharacterInfo/Name"); _characterName = GetNode<Label>(layout + "BottomLeftCharacterPanel/CharacterInfo/Name");
_hpLabel = GetNode<Label>(layout + "BottomLeftCharacterPanel/CharacterInfo/Hp"); _hpLabel = GetNode<Label>(layout + "BottomLeftCharacterPanel/CharacterInfo/Hp");
_mpLabel = GetNode<Label>(layout + "BottomLeftCharacterPanel/CharacterInfo/Mp"); _mpLabel = GetNode<Label>(layout + "BottomLeftCharacterPanel/CharacterInfo/Mp");
@@ -94,7 +119,12 @@ public partial class BattleScreen : Node
_decisionDialog = GetNode<Control>("OverlayLayer/DecisionDialog"); _decisionDialog = GetNode<Control>("OverlayLayer/DecisionDialog");
_decisionTitle = GetNode<Label>("OverlayLayer/DecisionDialog/DialogPanel/DialogContent/Title"); _decisionTitle = GetNode<Label>("OverlayLayer/DecisionDialog/DialogPanel/DialogContent/Title");
_decisionInfo = GetNode<Label>("OverlayLayer/DecisionDialog/DialogPanel/DialogContent/Info"); // 详情文本可能是一整张角色/技能说明书,必须放在 ScrollContainer 里,
// 否则弹窗会被撑到超出窗口、把确认按钮顶到屏幕外(现象:弹窗点不动)。
_decisionInfoScroll = GetNode<ScrollContainer>(
"OverlayLayer/DecisionDialog/DialogPanel/DialogContent/InfoScroll");
_decisionInfo = GetNode<Label>(
"OverlayLayer/DecisionDialog/DialogPanel/DialogContent/InfoScroll/Info");
_decisionOptions = GetNode<OptionButton>("OverlayLayer/DecisionDialog/DialogPanel/DialogContent/Options"); _decisionOptions = GetNode<OptionButton>("OverlayLayer/DecisionDialog/DialogPanel/DialogContent/Options");
_decisionChoiceList = GetNode<ItemList>("OverlayLayer/DecisionDialog/DialogPanel/DialogContent/ChoiceList"); _decisionChoiceList = GetNode<ItemList>("OverlayLayer/DecisionDialog/DialogPanel/DialogContent/ChoiceList");
_decisionTextInput = GetNode<LineEdit>("OverlayLayer/DecisionDialog/DialogPanel/DialogContent/TextInput"); _decisionTextInput = GetNode<LineEdit>("OverlayLayer/DecisionDialog/DialogPanel/DialogContent/TextInput");
@@ -105,12 +135,14 @@ public partial class BattleScreen : Node
_endpointEdit.Text = _settings.SoloServerUrl; _endpointEdit.Text = _settings.SoloServerUrl;
_connectButton.Pressed += OnConnectPressed; _connectButton.Pressed += OnConnectPressed;
_startButton.Pressed += OnStartPressed; _startButton.Pressed += OnStartPressed;
_welcomeConnectButton.Pressed += OnConnectPressed;
_welcomeStartButton.Pressed += OnStartPressed;
_moveButton.Pressed += () => SubmitActionType("Move"); _moveButton.Pressed += () => SubmitActionType("Move");
_attackButton.Pressed += () => SubmitActionType("NormalAttack"); _attackButton.Pressed += () => SubmitActionType("NormalAttack");
_skillButton.Pressed += () => SubmitSkillAction("normal"); _skillButton.Pressed += () => SubmitSkillAction("normal");
_superSkillButton.Pressed += () => SubmitSkillAction("super"); _superSkillButton.Pressed += () => SubmitSkillAction("super");
_itemButton.Pressed += () => SubmitActionType("UseItem"); _itemButton.Pressed += () => SubmitActionType("UseItem");
GetNode<Button>(layout + "BottomRightActionDock/ActionGrid/HideGridButton").Pressed += HideGrid; GetNode<Button>(layout + "BattleUtilityPanel/UtilityRow/HideGridButton").Pressed += OnCenterMapPressed;
_endTurnButton.Pressed += OnEndTurnPressed; _endTurnButton.Pressed += OnEndTurnPressed;
_confirmGridButton.Pressed += OnConfirmGridPressed; _confirmGridButton.Pressed += OnConfirmGridPressed;
_contextCancelButton.Pressed += OnContextCancelPressed; _contextCancelButton.Pressed += OnContextCancelPressed;
@@ -118,6 +150,7 @@ public partial class BattleScreen : Node
_decisionCancel.Pressed += OnDialogCancelPressed; _decisionCancel.Pressed += OnDialogCancelPressed;
_decisionOptions.ItemSelected += OnDialogOptionSelected; _decisionOptions.ItemSelected += OnDialogOptionSelected;
_decisionChoiceList.MultiSelected += OnInquiryChoiceToggled; _decisionChoiceList.MultiSelected += OnInquiryChoiceToggled;
_decisionChoiceList.ItemSelected += OnDialogListSelected;
_decisionTextInput.TextChanged += _ => _decisionConfirm.Disabled = false; _decisionTextInput.TextChanged += _ => _decisionConfirm.Disabled = false;
_decisionNumberInput.ValueChanged += _ => _decisionConfirm.Disabled = false; _decisionNumberInput.ValueChanged += _ => _decisionConfirm.Disabled = false;
@@ -125,22 +158,35 @@ public partial class BattleScreen : Node
_gridOverlay.CellClicked += OnGridCellClicked; _gridOverlay.CellClicked += OnGridCellClicked;
_session.StateChanged += OnSessionStateChanged; _session.StateChanged += OnSessionStateChanged;
_session.SessionError += ShowError; _session.SessionError += ShowError;
_session.Reconnected += OnSessionReconnected;
_store.SnapshotChanged += OnSnapshotChanged; _store.SnapshotChanged += OnSnapshotChanged;
_store.DecisionChanged += OnDecisionChanged; _store.DecisionChanged += OnDecisionChanged;
_store.ProtocolError += ShowError; _store.ProtocolError += ShowError;
_store.GameFinished += OnGameFinished; _store.GameFinished += OnGameFinished;
_store.ConnectionRecovered += OnConnectionRecovered;
_store.DecisionDropped += OnDecisionDropped;
_store.SnapshotChanged += OnLogSnapshotChanged;
_store.DecisionChanged += OnLogDecisionChanged;
_store.GameFinished += OnLogGameFinished;
InitializeOverlays();
InitializeBattleHud();
SetupFocusNavigation();
UpdateConnectionUi(); UpdateConnectionUi();
UpdateActionButtons(); UpdateActionButtons();
HideGrid(); _gridOverlay.ClearInteraction();
} }
public override void _Process(double delta) public override void _Process(double delta)
{ {
UpdateReconnectOverlay();
var decision = _store?.PendingDecision; var decision = _store?.PendingDecision;
if (decision?.TimeoutMs is not int timeoutMs || timeoutMs <= 0) if (decision?.TimeoutMs is not int timeoutMs || timeoutMs <= 0)
{ {
_timeoutLabel.Text = string.Empty; // 重连后服务器补发的决策请求不带 timeoutMs(见 AttachSink),
// 不能假装有倒计时,只能如实说明。
_timeoutLabel.Text = decision is null ? string.Empty : "重连后无倒计时";
return; return;
} }
@@ -151,10 +197,16 @@ public partial class BattleScreen : Node
public override void _ExitTree() public override void _ExitTree()
{ {
if (_animator is not null)
{
_animator.QueueChanged -= OnAnimationQueueChanged;
_animator.SkipCalled -= OnAnimationSkipCalled;
}
if (_session is not null) if (_session is not null)
{ {
_session.StateChanged -= OnSessionStateChanged; _session.StateChanged -= OnSessionStateChanged;
_session.SessionError -= ShowError; _session.SessionError -= ShowError;
_session.Reconnected -= OnSessionReconnected;
} }
if (_store is not null) if (_store is not null)
{ {
@@ -162,6 +214,11 @@ public partial class BattleScreen : Node
_store.DecisionChanged -= OnDecisionChanged; _store.DecisionChanged -= OnDecisionChanged;
_store.ProtocolError -= ShowError; _store.ProtocolError -= ShowError;
_store.GameFinished -= OnGameFinished; _store.GameFinished -= OnGameFinished;
_store.ConnectionRecovered -= OnConnectionRecovered;
_store.DecisionDropped -= OnDecisionDropped;
_store.SnapshotChanged -= OnLogSnapshotChanged;
_store.DecisionChanged -= OnLogDecisionChanged;
_store.GameFinished -= OnLogGameFinished;
} }
} }
@@ -183,12 +240,13 @@ public partial class BattleScreen : Node
_settings.SetSoloServerUrl(endpoint.ToString()); _settings.SetSoloServerUrl(endpoint.ToString());
_connectButton.Disabled = true; _connectButton.Disabled = true;
_welcomeConnectButton.Disabled = true;
_connectionLabel.Text = "● 正在连接……"; _connectionLabel.Text = "● 正在连接……";
var connected = await _session.ConnectAsync(endpoint); var connected = await _session.ConnectAsync(endpoint);
_connectButton.Disabled = false; _connectButton.Disabled = false;
if (!connected) if (!connected)
{ {
ShowError("无法连接 Solo WebAPI,请确认服务已在 11030 端口启动。"); ShowError("无法连接 Solo WebAPI,请确认服务已在 12030 端口启动。");
} }
UpdateConnectionUi(); UpdateConnectionUi();
} }
@@ -204,13 +262,16 @@ public partial class BattleScreen : Node
try try
{ {
_startButton.Disabled = true; _startButton.Disabled = true;
_welcomeStartButton.Disabled = true;
_contextLabel.Text = "已发送 gaming.start,等待角色选择请求……"; _contextLabel.Text = "已发送 gaming.start,等待角色选择请求……";
await _store.StartGameAsync(new SoloStartOptions()); await _store.StartGameAsync(new SoloStartOptions());
UpdateWelcomeUi();
} }
catch (Exception exception) catch (Exception exception)
{ {
ShowError(exception.Message); ShowError(exception.Message);
_startButton.Disabled = false; _startButton.Disabled = false;
UpdateWelcomeUi();
} }
} }
@@ -223,12 +284,15 @@ public partial class BattleScreen : Node
try try
{ {
// 记录本次提交的行动类型:服务器的下一次决策会告诉我们它有没有被作废。
_submittedAction = actionType;
await _store.SubmitDecisionAsync(new { actionType }); await _store.SubmitDecisionAsync(new { actionType });
UpdateActionButtons(); UpdateActionButtons();
_contextLabel.Text = $"已提交 {actionType},等待服务器裁定……"; _contextLabel.Text = $"已提交 {actionType},等待服务器裁定……";
} }
catch (Exception exception) catch (Exception exception)
{ {
_submittedAction = null;
ShowError(exception.Message); ShowError(exception.Message);
} }
} }
@@ -267,6 +331,14 @@ public partial class BattleScreen : Node
return; return;
} }
// 先把表现任务入队(此时棋子还在旧位置,Move 的起点才正确),再应用新快照。
var requests = BattleSnapshotDiff.Build(_previousSnapshot, state);
_previousSnapshot = state;
if (requests.Count > 0)
{
_animator.Submit(requests, guid => AuthoritativePosition(state, guid));
}
_roundLabel.Text = $"Round {state.Round} · {state.TotalTime:0.0}s"; _roundLabel.Text = $"Round {state.Round} · {state.TotalTime:0.0}s";
_objectiveLabel.Text = state.TeamMode _objectiveLabel.Text = state.TeamMode
? $"团队比分:{string.Join(" / ", state.Teams.Select(team => $"{team.Name} {team.Score}"))}" ? $"团队比分:{string.Join(" / ", state.Teams.Select(team => $"{team.Name} {team.Score}"))}"
@@ -275,10 +347,16 @@ public partial class BattleScreen : Node
if (state.Map is not null) if (state.Map is not null)
{ {
var mapSize = new Vector2I(state.Map.Length, state.Map.Width); var mapSize = new Vector2I(state.Map.Length, state.Map.Width);
_greyboxMap.SetMapSize(mapSize); // 地面直接吃权威地图数据(坐标 + 高度 + 颜色),不再假设稠密矩形、也不画协议外的掩体。
_greyboxMap.SetMap(state.Map);
_gridOverlay.SetMapSize(mapSize); _gridOverlay.SetMapSize(mapSize);
_gridOverlay.SetGridCoordinates(state.Map.Grids.Select(grid => _gridOverlay.SetGridCoordinates(state.Map.Grids.Select(grid =>
new KeyValuePair<long, Vector2I>(grid.Id, new Vector2I(grid.X, grid.Y)))); new KeyValuePair<long, Vector3I>(grid.Id, new Vector3I(grid.X, grid.Y, grid.Z))));
if (_framedGameId != state.GameId)
{
_battleCamera.FrameMap(state.Map, GetViewport().GetVisibleRect().Size, _gridOverlay.CellSize);
_framedGameId = state.GameId;
}
} }
ReconcileUnits(state); ReconcileUnits(state);
@@ -286,8 +364,9 @@ public partial class BattleScreen : Node
var player = state.Characters.FirstOrDefault(character => character.Guid == state.PlayerGuid); var player = state.Characters.FirstOrDefault(character => character.Guid == state.PlayerGuid);
if (player is not null) if (player is not null)
{ {
_characterName.Text = $"{player.DisplayName} Lv.{player.Level}" _characterName.Text = player.DisplayName
+ (state.AiEscalated ? " · AI 托管" : string.Empty); + (state.AiEscalated ? " · AI 托管" : string.Empty);
_characterName.TooltipText = player.DisplayName;
_hpLabel.Text = $"HP {player.Hp:0} / {player.MaxHp:0}"; _hpLabel.Text = $"HP {player.Hp:0} / {player.MaxHp:0}";
_mpLabel.Text = $"MP {player.Mp:0} / {player.MaxMp:0} EP {player.Ep:0} / {player.MaxEp:0}"; _mpLabel.Text = $"MP {player.Mp:0} / {player.MaxMp:0} EP {player.Ep:0} / {player.MaxEp:0}";
} }
@@ -296,10 +375,11 @@ public partial class BattleScreen : Node
? "决策点 —" ? "决策点 —"
: $"决策点 {state.PlayerDp.Current} / {state.PlayerDp.Max} · 已行动 {state.PlayerDp.ActionsTaken}"; : $"决策点 {state.PlayerDp.Current} / {state.PlayerDp.Max} · 已行动 {state.PlayerDp.ActionsTaken}";
_queueActor1.Text = state.Queue.ElementAtOrDefault(0)?.DisplayName ?? "—"; RenderTurnQueue(state);
_queueActor2.Text = state.Queue.ElementAtOrDefault(1)?.DisplayName ?? "—"; UpdateRoundReward(state);
_startButton.Disabled = state.Running; _startButton.Disabled = state.Running;
UpdateActionButtons(); UpdateActionButtons();
UpdateWelcomeUi();
} }
private void OnDecisionChanged() private void OnDecisionChanged()
@@ -308,9 +388,13 @@ public partial class BattleScreen : Node
_selectedTargetGuids.Clear(); _selectedTargetGuids.Clear();
_decisionReceivedAtMs = Time.GetTicksMsec(); _decisionReceivedAtMs = Time.GetTicksMsec();
_confirmGridButton.Disabled = true; _confirmGridButton.Disabled = true;
_confirmGridButton.Text = "确认";
_contextCancelButton.Text = "取消";
_decisionDialog.Visible = false; _decisionDialog.Visible = false;
_gridOverlay.ClearInteraction(); _gridOverlay.ClearInteraction();
UpdateTargetPicker(null);
UpdateActionButtons(); UpdateActionButtons();
UpdateWelcomeUi();
var decision = _store.PendingDecision; var decision = _store.PendingDecision;
if (decision is null) if (decision is null)
@@ -319,6 +403,10 @@ public partial class BattleScreen : Node
return; return;
} }
// 上一次提交的结局:紧邻的决策类型是唯一可依据的信号(服务器没有拒绝回执)。
var cancelledReason = DecisionUiRules.DetectCancelledAction(_submittedAction, decision.Kind);
_submittedAction = null;
_contextLabel.Text = $"服务器请求:{decision.Kind}"; _contextLabel.Text = $"服务器请求:{decision.Kind}";
switch (decision.Kind) switch (decision.Kind)
{ {
@@ -382,30 +470,62 @@ public partial class BattleScreen : Node
case SoloDecisionKinds.Targets: case SoloDecisionKinds.Targets:
{ {
var payload = decision.ReadPayload<TargetsPayload>(); var payload = decision.ReadPayload<TargetsPayload>();
var targetCount = payload?.Targets.Count ?? 0;
var maxTargets = Math.Max(1, payload?.MaxTargets ?? 1);
if (payload?.SelectAll == true) if (payload?.SelectAll == true)
{ {
_contextCancelButton.Text = "取消选择";
_selectedTargetGuids.UnionWith(payload.Targets.Select(target => target.Guid)); _selectedTargetGuids.UnionWith(payload.Targets.Select(target => target.Guid));
_confirmGridButton.Disabled = _selectedTargetGuids.Count == 0; _confirmGridButton.Disabled = _selectedTargetGuids.Count == 0;
_confirmGridButton.Text = "确认全体";
_contextLabel.Text = _selectedTargetGuids.Count == 0
? "服务器未提供可选目标。"
: $"已默认选中全部 {_selectedTargetGuids.Count} 个目标;点击「确认全体」提交。";
} }
else
{
_contextCancelButton.Text = "取消选择";
_confirmGridButton.Text = "确认目标";
if (payload is { Targets.Count: 1 }
&& (payload.Targets[0].IsSelf || payload.Targets[0].Guid == payload.ActorGuid))
{
_selectedTargetGuids.Add(payload.Targets[0].Guid);
}
_confirmGridButton.Disabled = _selectedTargetGuids.Count == 0;
var instruction = targetCount == 0
? "服务器未提供可选目标,请取消后重选行动。"
: _selectedTargetGuids.Count > 0
? "已自动选中自身;点击「确认目标」提交。"
: $"点击橙框单位或右侧目标列表(0/{Math.Min(maxTargets, targetCount)}),再按「确认目标」。";
_contextLabel.Text = string.IsNullOrEmpty(payload?.SkillName) _contextLabel.Text = string.IsNullOrEmpty(payload?.SkillName)
? TargetSelectionHint(payload) ? instruction
: $"{payload.SkillName} · {TargetSelectionHint(payload)}"; : $"{payload.SkillName} · {instruction}";
}
UpdateTargetPicker(payload);
break; break;
} }
case SoloDecisionKinds.TargetGrid: case SoloDecisionKinds.TargetGrid:
_gridOverlay.SetReachableCells( {
decision.ReadPayload<TargetGridPayload>()?.GridIds ?? []); var gridIds = decision.ReadPayload<TargetGridPayload>()?.GridIds ?? [];
_contextLabel.Text = "选择服务器允许的移动格,然后确认。"; _gridOverlay.SetReachableCells(gridIds);
_confirmGridButton.Text = "确认移动";
_contextCancelButton.Text = "取消选择";
_contextLabel.Text = gridIds.Count == 0
? "服务器未提供可移动格,请取消后重选行动。"
: "点击青蓝高亮格选目的地,再点「确认移动」。";
break; break;
}
case SoloDecisionKinds.TargetGrids: case SoloDecisionKinds.TargetGrids:
{ {
var payload = decision.ReadPayload<TargetGridsPayload>(); var payload = decision.ReadPayload<TargetGridsPayload>();
_gridOverlay.SetAttackCells(payload?.GridIds ?? []); _gridOverlay.SetAttackCells(payload?.GridIds ?? []);
_confirmGridButton.Text = "确认范围";
_contextCancelButton.Text = "取消选择";
_contextLabel.Text = payload is null _contextLabel.Text = payload is null
? "选择技能中心格,然后确认。" ? "选择技能中心格,然后确认范围。"
: $"{payload.SkillName} · 选择中心格({ShapeLabel(payload.ShapeRangeType)},半径 {payload.ShapeRadius})。"; : $"{payload.SkillName} · 点击橙色高亮格选中心({ShapeLabel(payload.ShapeRangeType)},半径 {payload.ShapeRadius}),再点「确认范围」。";
break; break;
} }
@@ -425,6 +545,12 @@ public partial class BattleScreen : Node
} }
} }
if (cancelledReason is not null)
{
_contextLabel.Text = cancelledReason;
GD.PushWarning(cancelledReason);
}
ReconcileUnits(_store.Snapshot); ReconcileUnits(_store.Snapshot);
} }
@@ -437,37 +563,85 @@ public partial class BattleScreen : Node
_dialogDecisionKind = _store.PendingDecision?.Kind; _dialogDecisionKind = _store.PendingDecision?.Kind;
_decisionTitle.Text = title; _decisionTitle.Text = title;
_decisionInfo.Text = info; _decisionInfo.Text = info;
_decisionOptions.Clear();
_dialogValues.Clear(); _dialogValues.Clear();
_dialogAvailable.Clear(); _dialogAvailable.Clear();
_dialogDetails.Clear(); _dialogDetails.Clear();
ResetDecisionInputs(); List<string> labels = [];
foreach (var option in options) foreach (var option in options)
{ {
_decisionOptions.AddItem(option.Label); labels.Add(option.Label);
_dialogValues.Add(option.Value); _dialogValues.Add(option.Value);
_dialogAvailable.Add(option.Available); _dialogAvailable.Add(option.Available);
_dialogDetails.Add(option.Details); _dialogDetails.Add(option.Details);
} }
_decisionOptions.Clear();
ResetDecisionInputs();
// 选项多时直接用可点击列表:下拉框一次只显示一项,10 个候选看起来「根本没有能点的地方」。
_dialogUsesList = _dialogValues.Count > OptionButtonThreshold;
_dialogMultiSelect = false;
if (_dialogValues.Count == 0) if (_dialogValues.Count == 0)
{ {
_decisionOptions.AddItem("没有可用选项"); _decisionOptions.AddItem("没有可用选项");
_decisionOptions.Disabled = true; _decisionOptions.Disabled = true;
} }
else if (_dialogUsesList)
{
_decisionOptions.Visible = false;
_decisionChoiceList.Visible = true;
_decisionChoiceList.SelectMode = ItemList.SelectModeEnum.Single;
foreach (var label in labels)
{
_decisionChoiceList.AddItem(label);
}
_decisionChoiceList.Select(0);
ApplyDialogOption(0);
}
else else
{ {
_decisionOptions.Disabled = false; _decisionOptions.Disabled = false;
foreach (var label in labels)
{
_decisionOptions.AddItem(label);
}
_decisionOptions.Select(0); _decisionOptions.Select(0);
ApplyDialogOption(0); ApplyDialogOption(0);
} }
_decisionCancel.Disabled = !canCancel; _decisionCancel.Disabled = !canCancel;
_decisionConfirm.Text = _dialogDecisionKind == SoloDecisionKinds.Continue ? "继续" : "确认"; _decisionConfirm.Text = _dialogDecisionKind switch
{
SoloDecisionKinds.SelectCharacter => "进入战场",
SoloDecisionKinds.Skill => "选择技能",
SoloDecisionKinds.Item => "使用物品",
SoloDecisionKinds.Continue => "继续",
_ => "确认"
};
_decisionConfirm.Disabled = _dialogValues.Count == 0 _decisionConfirm.Disabled = _dialogValues.Count == 0
|| (_dialogAvailable.Count > 0 && !_dialogAvailable[0]); || (_dialogAvailable.Count > 0 && !_dialogAvailable[0]);
_decisionDialog.Visible = true; _decisionDialog.Visible = true;
// 上一次的长文本可能把滚动条留在底部;新决策要从头看起。
_decisionInfoScroll.ScrollVertical = 0;
// 键盘/手柄焦点:有多选项时先落在选择框上(否则一个误按的回车就把「10 选 1」
// 里的第一项定下来了);只有单选类弹窗才直接把焦点给确认键。
var interactive = _decisionChoiceList.Visible ? (Control)_decisionChoiceList
: _decisionOptions.Visible ? _decisionOptions
: _decisionTextInput.Visible ? _decisionTextInput
: _decisionNumberInput.Visible ? _decisionNumberInput
: _decisionConfirm;
if (interactive is OptionButton { ItemCount: > 1 } or ItemList)
{
interactive.GrabFocus();
}
else
{
_decisionConfirm.GrabFocus();
}
} }
private void ResetDecisionInputs() private void ResetDecisionInputs()
@@ -486,6 +660,17 @@ public partial class BattleScreen : Node
ApplyDialogOption((int)index); ApplyDialogOption((int)index);
} }
/// <summary>列表式选择(选项 &gt; <see cref="OptionButtonThreshold"/> 时):单选,选中即在右侧/下方显示详情。</summary>
private void OnDialogListSelected(long index)
{
if (_dialogMultiSelect)
{
return;
}
ApplyDialogOption((int)index);
}
private void ApplyDialogOption(int index) private void ApplyDialogOption(int index)
{ {
if (index < 0 || index >= _dialogValues.Count) if (index < 0 || index >= _dialogValues.Count)
@@ -510,6 +695,8 @@ public partial class BattleScreen : Node
} }
_dialogDecisionKind = SoloDecisionKinds.Inquiry; _dialogDecisionKind = SoloDecisionKinds.Inquiry;
_dialogUsesList = true;
_dialogMultiSelect = true;
_decisionTitle.Text = string.IsNullOrWhiteSpace(payload.Topic) ? "询问" : payload.Topic; _decisionTitle.Text = string.IsNullOrWhiteSpace(payload.Topic) ? "询问" : payload.Topic;
_decisionInfo.Text = payload.Description; _decisionInfo.Text = payload.Description;
_dialogValues.Clear(); _dialogValues.Clear();
@@ -540,6 +727,7 @@ public partial class BattleScreen : Node
default: default:
_decisionChoiceList.Visible = true; _decisionChoiceList.Visible = true;
_decisionChoiceList.SelectMode = ItemList.SelectModeEnum.Multi;
foreach (var choice in payload.Choices) foreach (var choice in payload.Choices)
{ {
_decisionChoiceList.AddItem($"{choice.Key} · {choice.Text}"); _decisionChoiceList.AddItem($"{choice.Key} · {choice.Text}");
@@ -602,12 +790,22 @@ public partial class BattleScreen : Node
} }
else else
{ {
if (_dialogValues.Count == 0 || _decisionOptions.Selected < 0) if (_dialogValues.Count == 0)
{ {
return; return;
} }
var value = _dialogValues[_decisionOptions.Selected]; // 注意:不能再用 `_decisionOptions.Selected` 当守卫 —— 走列表路径时那个下拉框已经被清空并隐藏,
// Selected 恒为 -1,会导致「点了确认却什么都没发生」。选中项一律从当前生效的控件里读。
var selectedIndex = _dialogUsesList
? (_decisionChoiceList.GetSelectedItems() is { Length: > 0 } picked ? (int)picked[0] : -1)
: _decisionOptions.Selected;
if (selectedIndex < 0 || selectedIndex >= _dialogValues.Count)
{
return;
}
var value = _dialogValues[selectedIndex];
payload = _dialogDecisionKind switch payload = _dialogDecisionKind switch
{ {
SoloDecisionKinds.SelectCharacter => new { characterGuid = value }, SoloDecisionKinds.SelectCharacter => new { characterGuid = value },
@@ -619,11 +817,19 @@ public partial class BattleScreen : Node
try try
{ {
// 技能 / 物品的选择也走「服务器可达才继续」的链路,作废时同样回到 ActionType。
_submittedAction = _dialogDecisionKind switch
{
SoloDecisionKinds.Skill => "CastSkill",
SoloDecisionKinds.Item => "UseItem",
_ => null
};
_decisionDialog.Visible = false; _decisionDialog.Visible = false;
await _store.SubmitDecisionAsync(payload); await _store.SubmitDecisionAsync(payload);
} }
catch (Exception exception) catch (Exception exception)
{ {
_submittedAction = null;
ShowError(exception.Message); ShowError(exception.Message);
} }
} }
@@ -682,7 +888,9 @@ public partial class BattleScreen : Node
} }
} }
_confirmGridButton.Disabled = false; _confirmGridButton.Disabled = false;
_contextLabel.Text = $"已选择逻辑格 ({cell.X}, {cell.Y}) / ID {grid.Id}"; _contextLabel.Text = decision.Kind == SoloDecisionKinds.TargetGrid
? $"已选移动目的地 ({cell.X}, {cell.Y}) · 点击「确认移动」提交。"
: $"已选技能中心 ({cell.X}, {cell.Y}) · 点击「确认范围」提交。";
} }
private async void OnConfirmGridPressed() private async void OnConfirmGridPressed()
@@ -693,16 +901,21 @@ public partial class BattleScreen : Node
} }
object payload; object payload;
string? submittedAction;
if (_store.PendingDecision.Kind == SoloDecisionKinds.Targets if (_store.PendingDecision.Kind == SoloDecisionKinds.Targets
&& _selectedTargetGuids.Count > 0) && _selectedTargetGuids.Count > 0)
{ {
payload = new { targetGuids = _selectedTargetGuids.ToArray() }; payload = new { targetGuids = _selectedTargetGuids.ToArray() };
// 目标提交后正常也可能回到 ActionType,不能仅靠下一种决策断言行动被取消。
submittedAction = null;
} }
else if (_selectedGridId is not null) else if (_selectedGridId is not null)
{ {
payload = _store.PendingDecision.Kind == SoloDecisionKinds.TargetGrid var isMove = _store.PendingDecision.Kind == SoloDecisionKinds.TargetGrid;
payload = isMove
? new { gridId = _selectedGridId.Value } ? new { gridId = _selectedGridId.Value }
: new { gridIds = new[] { _selectedGridId.Value } }; : new { gridIds = new[] { _selectedGridId.Value } };
submittedAction = null;
} }
else else
{ {
@@ -711,6 +924,10 @@ public partial class BattleScreen : Node
try try
{ {
_confirmGridButton.Disabled = true;
_confirmGridButton.Text = "提交中…";
_contextLabel.Text = "正在向服务器提交所选目标……";
_submittedAction = submittedAction;
await _store.SubmitDecisionAsync(payload); await _store.SubmitDecisionAsync(payload);
_selectedGridId = null; _selectedGridId = null;
_selectedTargetGuids.Clear(); _selectedTargetGuids.Clear();
@@ -720,6 +937,16 @@ public partial class BattleScreen : Node
} }
catch (Exception exception) catch (Exception exception)
{ {
_submittedAction = null;
_confirmGridButton.Disabled = _selectedGridId is null && _selectedTargetGuids.Count == 0;
_confirmGridButton.Text = _store.PendingDecision?.Kind switch
{
SoloDecisionKinds.TargetGrid => "确认移动",
SoloDecisionKinds.TargetGrids => "确认范围",
SoloDecisionKinds.Targets when _store.PendingDecision.ReadPayload<TargetsPayload>()?.SelectAll == true => "确认全体",
SoloDecisionKinds.Targets => "确认目标",
_ => "确认"
};
ShowError(exception.Message); ShowError(exception.Message);
} }
} }
@@ -758,10 +985,16 @@ public partial class BattleScreen : Node
{ {
var kind = _store.PendingDecision?.Kind; var kind = _store.PendingDecision?.Kind;
var choosingAction = kind == SoloDecisionKinds.ActionType; var choosingAction = kind == SoloDecisionKinds.ActionType;
var dp = _store.PendingDecision?.ReadPayload<ActionTypePayload>()?.Dp var actionPayload = choosingAction
?? _store.Snapshot?.PlayerDp; ? _store.PendingDecision?.ReadPayload<ActionTypePayload>()
: null;
var dp = actionPayload?.Dp ?? _store.Snapshot?.PlayerDp;
// 权威服务器原则:普通攻击是否可达由服务端的 attackTargets(严格 ATR 口径)决定,
// 为空就禁用按钮,不再让玩家白提交一轮、也不再把决策次数浪费在服务端的防打转护栏上。
var attackReachable = DecisionUiRules.IsNormalAttackReachable(actionPayload);
_moveButton.Disabled = !choosingAction; _moveButton.Disabled = !choosingAction;
_attackButton.Disabled = !choosingAction _attackButton.Disabled = !choosingAction
|| attackReachable == false
|| !DecisionUiRules.IsActionAvailable(dp, "NormalAttack"); || !DecisionUiRules.IsActionAvailable(dp, "NormalAttack");
_skillButton.Disabled = !choosingAction _skillButton.Disabled = !choosingAction
|| !DecisionUiRules.IsActionAvailable(dp, "CastSkill", "PreCastSkill"); || !DecisionUiRules.IsActionAvailable(dp, "CastSkill", "PreCastSkill");
@@ -769,7 +1002,9 @@ public partial class BattleScreen : Node
|| !DecisionUiRules.IsActionAvailable(dp, "CastSuperSkill"); || !DecisionUiRules.IsActionAvailable(dp, "CastSuperSkill");
_itemButton.Disabled = !choosingAction _itemButton.Disabled = !choosingAction
|| !DecisionUiRules.IsActionAvailable(dp, "UseItem"); || !DecisionUiRules.IsActionAvailable(dp, "UseItem");
_attackButton.Text = DecisionUiRules.QuotaLabel("普通攻击", dp, "NormalAttack"); _attackButton.Text = attackReachable == false
? "普通攻击\n暂无目标"
: DecisionUiRules.QuotaLabel("普通攻击", dp, "NormalAttack");
_skillButton.Text = DecisionUiRules.QuotaLabel("战技 / 魔法", dp, "CastSkill", "PreCastSkill"); _skillButton.Text = DecisionUiRules.QuotaLabel("战技 / 魔法", dp, "CastSkill", "PreCastSkill");
_superSkillButton.Text = DecisionUiRules.QuotaLabel("爆发技", dp, "CastSuperSkill"); _superSkillButton.Text = DecisionUiRules.QuotaLabel("爆发技", dp, "CastSuperSkill");
_itemButton.Text = DecisionUiRules.QuotaLabel("物品", dp, "UseItem"); _itemButton.Text = DecisionUiRules.QuotaLabel("物品", dp, "UseItem");
@@ -783,6 +1018,7 @@ public partial class BattleScreen : Node
private void OnSessionStateChanged(int state) private void OnSessionStateChanged(int state)
{ {
UpdateConnectionUi(); UpdateConnectionUi();
UpdateReconnectOverlay();
} }
private void UpdateConnectionUi() private void UpdateConnectionUi()
@@ -791,27 +1027,51 @@ public partial class BattleScreen : Node
{ {
SessionState.Connected => "● 已连接 /ws/solo", SessionState.Connected => "● 已连接 /ws/solo",
SessionState.Connecting => "● 正在连接……", SessionState.Connecting => "● 正在连接……",
SessionState.Reconnecting => "● 正在重连……", SessionState.Reconnecting => $"● 正在重连……(第 {Math.Max(1, _session.ReconnectAttempt)} 次)",
SessionState.Faulted => "● 连接错误", SessionState.Faulted => "● 连接错误",
_ => "● 未连接" _ => "● 未连接"
}; };
_connectButton.Text = _session.State == SessionState.Connected ? "断开" : "连接"; _connectButton.Text = _session.State == SessionState.Connected ? "断开" : "连接";
_startButton.Disabled = _session.State != SessionState.Connected || _store.IsStarted; _startButton.Disabled = _session.State != SessionState.Connected || _store.IsStarted || _store.IsWaitingForStart;
_dropButton.Disabled = _session.State != SessionState.Connected;
_endpointEdit.Editable = _session.State != SessionState.Connected; _endpointEdit.Editable = _session.State != SessionState.Connected;
UpdateWelcomeUi();
} }
private void HideGrid() private void UpdateWelcomeUi()
{ {
_gridOverlay.ClearInteraction(); _welcomePanel.Visible = !_store.IsStarted
if (_store.PendingDecision is null) && _store.PendingDecision is null
&& !_resultScreen.Visible;
_welcomeConnectButton.Disabled = _session.State is SessionState.Connected
or SessionState.Connecting or SessionState.Reconnecting;
_welcomeStartButton.Disabled = _session.State != SessionState.Connected
|| _store.IsStarted || _store.IsWaitingForStart;
_welcomeStatus.Text = _session.State switch
{ {
_contextLabel.Text = "观察模式 · 等待服务器决策"; SessionState.Connected when _store.IsWaitingForStart => "正在等待角色选择……",
SessionState.Connected => "连接成功 · 点击「开始新局」",
SessionState.Connecting or SessionState.Reconnecting => "正在连接 Solo 服务器……",
SessionState.Faulted => "连接失败 · 请确认 Solo WebAPI 已启动",
_ => "① 连接服务器 → ② 开始新局 → ③ 选择角色"
};
RefreshHudVisibility();
} }
private void OnCenterMapPressed()
{
if (_store.Snapshot?.Map is not { } map)
{
ShowToast("进入战斗后可以居中查看地图。", isError: false);
return;
}
_battleCamera.FrameMap(map, GetViewport().GetVisibleRect().Size, _gridOverlay.CellSize);
} }
private void OnHoveredCellChanged(Vector2I cell) private void OnHoveredCellChanged(Vector2I cell)
{ {
if (cell.X >= 0 && _store.PendingDecision is null) if (cell.X >= 0 && _store.IsStarted && _store.PendingDecision is null)
{ {
_contextLabel.Text = $"逻辑格 ({cell.X}, {cell.Y})"; _contextLabel.Text = $"逻辑格 ({cell.X}, {cell.Y})";
} }
@@ -820,6 +1080,7 @@ public partial class BattleScreen : Node
private void ShowError(string message) private void ShowError(string message)
{ {
_contextLabel.Text = message; _contextLabel.Text = message;
ShowToast(message);
GD.PushWarning(message); GD.PushWarning(message);
UpdateConnectionUi(); UpdateConnectionUi();
} }
@@ -830,6 +1091,28 @@ public partial class BattleScreen : Node
? "对局结束。" ? "对局结束。"
: $"对局结束,胜者:{winnerName}"; : $"对局结束,胜者:{winnerName}";
_startButton.Disabled = _session.State != SessionState.Connected; _startButton.Disabled = _session.State != SessionState.Connected;
ShowResultScreen(winnerName);
UpdateWelcomeUi();
}
/// <summary>
/// 连接刚恢复(BattleStore 还没发 gaming.resume):上一个连接的本地中间状态全部作废,
/// 断线期间的表现也没有播放价值 —— 直接清空,等服务器补发的快照重建画面。
/// </summary>
private void OnSessionReconnected()
{
ClearLocalInteraction("重连");
_animator.SkipAll("重连");
}
private void OnConnectionRecovered()
{
ShowToast(
_store.IsStarted
? "连接已恢复,等待服务器补发快照与待处理决策。"
: "连接已恢复。",
isError: false);
RefreshLogDrawer();
} }
private void ReconcileUnits(SoloGameState? state) private void ReconcileUnits(SoloGameState? state)
@@ -898,11 +1181,34 @@ public partial class BattleScreen : Node
isFriendly, isFriendly,
character.Guid == state.CurrentActorGuid, character.Guid == state.CurrentActorGuid,
selectableTargets.Contains(character.Guid), selectableTargets.Contains(character.Guid),
worldPosition); worldPosition,
_animator.TakesOverPosition(character.Guid),
_animator.TakesOverHp(character.Guid));
unit.SetSelected(_selectedTargetGuids.Contains(character.Guid)); unit.SetSelected(_selectedTargetGuids.Contains(character.Guid));
} }
} }
private Vector2 AuthoritativePosition(SoloGameState state, string characterGuid)
{
var map = state.Map;
var character = state.Characters.FirstOrDefault(candidate => candidate.Guid == characterGuid);
var grid = character is null
? null
: map?.Grids.FirstOrDefault(candidate => candidate.Id == character.GridId)
?? map?.Grids.FirstOrDefault(candidate =>
candidate.Characters.Contains(characterGuid, StringComparer.Ordinal));
if (grid is null)
{
return _unitViews.TryGetValue(characterGuid, out var unit) ? unit.Position : Vector2.Zero;
}
return GridProjector.GridToScreen(
new Vector2I(grid.X, grid.Y),
_gridOverlay.CellSize.X,
_gridOverlay.CellSize.Y,
grid.Z);
}
private void OnUnitClicked(string characterGuid) private void OnUnitClicked(string characterGuid)
{ {
if (_store.PendingDecision?.Kind != SoloDecisionKinds.Targets) if (_store.PendingDecision?.Kind != SoloDecisionKinds.Targets)
@@ -911,6 +1217,10 @@ public partial class BattleScreen : Node
} }
var payload = _store.PendingDecision.ReadPayload<TargetsPayload>(); var payload = _store.PendingDecision.ReadPayload<TargetsPayload>();
if (payload?.SelectAll == true)
{
return;
}
var allowedTargets = payload?.Targets var allowedTargets = payload?.Targets
.Select(target => target.Guid) .Select(target => target.Guid)
.ToHashSet(StringComparer.Ordinal) ?? []; .ToHashSet(StringComparer.Ordinal) ?? [];
@@ -943,24 +1253,15 @@ public partial class BattleScreen : Node
{ {
pair.Value.SetSelected(_selectedTargetGuids.Contains(pair.Key)); pair.Value.SetSelected(_selectedTargetGuids.Contains(pair.Key));
} }
RefreshTargetChoiceStates();
var target = _store.Snapshot?.Characters.FirstOrDefault(character => character.Guid == characterGuid); var target = _store.Snapshot?.Characters.FirstOrDefault(character => character.Guid == characterGuid);
var max = Math.Max(1, payload?.MaxTargets ?? 1); var max = Math.Max(1, payload?.MaxTargets ?? 1);
_contextLabel.Text = target is null _contextLabel.Text = _selectedTargetGuids.Count == 0
? $"已选择 {_selectedTargetGuids.Count}/{max} 个目标。" ? "已取消目标选择 · 点击橙框单位重新选择,再按「确认目标」。"
: $"{target.DisplayName} · 已选择 {_selectedTargetGuids.Count}/{max},确认后提交服务器。"; : target is null
} ? $"已选 {_selectedTargetGuids.Count}/{max} 个目标 · 点击「确认目标」提交。"
: $"已选中「{target.DisplayName}」({_selectedTargetGuids.Count}/{max}) · 点击「确认目标」提交。";
private static string TargetSelectionHint(TargetsPayload? payload)
{
if (payload is null)
{
return "点击合法目标。";
}
return payload.SelectAll
? $"全体目标已默认选中({payload.Targets.Count} 个),确认后提交。"
: $"点击合法单位选择目标,最多 {Math.Max(1, payload.MaxTargets)} 个。";
} }
private static string ShapeLabel(string shape) private static string ShapeLabel(string shape)
+439 -53
View File
@@ -1,9 +1,10 @@
[gd_scene load_steps=5 format=3] [gd_scene load_steps=6 format=3]
[ext_resource type="Script" path="res://src/Screens/Battle/BattleScreen.cs" id="1_screen"] [ext_resource type="Script" path="res://src/Screens/Battle/BattleScreen.cs" id="1_screen"]
[ext_resource type="Script" path="res://src/World/GreyboxMap2D.cs" id="2_map"] [ext_resource type="Script" path="res://src/World/GreyboxMap2D.cs" id="2_map"]
[ext_resource type="Script" path="res://src/World/GridOverlay2D.cs" id="3_grid"] [ext_resource type="Script" path="res://src/World/GridOverlay2D.cs" id="3_grid"]
[ext_resource type="Script" path="res://src/World/BattleCameraController.cs" id="4_camera"] [ext_resource type="Script" path="res://src/World/BattleCameraController.cs" id="4_camera"]
[ext_resource type="Theme" path="res://src/Resources/SilverFantasyTheme.tres" id="5_theme"]
[node name="BattleScreen" type="Node"] [node name="BattleScreen" type="Node"]
script = ExtResource("1_screen") script = ExtResource("1_screen")
@@ -79,6 +80,8 @@ anchor_right = 1.0
anchor_bottom = 1.0 anchor_bottom = 1.0
grow_horizontal = 2 grow_horizontal = 2
grow_vertical = 2 grow_vertical = 2
mouse_filter = 2
theme = ExtResource("5_theme")
theme_override_constants/margin_left = 20 theme_override_constants/margin_left = 20
theme_override_constants/margin_top = 20 theme_override_constants/margin_top = 20
theme_override_constants/margin_right = 20 theme_override_constants/margin_right = 20
@@ -86,6 +89,7 @@ theme_override_constants/margin_bottom = 20
[node name="Layout" type="Control" parent="HudLayer/SafeArea"] [node name="Layout" type="Control" parent="HudLayer/SafeArea"]
layout_mode = 2 layout_mode = 2
mouse_filter = 2
[node name="TopLeftMissionPanel" type="PanelContainer" parent="HudLayer/SafeArea/Layout"] [node name="TopLeftMissionPanel" type="PanelContainer" parent="HudLayer/SafeArea/Layout"]
layout_mode = 1 layout_mode = 1
@@ -93,7 +97,7 @@ anchors_preset = 0
anchor_left = 0.01 anchor_left = 0.01
anchor_top = 0.01 anchor_top = 0.01
anchor_right = 0.27 anchor_right = 0.27
anchor_bottom = 0.17 anchor_bottom = 0.245
grow_horizontal = 2 grow_horizontal = 2
grow_vertical = 2 grow_vertical = 2
@@ -103,7 +107,7 @@ theme_override_constants/separation = 8
[node name="Title" type="Label" parent="HudLayer/SafeArea/Layout/TopLeftMissionPanel/MissionInfo"] [node name="Title" type="Label" parent="HudLayer/SafeArea/Layout/TopLeftMissionPanel/MissionInfo"]
layout_mode = 2 layout_mode = 2
text = "灰盒战斗竖切" text = "筽祀牻 · 银辉战场"
theme_override_font_sizes/font_size = 24 theme_override_font_sizes/font_size = 24
[node name="Round" type="Label" parent="HudLayer/SafeArea/Layout/TopLeftMissionPanel/MissionInfo"] [node name="Round" type="Label" parent="HudLayer/SafeArea/Layout/TopLeftMissionPanel/MissionInfo"]
@@ -112,44 +116,45 @@ text = "Round 1 · 等待权威快照"
[node name="Objective" type="Label" parent="HudLayer/SafeArea/Layout/TopLeftMissionPanel/MissionInfo"] [node name="Objective" type="Label" parent="HudLayer/SafeArea/Layout/TopLeftMissionPanel/MissionInfo"]
layout_mode = 2 layout_mode = 2
text = "目标:验证 16 × 12 二等角逻辑格" text = "连接服务器,开启一场 Solo 战斗"
[node name="Reward" type="Label" parent="HudLayer/SafeArea/Layout/TopLeftMissionPanel/MissionInfo"]
layout_mode = 2
text = "本回合奖励:—"
clip_text = true
[node name="TopTurnQueue" type="PanelContainer" parent="HudLayer/SafeArea/Layout"] [node name="TopTurnQueue" type="PanelContainer" parent="HudLayer/SafeArea/Layout"]
layout_mode = 1 layout_mode = 1
anchor_left = 0.32 anchor_left = 0.32
anchor_top = 0.01 anchor_top = 0.01
anchor_right = 0.68 anchor_right = 0.68
anchor_bottom = 0.09 anchor_bottom = 0.235
grow_horizontal = 2 grow_horizontal = 2
grow_vertical = 2 grow_vertical = 2
[node name="QueueRow" type="HBoxContainer" parent="HudLayer/SafeArea/Layout/TopTurnQueue"] [node name="QueueContent" type="VBoxContainer" parent="HudLayer/SafeArea/Layout/TopTurnQueue"]
layout_mode = 2 layout_mode = 2
alignment = 1 theme_override_constants/separation = 4
theme_override_constants/separation = 24
[node name="QueueTitle" type="Label" parent="HudLayer/SafeArea/Layout/TopTurnQueue/QueueRow"] [node name="QueueTitle" type="Label" parent="HudLayer/SafeArea/Layout/TopTurnQueue/QueueContent"]
layout_mode = 2 layout_mode = 2
text = "行动顺序" text = "行动顺序"
[node name="Actor1" type="Label" parent="HudLayer/SafeArea/Layout/TopTurnQueue/QueueRow"] [node name="QueueScroll" type="ScrollContainer" parent="HudLayer/SafeArea/Layout/TopTurnQueue/QueueContent"]
layout_mode = 2 layout_mode = 2
text = "01 心音" size_flags_vertical = 3
vertical_scroll_mode = 3
[node name="Arrow1" type="Label" parent="HudLayer/SafeArea/Layout/TopTurnQueue/QueueRow"] [node name="QueueCards" type="HBoxContainer" parent="HudLayer/SafeArea/Layout/TopTurnQueue/QueueContent/QueueScroll"]
layout_mode = 2 layout_mode = 2
text = "→" theme_override_constants/separation = 6
[node name="Actor2" type="Label" parent="HudLayer/SafeArea/Layout/TopTurnQueue/QueueRow"]
layout_mode = 2
text = "02 敌方"
[node name="ConnectionPanel" type="PanelContainer" parent="HudLayer/SafeArea/Layout"] [node name="ConnectionPanel" type="PanelContainer" parent="HudLayer/SafeArea/Layout"]
layout_mode = 1 layout_mode = 1
anchor_left = 0.70 anchor_left = 0.70
anchor_top = 0.01 anchor_top = 0.01
anchor_right = 0.99 anchor_right = 0.99
anchor_bottom = 0.18 anchor_bottom = 0.22
grow_horizontal = 2 grow_horizontal = 2
grow_vertical = 2 grow_vertical = 2
@@ -159,7 +164,7 @@ theme_override_constants/separation = 6
[node name="EndpointEdit" type="LineEdit" parent="HudLayer/SafeArea/Layout/ConnectionPanel/ConnectionContent"] [node name="EndpointEdit" type="LineEdit" parent="HudLayer/SafeArea/Layout/ConnectionPanel/ConnectionContent"]
layout_mode = 2 layout_mode = 2
text = "ws://localhost:11030/ws/solo" text = "ws://localhost:12030/ws/solo"
placeholder_text = "Solo WebSocket 地址" placeholder_text = "Solo WebSocket 地址"
[node name="ConnectionStatus" type="Label" parent="HudLayer/SafeArea/Layout/ConnectionPanel/ConnectionContent"] [node name="ConnectionStatus" type="Label" parent="HudLayer/SafeArea/Layout/ConnectionPanel/ConnectionContent"]
@@ -183,12 +188,81 @@ layout_mode = 2
disabled = true disabled = true
text = "开始新局" text = "开始新局"
[node name="DropButton" type="Button" parent="HudLayer/SafeArea/Layout/ConnectionPanel/ConnectionContent/ConnectionButtons"]
visible = false
custom_minimum_size = Vector2(120, 42)
layout_mode = 2
disabled = true
tooltip_text = "不发送关闭握手,直接中断 socket,用于验证断线恢复"
text = "强制断线"
[node name="ConnectionToggleButton" type="Button" parent="HudLayer/SafeArea/Layout"]
visible = false
layout_mode = 1
anchor_left = 0.79
anchor_top = 0.01
anchor_right = 0.99
anchor_bottom = 0.075
grow_horizontal = 2
grow_vertical = 2
text = "● 服务器"
tooltip_text = "展开或收起服务器连接设置"
[node name="WelcomePanel" type="PanelContainer" parent="HudLayer/SafeArea/Layout"]
layout_mode = 1
anchor_left = 0.32
anchor_top = 0.32
anchor_right = 0.68
anchor_bottom = 0.65
grow_horizontal = 2
grow_vertical = 2
[node name="WelcomeContent" type="VBoxContainer" parent="HudLayer/SafeArea/Layout/WelcomePanel"]
layout_mode = 2
alignment = 1
theme_override_constants/separation = 12
[node name="WelcomeTitle" type="Label" parent="HudLayer/SafeArea/Layout/WelcomePanel/WelcomeContent"]
layout_mode = 2
text = "踏入银辉战场"
horizontal_alignment = 1
theme_override_colors/font_color = Color(0.172549, 0.376471, 0.521569, 1)
theme_override_font_sizes/font_size = 28
[node name="WelcomeDescription" type="Label" parent="HudLayer/SafeArea/Layout/WelcomePanel/WelcomeContent"]
layout_mode = 2
text = "连接服务器、选择角色,踏上战场。"
horizontal_alignment = 1
autowrap_mode = 2
[node name="WelcomeStatus" type="Label" parent="HudLayer/SafeArea/Layout/WelcomePanel/WelcomeContent"]
layout_mode = 2
text = "① 连接服务器 → ② 开始新局 → ③ 选择角色"
horizontal_alignment = 1
theme_override_colors/font_color = Color(0.376471, 0.47451, 0.596078, 1)
[node name="WelcomeButtons" type="HBoxContainer" parent="HudLayer/SafeArea/Layout/WelcomePanel/WelcomeContent"]
layout_mode = 2
alignment = 1
theme_override_constants/separation = 12
[node name="WelcomeConnectButton" type="Button" parent="HudLayer/SafeArea/Layout/WelcomePanel/WelcomeContent/WelcomeButtons"]
custom_minimum_size = Vector2(170, 50)
layout_mode = 2
text = "连接服务器"
[node name="WelcomeStartButton" type="Button" parent="HudLayer/SafeArea/Layout/WelcomePanel/WelcomeContent/WelcomeButtons"]
custom_minimum_size = Vector2(170, 50)
layout_mode = 2
disabled = true
text = "开始新局"
[node name="BottomLeftCharacterPanel" type="PanelContainer" parent="HudLayer/SafeArea/Layout"] [node name="BottomLeftCharacterPanel" type="PanelContainer" parent="HudLayer/SafeArea/Layout"]
layout_mode = 1 layout_mode = 1
anchor_left = 0.01 anchor_left = 0.01
anchor_top = 0.76 anchor_top = 0.66
anchor_right = 0.30 anchor_right = 0.30
anchor_bottom = 0.99 anchor_bottom = 0.865
grow_horizontal = 2 grow_horizontal = 2
grow_vertical = 2 grow_vertical = 2
@@ -198,32 +272,35 @@ theme_override_constants/separation = 7
[node name="Name" type="Label" parent="HudLayer/SafeArea/Layout/BottomLeftCharacterPanel/CharacterInfo"] [node name="Name" type="Label" parent="HudLayer/SafeArea/Layout/BottomLeftCharacterPanel/CharacterInfo"]
layout_mode = 2 layout_mode = 2
text = "汐月心音 Lv. 1" text = "等待角色加入"
clip_text = true
text_overrun_behavior = 3
theme_override_font_sizes/font_size = 24 theme_override_font_sizes/font_size = 24
[node name="Hp" type="Label" parent="HudLayer/SafeArea/Layout/BottomLeftCharacterPanel/CharacterInfo"] [node name="Hp" type="Label" parent="HudLayer/SafeArea/Layout/BottomLeftCharacterPanel/CharacterInfo"]
layout_mode = 2 layout_mode = 2
text = "HP 100 / 100" text = "HP —"
[node name="Mp" type="Label" parent="HudLayer/SafeArea/Layout/BottomLeftCharacterPanel/CharacterInfo"] [node name="Mp" type="Label" parent="HudLayer/SafeArea/Layout/BottomLeftCharacterPanel/CharacterInfo"]
layout_mode = 2 layout_mode = 2
text = "MP 80 / 80 EP 0 / 200" text = "MP — EP —"
[node name="Dp" type="Label" parent="HudLayer/SafeArea/Layout/BottomLeftCharacterPanel/CharacterInfo"] [node name="Dp" type="Label" parent="HudLayer/SafeArea/Layout/BottomLeftCharacterPanel/CharacterInfo"]
layout_mode = 2 layout_mode = 2
text = "决策点 ◆ ◆" text = "决策点 —"
[node name="Hint" type="Label" parent="HudLayer/SafeArea/Layout/BottomLeftCharacterPanel/CharacterInfo"] [node name="Hint" type="Label" parent="HudLayer/SafeArea/Layout/BottomLeftCharacterPanel/CharacterInfo"]
visible = false
layout_mode = 2 layout_mode = 2
text = "UI 数据将由 BattleStore 权威快照驱动" text = "UI 数据将由 BattleStore 权威快照驱动"
autowrap_mode = 2 autowrap_mode = 2
[node name="BottomRightActionDock" type="PanelContainer" parent="HudLayer/SafeArea/Layout"] [node name="BottomRightActionDock" type="PanelContainer" parent="HudLayer/SafeArea/Layout"]
layout_mode = 1 layout_mode = 1
anchor_left = 0.69 anchor_left = 0.68
anchor_top = 0.76 anchor_top = 0.50
anchor_right = 0.99 anchor_right = 0.99
anchor_bottom = 0.99 anchor_bottom = 0.865
grow_horizontal = 2 grow_horizontal = 2
grow_vertical = 2 grow_vertical = 2
@@ -265,83 +342,148 @@ layout_mode = 2
disabled = true disabled = true
text = "物品" text = "物品"
[node name="HideGridButton" type="Button" parent="HudLayer/SafeArea/Layout/BottomRightActionDock/ActionGrid"]
custom_minimum_size = Vector2(150, 62)
layout_mode = 2
text = "隐藏网格"
[node name="EndTurnButton" type="Button" parent="HudLayer/SafeArea/Layout/BottomRightActionDock/ActionGrid"] [node name="EndTurnButton" type="Button" parent="HudLayer/SafeArea/Layout/BottomRightActionDock/ActionGrid"]
custom_minimum_size = Vector2(150, 62) custom_minimum_size = Vector2(150, 62)
layout_mode = 2 layout_mode = 2
disabled = true disabled = true
text = "结束行动" text = "结束行动"
tooltip_text = "接入服务器请求后启用" tooltip_text = "结束本回合的行动"
[node name="TargetPicker" type="VBoxContainer" parent="HudLayer/SafeArea/Layout/BottomRightActionDock"]
visible = false
layout_mode = 2
theme_override_constants/separation = 8
[node name="TargetTitle" type="Label" parent="HudLayer/SafeArea/Layout/BottomRightActionDock/TargetPicker"]
layout_mode = 2
text = "选择目标"
theme_override_font_sizes/font_size = 20
[node name="TargetHelp" type="Label" parent="HudLayer/SafeArea/Layout/BottomRightActionDock/TargetPicker"]
layout_mode = 2
text = "点击棋子或下方列表,再按确认目标"
autowrap_mode = 2
[node name="TargetScroll" type="ScrollContainer" parent="HudLayer/SafeArea/Layout/BottomRightActionDock/TargetPicker"]
layout_mode = 2
size_flags_vertical = 3
horizontal_scroll_mode = 3
[node name="TargetChoices" type="VBoxContainer" parent="HudLayer/SafeArea/Layout/BottomRightActionDock/TargetPicker/TargetScroll"]
layout_mode = 2
size_flags_horizontal = 3
theme_override_constants/separation = 6
[node name="BattleUtilityPanel" type="PanelContainer" parent="HudLayer/SafeArea/Layout"]
visible = false
layout_mode = 1
anchor_left = 0.73
anchor_top = 0.30
anchor_right = 0.99
anchor_bottom = 0.405
grow_horizontal = 2
grow_vertical = 2
[node name="UtilityRow" type="HBoxContainer" parent="HudLayer/SafeArea/Layout/BattleUtilityPanel"]
layout_mode = 2
theme_override_constants/separation = 8
[node name="HideGridButton" type="Button" parent="HudLayer/SafeArea/Layout/BattleUtilityPanel/UtilityRow"]
layout_mode = 2
size_flags_horizontal = 3
text = "镜头居中"
tooltip_text = "滚轮缩放 · WASD/方向键移动 · 中键拖动画面 · 点击重置视角"
[node name="LogButton" type="Button" parent="HudLayer/SafeArea/Layout/BattleUtilityPanel/UtilityRow"]
layout_mode = 2
size_flags_horizontal = 3
text = "战斗日志"
tooltip_text = "查看服务器下发的战斗日志"
[node name="BottomContextBar" type="PanelContainer" parent="HudLayer/SafeArea/Layout"] [node name="BottomContextBar" type="PanelContainer" parent="HudLayer/SafeArea/Layout"]
layout_mode = 1 layout_mode = 1
anchor_left = 0.32 anchor_left = 0.01
anchor_top = 0.89 anchor_top = 0.88
anchor_right = 0.68 anchor_right = 0.99
anchor_bottom = 0.99 anchor_bottom = 0.99
grow_horizontal = 2 grow_horizontal = 2
grow_vertical = 2 grow_vertical = 2
[node name="ContextRow" type="HBoxContainer" parent="HudLayer/SafeArea/Layout/BottomContextBar"] [node name="ContextRow" type="HBoxContainer" parent="HudLayer/SafeArea/Layout/BottomContextBar"]
layout_mode = 2 layout_mode = 2
alignment = 1 theme_override_constants/separation = 12
theme_override_constants/separation = 18
[node name="ContextLabel" type="Label" parent="HudLayer/SafeArea/Layout/BottomContextBar/ContextRow"] [node name="ContextLabel" type="Label" parent="HudLayer/SafeArea/Layout/BottomContextBar/ContextRow"]
layout_mode = 2 layout_mode = 2
size_flags_horizontal = 3 size_flags_horizontal = 3
text = "移动预览 · 选择目标格后确认" text = "等待连接 · 点击中央的「连接服务器」开始"
autowrap_mode = 2
[node name="TimeoutLabel" type="Label" parent="HudLayer/SafeArea/Layout/BottomContextBar/ContextRow"] [node name="TimeoutLabel" type="Label" parent="HudLayer/SafeArea/Layout/BottomContextBar/ContextRow"]
custom_minimum_size = Vector2(72, 0) custom_minimum_size = Vector2(72, 0)
layout_mode = 2 layout_mode = 2
text = "" text = ""
horizontal_alignment = 2 horizontal_alignment = 2
vertical_alignment = 1
[node name="CancelButton" type="Button" parent="HudLayer/SafeArea/Layout/BottomContextBar/ContextRow"] [node name="CancelButton" type="Button" parent="HudLayer/SafeArea/Layout/BottomContextBar/ContextRow"]
custom_minimum_size = Vector2(112, 44)
layout_mode = 2 layout_mode = 2
text = "取消" text = "取消"
[node name="ConfirmButton" type="Button" parent="HudLayer/SafeArea/Layout/BottomContextBar/ContextRow"] [node name="ConfirmButton" type="Button" parent="HudLayer/SafeArea/Layout/BottomContextBar/ContextRow"]
custom_minimum_size = Vector2(128, 44)
layout_mode = 2 layout_mode = 2
disabled = true disabled = true
text = "确认" text = "确认"
[node name="SkipAnimationButton" type="Button" parent="HudLayer/SafeArea/Layout/BottomContextBar/ContextRow"]
visible = false
layout_mode = 2
tooltip_text = "立即跳到最新权威快照"
text = "跳过表现"
[node name="OverlayLayer" type="CanvasLayer" parent="."] [node name="OverlayLayer" type="CanvasLayer" parent="."]
layer = 20 layer = 20
[node name="DecisionDialog" type="CenterContainer" parent="OverlayLayer"] [node name="DecisionDialog" type="Control" parent="OverlayLayer"]
visible = false visible = false
anchors_preset = 15 anchors_preset = 15
anchor_right = 1.0 anchor_right = 1.0
anchor_bottom = 1.0 anchor_bottom = 1.0
grow_horizontal = 2 grow_horizontal = 2
grow_vertical = 2 grow_vertical = 2
mouse_filter = 1 mouse_filter = 0
theme = ExtResource("5_theme")
[node name="DialogDim" type="ColorRect" parent="OverlayLayer/DecisionDialog"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 0
color = Color(0.043137, 0.078431, 0.137255, 0.57)
[node name="DialogPanel" type="PanelContainer" parent="OverlayLayer/DecisionDialog"] [node name="DialogPanel" type="PanelContainer" parent="OverlayLayer/DecisionDialog"]
custom_minimum_size = Vector2(680, 320) layout_mode = 1
layout_mode = 2 anchor_left = 0.16
anchor_top = 0.08
anchor_right = 0.84
anchor_bottom = 0.92
grow_horizontal = 2
grow_vertical = 2
[node name="DialogContent" type="VBoxContainer" parent="OverlayLayer/DecisionDialog/DialogPanel"] [node name="DialogContent" type="VBoxContainer" parent="OverlayLayer/DecisionDialog/DialogPanel"]
layout_mode = 2 layout_mode = 2
theme_override_constants/separation = 16 theme_override_constants/separation = 12
[node name="Title" type="Label" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent"] [node name="Title" type="Label" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent"]
layout_mode = 2 layout_mode = 2
text = "服务器决策" text = "服务器决策"
horizontal_alignment = 1 horizontal_alignment = 1
theme_override_font_sizes/font_size = 28 theme_override_font_sizes/font_size = 24
[node name="Info" type="Label" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent"]
layout_mode = 2
text = "请选择一个选项。"
horizontal_alignment = 1
autowrap_mode = 2
[node name="Options" type="OptionButton" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent"] [node name="Options" type="OptionButton" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent"]
custom_minimum_size = Vector2(0, 56) custom_minimum_size = Vector2(0, 56)
@@ -349,10 +491,22 @@ layout_mode = 2
[node name="ChoiceList" type="ItemList" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent"] [node name="ChoiceList" type="ItemList" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent"]
visible = false visible = false
custom_minimum_size = Vector2(0, 130) custom_minimum_size = Vector2(0, 150)
layout_mode = 2 layout_mode = 2
size_flags_vertical = 3
select_mode = 1 select_mode = 1
[node name="InfoScroll" type="ScrollContainer" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent"]
layout_mode = 2
size_flags_vertical = 3
horizontal_scroll_mode = 0
[node name="Info" type="Label" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent/InfoScroll"]
layout_mode = 2
size_flags_horizontal = 3
text = "请选择一个选项。"
autowrap_mode = 2
[node name="TextInput" type="LineEdit" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent"] [node name="TextInput" type="LineEdit" parent="OverlayLayer/DecisionDialog/DialogPanel/DialogContent"]
visible = false visible = false
custom_minimum_size = Vector2(0, 48) custom_minimum_size = Vector2(0, 48)
@@ -389,6 +543,52 @@ visible = false
[node name="BattleLogDrawer" type="Control" parent="OverlayLayer"] [node name="BattleLogDrawer" type="Control" parent="OverlayLayer"]
visible = false visible = false
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 2
theme = ExtResource("5_theme")
[node name="LogPanel" type="PanelContainer" parent="OverlayLayer/BattleLogDrawer"]
layout_mode = 1
anchor_left = 0.55
anchor_top = 0.16
anchor_right = 0.845
anchor_bottom = 0.84
grow_horizontal = 2
grow_vertical = 2
[node name="LogContent" type="VBoxContainer" parent="OverlayLayer/BattleLogDrawer/LogPanel"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="LogHeader" type="HBoxContainer" parent="OverlayLayer/BattleLogDrawer/LogPanel/LogContent"]
layout_mode = 2
[node name="LogTitle" type="Label" parent="OverlayLayer/BattleLogDrawer/LogPanel/LogContent/LogHeader"]
layout_mode = 2
size_flags_horizontal = 3
text = "战斗日志"
[node name="LogCloseButton" type="Button" parent="OverlayLayer/BattleLogDrawer/LogPanel/LogContent/LogHeader"]
custom_minimum_size = Vector2(96, 40)
layout_mode = 2
text = "关闭"
[node name="LogScroll" type="ScrollContainer" parent="OverlayLayer/BattleLogDrawer/LogPanel/LogContent"]
layout_mode = 2
size_flags_vertical = 3
horizontal_scroll_mode = 0
scroll_following = true
[node name="LogText" type="RichTextLabel" parent="OverlayLayer/BattleLogDrawer/LogPanel/LogContent/LogScroll"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_vertical = 3
fit_content = true
scroll_active = false
[node name="InquiryDialog" type="Control" parent="OverlayLayer"] [node name="InquiryDialog" type="Control" parent="OverlayLayer"]
visible = false visible = false
@@ -396,8 +596,194 @@ visible = false
[node name="PauseDialog" type="Control" parent="OverlayLayer"] [node name="PauseDialog" type="Control" parent="OverlayLayer"]
visible = false visible = false
[node name="AiHostedBanner" type="Control" parent="OverlayLayer"]
visible = false
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 2
theme = ExtResource("5_theme")
[node name="BannerPanel" type="PanelContainer" parent="OverlayLayer/AiHostedBanner"]
layout_mode = 1
anchor_left = 0.355
anchor_top = 0.02
anchor_right = 0.645
anchor_bottom = 0.1
grow_horizontal = 2
grow_vertical = 2
[node name="BannerLabel" type="Label" parent="OverlayLayer/AiHostedBanner/BannerPanel"]
layout_mode = 2
text = "AI 托管中 · 本回合由服务器代打"
horizontal_alignment = 1
vertical_alignment = 1
autowrap_mode = 2
[node name="ErrorToast" type="Control" parent="OverlayLayer"]
visible = false
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 2
theme = ExtResource("5_theme")
[node name="ToastPanel" type="PanelContainer" parent="OverlayLayer/ErrorToast"]
layout_mode = 1
anchor_left = 0.26
anchor_top = 0.11
anchor_right = 0.74
anchor_bottom = 0.2
grow_horizontal = 2
grow_vertical = 2
[node name="ToastLabel" type="Label" parent="OverlayLayer/ErrorToast/ToastPanel"]
layout_mode = 2
text = ""
horizontal_alignment = 1
vertical_alignment = 1
autowrap_mode = 2
[node name="ReconnectOverlay" type="Control" parent="OverlayLayer"] [node name="ReconnectOverlay" type="Control" parent="OverlayLayer"]
visible = false visible = false
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 2
theme = ExtResource("5_theme")
[node name="ReconnectDim" type="ColorRect" parent="OverlayLayer/ReconnectOverlay"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
color = Color(0.02, 0.03, 0.05, 0.66)
mouse_filter = 0
[node name="ReconnectCenter" type="CenterContainer" parent="OverlayLayer/ReconnectOverlay"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 1
[node name="ReconnectCard" type="PanelContainer" parent="OverlayLayer/ReconnectOverlay/ReconnectCenter"]
custom_minimum_size = Vector2(620, 0)
layout_mode = 2
[node name="ReconnectContent" type="VBoxContainer" parent="OverlayLayer/ReconnectOverlay/ReconnectCenter/ReconnectCard"]
layout_mode = 2
theme_override_constants/separation = 16
[node name="ReconnectTitle" type="Label" parent="OverlayLayer/ReconnectOverlay/ReconnectCenter/ReconnectCard/ReconnectContent"]
layout_mode = 2
text = "连接已中断"
horizontal_alignment = 1
theme_override_font_sizes/font_size = 30
[node name="ReconnectDetail" type="Label" parent="OverlayLayer/ReconnectOverlay/ReconnectCenter/ReconnectCard/ReconnectContent"]
layout_mode = 2
text = "正在重连……"
horizontal_alignment = 1
autowrap_mode = 2
[node name="ReconnectHint" type="Label" parent="OverlayLayer/ReconnectOverlay/ReconnectCenter/ReconnectCard/ReconnectContent"]
layout_mode = 2
text = "服务器会继续推进对局并暂由 AI 托管你的角色;恢复后自动夺回控制权。"
horizontal_alignment = 1
autowrap_mode = 2
[node name="ReconnectButtons" type="HBoxContainer" parent="OverlayLayer/ReconnectOverlay/ReconnectCenter/ReconnectCard/ReconnectContent"]
layout_mode = 2
alignment = 1
theme_override_constants/separation = 18
[node name="ReconnectNowButton" type="Button" parent="OverlayLayer/ReconnectOverlay/ReconnectCenter/ReconnectCard/ReconnectContent/ReconnectButtons"]
custom_minimum_size = Vector2(180, 52)
layout_mode = 2
text = "立即重连"
[node name="ReconnectAbortButton" type="Button" parent="OverlayLayer/ReconnectOverlay/ReconnectCenter/ReconnectCard/ReconnectContent/ReconnectButtons"]
custom_minimum_size = Vector2(180, 52)
layout_mode = 2
text = "放弃并断开"
[node name="ResultScreen" type="Control" parent="OverlayLayer"] [node name="ResultScreen" type="Control" parent="OverlayLayer"]
visible = false visible = false
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 2
theme = ExtResource("5_theme")
[node name="ResultDim" type="ColorRect" parent="OverlayLayer/ResultScreen"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
color = Color(0.02, 0.03, 0.05, 0.72)
mouse_filter = 0
[node name="ResultCenter" type="CenterContainer" parent="OverlayLayer/ResultScreen"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 1
[node name="ResultCard" type="PanelContainer" parent="OverlayLayer/ResultScreen/ResultCenter"]
custom_minimum_size = Vector2(700, 0)
layout_mode = 2
[node name="ResultContent" type="VBoxContainer" parent="OverlayLayer/ResultScreen/ResultCenter/ResultCard"]
layout_mode = 2
theme_override_constants/separation = 16
[node name="ResultTitle" type="Label" parent="OverlayLayer/ResultScreen/ResultCenter/ResultCard/ResultContent"]
layout_mode = 2
text = "对局结束"
horizontal_alignment = 1
theme_override_font_sizes/font_size = 32
[node name="ResultWinner" type="Label" parent="OverlayLayer/ResultScreen/ResultCenter/ResultCard/ResultContent"]
layout_mode = 2
text = ""
horizontal_alignment = 1
theme_override_font_sizes/font_size = 24
[node name="ResultSummary" type="Label" parent="OverlayLayer/ResultScreen/ResultCenter/ResultCard/ResultContent"]
layout_mode = 2
text = ""
horizontal_alignment = 1
autowrap_mode = 2
[node name="ResultButtons" type="HBoxContainer" parent="OverlayLayer/ResultScreen/ResultCenter/ResultCard/ResultContent"]
layout_mode = 2
alignment = 1
theme_override_constants/separation = 18
[node name="ResultRestartButton" type="Button" parent="OverlayLayer/ResultScreen/ResultCenter/ResultCard/ResultContent/ResultButtons"]
custom_minimum_size = Vector2(180, 52)
layout_mode = 2
text = "再来一局"
[node name="ResultCloseButton" type="Button" parent="OverlayLayer/ResultScreen/ResultCenter/ResultCard/ResultContent/ResultButtons"]
custom_minimum_size = Vector2(180, 52)
layout_mode = 2
text = "查看战场"
+84
View File
@@ -0,0 +1,84 @@
using OSM.Client.Contracts;
namespace OSM.Client.Screens.Battle;
public enum BattleAnimationKind
{
Move,
Hit,
Heal,
Eliminate,
Respawn
}
/// <summary>一条待播放的表现任务(只描述「发生了什么」,不含屏幕坐标)。</summary>
public sealed record BattleAnimationRequest(
string Guid,
BattleAnimationKind Kind,
double Magnitude);
/// <summary>
/// 权威快照差分:把「上一帧快照 → 这一帧快照」翻译成表现任务。
/// <para><b>纯函数</b>:不碰场景、不碰时间,只读两个快照 —— 这样表现层的行为可以被静态自检钉死
/// (见 PhaseESmokeTest),也避免把动画逻辑混进网络/权威状态里。</para>
/// <para>只依据服务器给的数据推断,不做任何「应该掉了多少血」「应该走到哪」的本地计算:
/// 位置变化看 <c>gridId</c>,血量变化看 <c>hp</c> 差值,生死看 <c>isEliminated</c>。</para>
/// </summary>
public static class BattleSnapshotDiff
{
public static IReadOnlyList<BattleAnimationRequest> Build(
SoloGameState? previous,
SoloGameState? current)
{
if (current is null)
{
return [];
}
// 首帧没有可比对象:全部单位直接以权威状态出现,不播任何补间。
if (previous is null)
{
return [];
}
var previousByGuid = previous.Characters.ToDictionary(
character => character.Guid,
StringComparer.Ordinal);
List<BattleAnimationRequest> requests = [];
foreach (var character in current.Characters)
{
if (!previousByGuid.TryGetValue(character.Guid, out var before))
{
// 中途新出现的单位(复活/召唤)以权威状态直接现身,不补间。
continue;
}
if (before.GridId != character.GridId)
{
requests.Add(new BattleAnimationRequest(character.Guid, BattleAnimationKind.Move, 0));
}
var hpDelta = character.Hp - before.Hp;
if (hpDelta < -0.001)
{
requests.Add(new BattleAnimationRequest(character.Guid, BattleAnimationKind.Hit, -hpDelta));
}
else if (hpDelta > 0.001)
{
requests.Add(new BattleAnimationRequest(character.Guid, BattleAnimationKind.Heal, hpDelta));
}
if (!before.IsEliminated && character.IsEliminated)
{
requests.Add(new BattleAnimationRequest(character.Guid, BattleAnimationKind.Eliminate, 0));
}
else if (before.IsEliminated && !character.IsEliminated)
{
requests.Add(new BattleAnimationRequest(character.Guid, BattleAnimationKind.Respawn, 0));
}
}
return requests;
}
}
@@ -0,0 +1 @@
uid://d2yhwg52hk0j4
+73 -1
View File
@@ -35,7 +35,7 @@ public static class DecisionUiRules
var remaining = quotas.Sum(quota => quota.Remaining); var remaining = quotas.Sum(quota => quota.Remaining);
var total = quotas.Sum(quota => quota.Quota); var total = quotas.Sum(quota => quota.Quota);
var minimumCost = quotas.Min(quota => quota.DecisionPointCost); var minimumCost = quotas.Min(quota => quota.DecisionPointCost);
return $"{baseLabel} {remaining}/{total} · {minimumCost}DP"; return $"{baseLabel}\n{remaining}/{total} · {minimumCost}DP";
} }
public static string SkillDetails(SoloSkillDto skill) public static string SkillDetails(SoloSkillDto skill)
@@ -75,6 +75,78 @@ public static class DecisionUiRules
return $"{item.ItemType} · 射程 {range} · {uses}{reason}\n{description}"; return $"{item.ItemType} · 射程 {range} · {uses}{reason}\n{description}";
} }
/// <summary>
/// 服务器对"提交了但不可行"的行动没有拒绝回执(<c>gaming.resolved</c> 尚未实现),
/// 唯一信号是<b>紧随其后的那条决策类型</b>:可行的行动一定会进入它自己的下一步
/// (Move→TargetGrid、NormalAttack→Targets、PreCastSkill→Skill、UseItem→Item),
/// 而被作废的行动会直接回到 <c>ActionType</c> 重新询问。
/// <para>返回 null 表示"接受了"或"无法判定";返回文案表示该行动被服务器取消。</para>
/// </summary>
/// <summary>
/// 普通攻击此刻是否真的打得到人。
/// <para>优先用服务端的严格口径 <c>attackTargets</c>(= ATR 内可达的敌人),它与引擎在选普攻目标前
/// 自己做的收窄完全一致;为空即提交必然被作废。</para>
/// <para>旧版服务端不下发该字段时退回 <c>enemyOptions</c> 的宽口径(攻击可达 ∪ 施法可达)——
/// 那只能证明「场上有敌人」,证明不了「够得着」,属于不够精确的必要条件。</para>
/// <para>返回 null 表示没有可判断的负载。</para>
/// </summary>
public static bool? IsNormalAttackReachable(ActionTypePayload? payload)
{
if (payload is null)
{
return null;
}
if (payload.AttackTargets is { } precise)
{
return precise.Count > 0;
}
if (payload.CanNormalAttack is { } flag)
{
return flag;
}
return payload.EnemyOptions.Count > 0 || payload.Enemys.Count > 0;
}
public static string? DetectCancelledAction(string? submittedAction, string? nextDecisionKind)
{
if (string.IsNullOrEmpty(submittedAction) || string.IsNullOrEmpty(nextDecisionKind))
{
return null;
}
var expected = submittedAction switch
{
"Move" => SoloDecisionKinds.TargetGrid,
"NormalAttack" => SoloDecisionKinds.Targets,
"PreCastSkill" or "CastSkill" or "CastSuperSkill" => SoloDecisionKinds.Skill,
"UseItem" => SoloDecisionKinds.Item,
_ => null
};
if (expected is null || nextDecisionKind == expected)
{
return null;
}
// 只有"直接回到行动菜单"才是无歧义的行动作废;其他岔路(如换目标阶段)不在这里报错。
return nextDecisionKind == SoloDecisionKinds.ActionType
? $"{ActionLabel(submittedAction)}被服务器取消:当前位置没有符合条件的目标或格子,换一个行动试试。"
: null;
}
private static string ActionLabel(string actionType) => actionType switch
{
"Move" => "移动",
"NormalAttack" => "普通攻击",
"PreCastSkill" or "CastSkill" => "技能",
"CastSuperSkill" => "爆发技",
"UseItem" => "使用物品",
_ => actionType
};
public static IReadOnlyList<long> GetAffectedGridIds( public static IReadOnlyList<long> GetAffectedGridIds(
TargetGridsPayload payload, TargetGridsPayload payload,
long centerGridId, long centerGridId,
@@ -0,0 +1 @@
uid://cwadnbm01wjp2
+8
View File
@@ -13,6 +13,14 @@ public partial class Main : Node
{ {
AddChild(new OSM.Client.Diagnostics.PhaseCDecisionSmokeTest()); AddChild(new OSM.Client.Diagnostics.PhaseCDecisionSmokeTest());
} }
else if (userArguments.Contains("phase-e-smoke-test"))
{
AddChild(new OSM.Client.Diagnostics.PhaseESmokeTest());
}
else if (userArguments.Contains("solo-reconnect-smoke-test"))
{
AddChild(new OSM.Client.Diagnostics.SoloReconnectSmokeTest());
}
else if (userArguments.Contains("solo-vertical-smoke-test")) else if (userArguments.Contains("solo-vertical-smoke-test"))
{ {
AddChild(new OSM.Client.Diagnostics.SoloVerticalSliceSmokeTest()); AddChild(new OSM.Client.Diagnostics.SoloVerticalSliceSmokeTest());
+64 -3
View File
@@ -14,6 +14,7 @@ public partial class UnitView : Node2D
private Area2D _hitArea = null!; private Area2D _hitArea = null!;
private ProgressBar _hpBar = null!; private ProgressBar _hpBar = null!;
private Label _aiLabel = null!; private Label _aiLabel = null!;
private Label _selectedLabel = null!;
private Label _nameLabel = null!; private Label _nameLabel = null!;
private bool _isFriendly; private bool _isFriendly;
@@ -21,10 +22,15 @@ public partial class UnitView : Node2D
private bool _isSelectable; private bool _isSelectable;
private bool _isSelected; private bool _isSelected;
private bool _isEliminated; private bool _isEliminated;
private Tween? _hpTween;
private Tween? _flashTween;
public string CharacterGuid { get; private set; } = string.Empty; public string CharacterGuid { get; private set; } = string.Empty;
public long CharacterId { get; private set; } public long CharacterId { get; private set; }
/// <summary>最近一次权威快照里的血量。血条补间只是表现,这个值才是判定依据。</summary>
public double AuthoritativeHp { get; private set; }
public override void _Ready() public override void _Ready()
{ {
_shadow = GetNode<Polygon2D>("Shadow"); _shadow = GetNode<Polygon2D>("Shadow");
@@ -34,6 +40,7 @@ public partial class UnitView : Node2D
_hitArea = GetNode<Area2D>("HitArea"); _hitArea = GetNode<Area2D>("HitArea");
_hpBar = GetNode<ProgressBar>("HpBar"); _hpBar = GetNode<ProgressBar>("HpBar");
_aiLabel = GetNode<Label>("StatusIcons/AiLabel"); _aiLabel = GetNode<Label>("StatusIcons/AiLabel");
_selectedLabel = GetNode<Label>("SelectedLabel");
_nameLabel = GetNode<Label>("NameLabel"); _nameLabel = GetNode<Label>("NameLabel");
_hitArea.InputEvent += OnInputEvent; _hitArea.InputEvent += OnInputEvent;
@@ -42,12 +49,18 @@ public partial class UnitView : Node2D
AddToGroup("battle_unit"); AddToGroup("battle_unit");
} }
/// <summary>
/// 应用权威快照。<paramref name="deferPosition"/> / <paramref name="deferHp"/> 为真时表示
/// 表现层正在接管该棋子的位置或血条补间,本次只更新权威数值与状态,不覆盖正在播放的画面。
/// </summary>
public void ApplySnapshot( public void ApplySnapshot(
SoloCharacterDto character, SoloCharacterDto character,
bool isFriendly, bool isFriendly,
bool isCurrentActor, bool isCurrentActor,
bool isSelectable, bool isSelectable,
Vector2 worldPosition) Vector2 worldPosition,
bool deferPosition = false,
bool deferHp = false)
{ {
CharacterGuid = character.Guid; CharacterGuid = character.Guid;
CharacterId = character.Id; CharacterId = character.Id;
@@ -55,11 +68,19 @@ public partial class UnitView : Node2D
_isCurrentActor = isCurrentActor; _isCurrentActor = isCurrentActor;
_isSelectable = isSelectable; _isSelectable = isSelectable;
_isEliminated = character.IsEliminated; _isEliminated = character.IsEliminated;
AuthoritativeHp = character.Hp;
if (!deferPosition)
{
Position = worldPosition; Position = worldPosition;
}
_nameLabel.Text = character.DisplayName; _nameLabel.Text = character.DisplayName;
_hpBar.MaxValue = Math.Max(1.0, character.MaxHp); _hpBar.MaxValue = Math.Max(1.0, character.MaxHp);
if (!deferHp)
{
_hpBar.Value = Mathf.Clamp((float)character.Hp, 0.0f, (float)_hpBar.MaxValue); _hpBar.Value = Mathf.Clamp((float)character.Hp, 0.0f, (float)_hpBar.MaxValue);
}
_hpBar.TooltipText = $"HP {character.Hp:0} / {character.MaxHp:0}"; _hpBar.TooltipText = $"HP {character.Hp:0} / {character.MaxHp:0}";
_aiLabel.Visible = character.IsAi; _aiLabel.Visible = character.IsAi;
_body.Visible = false; _body.Visible = false;
@@ -80,6 +101,45 @@ public partial class UnitView : Node2D
UpdateVisuals(); UpdateVisuals();
} }
/// <summary>
/// 血条补间:从「变化前」走到权威值。
/// 数值本身早已由快照决定,这里只负责让它走得有因果感,绝不反过来影响任何判定。
/// </summary>
public void PlayHpTransition(double fromHp, double toHp, double durationSeconds)
{
KillTween(ref _hpTween);
_hpBar.Value = Math.Clamp(fromHp, 0.0, _hpBar.MaxValue);
_hpTween = CreateTween();
_hpTween.TweenProperty(
_hpBar,
"value",
Math.Clamp(toHp, 0.0, _hpBar.MaxValue),
Math.Max(0.05, durationSeconds));
}
public void FlashDamage() => Flash(new Color(1.0f, 0.40f, 0.40f));
public void FlashHeal() => Flash(new Color(0.48f, 1.0f, 0.62f));
private void Flash(Color tint)
{
KillTween(ref _flashTween);
_placeholderBody.Modulate = Colors.White;
_flashTween = CreateTween();
_flashTween.TweenProperty(_placeholderBody, "modulate", tint, 0.09);
_flashTween.TweenProperty(_placeholderBody, "modulate", Colors.White, 0.22);
}
private static void KillTween(ref Tween? tween)
{
if (tween is not null && tween.IsValid())
{
tween.Kill();
}
tween = null;
}
private void UpdateVisuals() private void UpdateVisuals()
{ {
var teamColor = _isFriendly var teamColor = _isFriendly
@@ -100,6 +160,7 @@ public partial class UnitView : Node2D
? new Color("ff9a62") ? new Color("ff9a62")
: new Color("f4d35e"); : new Color("f4d35e");
_selectionRing.Width = _isSelected ? 5.0f : 3.0f; _selectionRing.Width = _isSelected ? 5.0f : 3.0f;
_selectedLabel.Visible = _isSelected;
_hpBar.Modulate = _isEliminated ? new Color(1, 1, 1, 0.45f) : Colors.White; _hpBar.Modulate = _isEliminated ? new Color(1, 1, 1, 0.45f) : Colors.White;
_nameLabel.Modulate = _isEliminated ? new Color(1, 1, 1, 0.55f) : Colors.White; _nameLabel.Modulate = _isEliminated ? new Color(1, 1, 1, 0.55f) : Colors.White;
ZIndex = 0; ZIndex = 0;
@@ -125,12 +186,12 @@ public partial class UnitView : Node2D
{ {
if (_isSelectable && !_isEliminated) if (_isSelectable && !_isEliminated)
{ {
_placeholderBody.Scale = Vector2.One * 1.06f; _placeholderBody.Scale = Vector2.One * (_isSelected ? 1.12f : 1.06f);
} }
} }
private void OnMouseExited() private void OnMouseExited()
{ {
_placeholderBody.Scale = Vector2.One; _placeholderBody.Scale = Vector2.One * (_isSelected ? 1.08f : 1.0f);
} }
} }
+1
View File
@@ -0,0 +1 @@
uid://cmql5o3r5i2yb
+15 -1
View File
@@ -8,6 +8,7 @@
size = Vector2(72, 116) size = Vector2(72, 116)
[node name="UnitView" type="Node2D"] [node name="UnitView" type="Node2D"]
scale = Vector2(1.08, 1.08)
script = ExtResource("1_unit") script = ExtResource("1_unit")
[node name="Shadow" type="Polygon2D" parent="."] [node name="Shadow" type="Polygon2D" parent="."]
@@ -62,6 +63,20 @@ horizontal_alignment = 1
theme_override_colors/font_color = Color(1, 0.78, 0.34, 1) theme_override_colors/font_color = Color(1, 0.78, 0.34, 1)
theme_override_font_sizes/font_size = 14 theme_override_font_sizes/font_size = 14
[node name="SelectedLabel" type="Label" parent="."]
visible = false
offset_left = -42.0
offset_top = -202.0
offset_right = 42.0
offset_bottom = -178.0
mouse_filter = 2
text = "✓ 已选目标"
horizontal_alignment = 1
theme_override_colors/font_color = Color(1, 0.92, 0.58, 1)
theme_override_colors/font_outline_color = Color(0.02, 0.04, 0.08, 1)
theme_override_constants/outline_size = 4
theme_override_font_sizes/font_size = 14
[node name="NameLabel" type="Label" parent="."] [node name="NameLabel" type="Label" parent="."]
offset_left = -88.0 offset_left = -88.0
offset_top = 12.0 offset_top = 12.0
@@ -73,4 +88,3 @@ horizontal_alignment = 1
theme_override_colors/font_outline_color = Color(0.02, 0.03, 0.05, 1) theme_override_colors/font_outline_color = Color(0.02, 0.03, 0.05, 1)
theme_override_constants/outline_size = 5 theme_override_constants/outline_size = 5
theme_override_font_sizes/font_size = 18 theme_override_font_sizes/font_size = 18
+82 -7
View File
@@ -1,23 +1,68 @@
using OSM.Client.Contracts;
namespace OSM.Client.World; namespace OSM.Client.World;
public partial class BattleCameraController : Camera2D public partial class BattleCameraController : Camera2D
{ {
[Export] [Export]
public float PanSpeed { get; set; } = 720.0f; public float PanSpeed { get; set; } = 640.0f;
[Export] [Export]
public float ZoomStep { get; set; } = 0.1f; public float ZoomFactor { get; set; } = 1.15f;
[Export] [Export]
public float MinimumZoom { get; set; } = 0.55f; public float MinimumZoom { get; set; } = 0.45f;
[Export] [Export]
public float MaximumZoom { get; set; } = 1.5f; public float MaximumZoom { get; set; } = 2.5f;
private bool _dragging; private bool _dragging;
private Rect2 _mapBounds;
private bool _hasMapBounds;
/// <summary>让实际收到的地图落入 HUD 之间的可交互视野。</summary>
public void FrameMap(SoloMapDto map, Vector2 viewportSize, Vector2 cellSize)
{
if (map.Grids.Count == 0)
{
return;
}
var left = float.PositiveInfinity;
var top = float.PositiveInfinity;
var right = float.NegativeInfinity;
var bottom = float.NegativeInfinity;
foreach (var grid in map.Grids)
{
var center = GridProjector.GridToScreen(
new Vector2I(grid.X, grid.Y), cellSize.X, cellSize.Y, grid.Z);
left = Mathf.Min(left, center.X - cellSize.X * 0.5f);
right = Mathf.Max(right, center.X + cellSize.X * 0.5f);
top = Mathf.Min(top, center.Y - cellSize.Y * 0.5f);
bottom = Mathf.Max(bottom, center.Y + cellSize.Y * 0.5f);
}
_mapBounds = new Rect2(new Vector2(left, top), new Vector2(right - left, bottom - top));
_hasMapBounds = true;
var width = Mathf.Max(1.0f, right - left);
var height = Mathf.Max(1.0f, bottom - top);
// 上方是状态栏,右侧是行动区,下方是指令栏。
var desiredZoom = Mathf.Min(viewportSize.X * 0.68f / width,
viewportSize.Y * 0.62f / height);
// 默认比全图适配更近一档;滚轮可退回全图,也可继续拉近查看细节。
SetZoom(desiredZoom * 1.45f);
Position = new Vector2((left + right) * 0.5f, (top + bottom) * 0.5f);
ClampToMapBounds();
ResetSmoothing();
}
public override void _Process(double delta) public override void _Process(double delta)
{ {
if (GetViewport().GuiGetFocusOwner() is LineEdit or TextEdit)
{
return;
}
var direction = Vector2.Zero; var direction = Vector2.Zero;
if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left))
{ {
@@ -39,6 +84,7 @@ public partial class BattleCameraController : Camera2D
if (direction != Vector2.Zero) if (direction != Vector2.Zero)
{ {
Position += direction.Normalized() * PanSpeed * (float)delta / Zoom.X; Position += direction.Normalized() * PanSpeed * (float)delta / Zoom.X;
ClampToMapBounds();
} }
} }
@@ -53,27 +99,56 @@ public partial class BattleCameraController : Camera2D
case InputEventMouseMotion mouseMotion when _dragging: case InputEventMouseMotion mouseMotion when _dragging:
Position -= mouseMotion.Relative / Zoom; Position -= mouseMotion.Relative / Zoom;
ClampToMapBounds();
GetViewport().SetInputAsHandled(); GetViewport().SetInputAsHandled();
break; break;
case InputEventMouseButton mouseButton when mouseButton.Pressed case InputEventMouseButton mouseButton when mouseButton.Pressed
&& mouseButton.ButtonIndex == MouseButton.WheelUp: && mouseButton.ButtonIndex == MouseButton.WheelUp:
SetZoom(Zoom.X + ZoomStep); ZoomAtCursor(mouseButton.Position, Zoom.X * ZoomFactor);
GetViewport().SetInputAsHandled(); GetViewport().SetInputAsHandled();
break; break;
case InputEventMouseButton mouseButton when mouseButton.Pressed case InputEventMouseButton mouseButton when mouseButton.Pressed
&& mouseButton.ButtonIndex == MouseButton.WheelDown: && mouseButton.ButtonIndex == MouseButton.WheelDown:
SetZoom(Zoom.X - ZoomStep); ZoomAtCursor(mouseButton.Position, Zoom.X / ZoomFactor);
GetViewport().SetInputAsHandled(); GetViewport().SetInputAsHandled();
break; break;
} }
} }
private void ZoomAtCursor(Vector2 viewportMousePosition, float value)
{
var offset = viewportMousePosition - GetViewport().GetVisibleRect().Size * 0.5f;
var worldPoint = GetScreenCenterPosition() + offset / Zoom;
SetZoom(value);
Position = worldPoint - offset / Zoom;
ClampToMapBounds();
ResetSmoothing();
}
private void ClampToMapBounds()
{
if (!_hasMapBounds)
{
return;
}
var viewportWorldSize = GetViewport().GetVisibleRect().Size / Zoom.X;
var halfView = viewportWorldSize * 0.5f;
var minX = _mapBounds.Position.X + halfView.X;
var maxX = _mapBounds.End.X - halfView.X;
var minY = _mapBounds.Position.Y + halfView.Y;
var maxY = _mapBounds.End.Y - halfView.Y;
Position = new Vector2(
minX <= maxX ? Mathf.Clamp(Position.X, minX, maxX) : _mapBounds.GetCenter().X,
minY <= maxY ? Mathf.Clamp(Position.Y, minY, maxY) : _mapBounds.GetCenter().Y);
}
private void SetZoom(float value) private void SetZoom(float value)
{ {
var clamped = Mathf.Clamp(value, MinimumZoom, MaximumZoom); var clamped = Mathf.Clamp(value, MinimumZoom, MaximumZoom);
Zoom = Vector2.One * clamped; Zoom = Vector2.One * clamped;
} }
} }
+77 -35
View File
@@ -1,12 +1,34 @@
using OSM.Client.Contracts;
namespace OSM.Client.World; namespace OSM.Client.World;
/// <summary>
/// 灰盒地面渲染。
/// <para><b>只画服务器地图里真实存在的格子</b>:坐标、高度、颜色全部来自 <c>MapDto</c>,
/// 因此不再假设「地图是从 (0,0) 起的稠密矩形」,也不会画出协议里根本不存在的掩体
/// (<c>GridDto</c> 只有 <c>Id/X/Y/Z/Color/Characters</c>,掩体规则见实施计划 §10,本阶段不包含)。</para>
/// </summary>
public partial class GreyboxMap2D : Node2D public partial class GreyboxMap2D : Node2D
{ {
/// <summary>
/// 服务器格子颜色的默认值,对应 FunGame.Core 里 <c>Grid.Color</c> 的初始值
/// <c>System.Drawing.Color.Gray</c>。全图都是它说明地图作者没给任何格子指定颜色。
/// </summary>
private const string ServerDefaultGridColor = "Gray";
[Export] [Export]
public Vector2I MapSize { get; set; } = new(16, 12); public Vector2I MapSize { get; set; } = new(16, 12);
[Export] [Export]
public Vector2 CellSize { get; set; } = new(128, 64); public Vector2 CellSize { get; set; } = new(144, 72);
[Export(PropertyHint.Range, "0,8,0.25")]
public float CellGapPixels { get; set; } = 2.0f;
private readonly List<SoloGridDto> _grids = [];
/// <summary>当前实际参与绘制的格子(自检用:画的就是服务器给的那批)。</summary>
public IReadOnlyList<SoloGridDto> DrawnGrids => _grids;
public override void _Ready() public override void _Ready()
{ {
@@ -19,33 +41,71 @@ public partial class GreyboxMap2D : Node2D
QueueRedraw(); QueueRedraw();
} }
/// <summary>用权威地图数据重建地面。传 null 表示清空。</summary>
public void SetMap(SoloMapDto? map)
{
_grids.Clear();
if (map is not null)
{
_grids.AddRange(map.Grids);
MapSize = new Vector2I(map.Length, map.Width);
}
QueueRedraw();
}
public override void _Draw() public override void _Draw()
{ {
for (var y = 0; y < MapSize.Y; y++) foreach (var grid in _grids)
{ {
for (var x = 0; x < MapSize.X; x++) var points = Diamond(CellCenter(grid));
{ var checker = (grid.X + grid.Y) % 2 == 0;
var center = GridProjector.GridToScreen(new Vector2I(x, y), CellSize.X, CellSize.Y); DrawColoredPolygon(points, checker ? new Color("273746") : new Color("22313f"));
var points = Diamond(center);
var checker = (x + y) % 2 == 0;
var fill = checker
? new Color("273746")
: new Color("22313f");
DrawColoredPolygon(points, fill); // 服务器显式指定过颜色时叠一层半透明着色;默认 Gray 视为「未指定」,
// 保留灰盒棋盘配色(否则当前每张图都会被刷成整片灰)。
if (TryParseExplicitColor(grid.Color, out var tint))
{
DrawColoredPolygon(points, tint with { A = 0.45f });
}
} }
} }
DrawCover(new Vector2I(5, 4), new Color("526777")); private Vector2 CellCenter(SoloGridDto grid)
DrawCover(new Vector2I(6, 4), new Color("526777")); {
DrawCover(new Vector2I(10, 7), new Color("705d54")); // 用服务器的 Z 抬升格心:单位位置本来就用了 Z(见 BattleScreen 的 GridToScreen 调用),
DrawCover(new Vector2I(11, 7), new Color("705d54")); // 地面若忽略 Z,多层地图上地面与棋子就会错位。
return GridProjector.GridToScreen(
new Vector2I(grid.X, grid.Y),
CellSize.X,
CellSize.Y,
grid.Z);
}
private static bool TryParseExplicitColor(string? serverColor, out Color color)
{
color = Colors.White;
if (string.IsNullOrWhiteSpace(serverColor)
|| string.Equals(serverColor, ServerDefaultGridColor, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Godot 的命名色表不保证覆盖 System.Drawing 的全部名字;认不出来就当没指定。
var parsed = Color.FromString(serverColor, Colors.Transparent);
if (parsed.A <= 0.001f)
{
return false;
}
color = parsed;
return true;
} }
private Vector2[] Diamond(Vector2 center) private Vector2[] Diamond(Vector2 center)
{ {
var halfWidth = CellSize.X * 0.5f; var halfWidth = Math.Max(1.0f, CellSize.X * 0.5f - CellGapPixels);
var halfHeight = CellSize.Y * 0.5f; var halfHeight = Math.Max(1.0f, CellSize.Y * 0.5f - CellGapPixels);
return return
[ [
center + new Vector2(0, -halfHeight), center + new Vector2(0, -halfHeight),
@@ -54,22 +114,4 @@ public partial class GreyboxMap2D : Node2D
center + new Vector2(-halfWidth, 0) center + new Vector2(-halfWidth, 0)
]; ];
} }
private void DrawCover(Vector2I grid, Color color)
{
var center = GridProjector.GridToScreen(grid, CellSize.X, CellSize.Y);
var top = center + new Vector2(0, -28);
var basePoints = Diamond(center);
var topPoints = Diamond(top);
DrawColoredPolygon(
[
basePoints[1], basePoints[2], topPoints[2], topPoints[1]
], color.Darkened(0.25f));
DrawColoredPolygon(
[
basePoints[2], basePoints[3], topPoints[3], topPoints[2]
], color.Darkened(0.4f));
DrawColoredPolygon(topPoints, color);
}
} }
+39 -13
View File
@@ -20,11 +20,15 @@ public partial class GridOverlay2D : Node2D
public Vector2I MapSize { get; set; } = new(16, 12); public Vector2I MapSize { get; set; } = new(16, 12);
[Export] [Export]
public Vector2 CellSize { get; set; } = new(128, 64); public Vector2 CellSize { get; set; } = new(144, 72);
[Export(PropertyHint.Range, "0,8,0.25")]
public float CellGapPixels { get; set; } = 2.0f;
private GridVisualState _visualState = GridVisualState.Hidden; private GridVisualState _visualState = GridVisualState.Hidden;
private Vector2I _hoveredCell = new(-1, -1); private Vector2I _hoveredCell = new(-1, -1);
private readonly Dictionary<long, Vector2I> _cellsById = []; private readonly Dictionary<long, Vector3I> _cellsById = [];
private readonly Dictionary<Vector2I, int> _heightByCoordinate = [];
private readonly HashSet<long> _reachableCells = []; private readonly HashSet<long> _reachableCells = [];
private readonly HashSet<long> _attackCells = []; private readonly HashSet<long> _attackCells = [];
private readonly HashSet<long> _affectedCells = []; private readonly HashSet<long> _affectedCells = [];
@@ -48,12 +52,13 @@ public partial class GridOverlay2D : Node2D
public override void _Process(double delta) public override void _Process(double delta)
{ {
var localMouse = ToLocal(GetGlobalMousePosition()); var localMouse = ToLocal(GetGlobalMousePosition());
var nextHovered = GridProjector.TryScreenToGrid( var nextHovered = _cellsById.Count > 0 && GridProjector.TryScreenToGrid(
localMouse, localMouse,
MapSize, MapSize,
out var cell, out var cell,
CellSize.X, CellSize.X,
CellSize.Y) CellSize.Y)
&& _heightByCoordinate.ContainsKey(cell)
? cell ? cell
: new Vector2I(-1, -1); : new Vector2I(-1, -1);
@@ -69,7 +74,10 @@ public partial class GridOverlay2D : Node2D
public override void _UnhandledInput(InputEvent @event) public override void _UnhandledInput(InputEvent @event)
{ {
if (@event is not InputEventMouseButton // 单位的 Area2D 会在 _UnhandledInput 之后收到鼠标拾取事件。
// 只有选格阶段才消费左键,否则 Targets 阶段的单位永远点不到。
if (VisualState is not (GridVisualState.Move or GridVisualState.Attack)
|| @event is not InputEventMouseButton
{ {
ButtonIndex: MouseButton.Left, ButtonIndex: MouseButton.Left,
Pressed: true Pressed: true
@@ -92,13 +100,20 @@ public partial class GridOverlay2D : Node2D
QueueRedraw(); QueueRedraw();
} }
public void SetGridCoordinates(IEnumerable<KeyValuePair<long, Vector2I>> cells) /// <summary>
/// 记录格子的真实坐标(含高度 Z),格子 ID 与坐标的对应只信服务器,不假设 ID 等于数组索引。
/// Z 用于把高亮画在正确的抬升高度上,与地面和单位保持一致。
/// </summary>
public void SetGridCoordinates(IEnumerable<KeyValuePair<long, Vector3I>> cells)
{ {
_cellsById.Clear(); _cellsById.Clear();
_heightByCoordinate.Clear();
foreach (var cell in cells) foreach (var cell in cells)
{ {
_cellsById[cell.Key] = cell.Value; _cellsById[cell.Key] = cell.Value;
_heightByCoordinate[new Vector2I(cell.Value.X, cell.Value.Y)] = cell.Value.Z;
} }
QueueRedraw(); QueueRedraw();
} }
@@ -142,12 +157,12 @@ public partial class GridOverlay2D : Node2D
{ {
if (VisualState == GridVisualState.Move) if (VisualState == GridVisualState.Move)
{ {
DrawCells(_reachableCells, new Color(0.18f, 0.72f, 1.0f, 0.24f), 1.5f); DrawCells(_reachableCells, new Color(0.18f, 0.76f, 1.0f, 0.38f), 2.5f);
} }
else if (VisualState == GridVisualState.Attack) else if (VisualState == GridVisualState.Attack)
{ {
DrawCells(_attackCells, new Color(1.0f, 0.34f, 0.18f, 0.22f), 1.5f); DrawCells(_attackCells, new Color(1.0f, 0.40f, 0.20f, 0.34f), 2.5f);
DrawCells(_affectedCells, new Color(1.0f, 0.68f, 0.18f, 0.27f), 2.0f); DrawCells(_affectedCells, new Color(1.0f, 0.72f, 0.20f, 0.38f), 3.0f);
} }
if (_selectedCell is long selectedId && _cellsById.TryGetValue(selectedId, out var selected)) if (_selectedCell is long selectedId && _cellsById.TryGetValue(selectedId, out var selected))
@@ -157,7 +172,7 @@ public partial class GridOverlay2D : Node2D
if (_hoveredCell.X >= 0) if (_hoveredCell.X >= 0)
{ {
DrawCell(_hoveredCell, new Color(1.0f, 0.95f, 0.55f, 0.35f), 3.0f); DrawCellAt(_hoveredCell, new Color(1.0f, 0.95f, 0.55f, 0.35f), 3.0f);
} }
} }
@@ -181,11 +196,22 @@ public partial class GridOverlay2D : Node2D
} }
} }
private void DrawCell(Vector2I grid, Color fill, float lineWidth) /// <summary>按逻辑坐标绘制(鼠标悬停用):高度取服务器给的该坐标的 Z,缺省为 0。</summary>
private void DrawCellAt(Vector2I coordinate, Color fill, float lineWidth)
{ {
var center = GridProjector.GridToScreen(grid, CellSize.X, CellSize.Y); var height = _heightByCoordinate.GetValueOrDefault(coordinate, 0);
var halfWidth = CellSize.X * 0.5f; DrawCell(new Vector3I(coordinate.X, coordinate.Y, height), fill, lineWidth);
var halfHeight = CellSize.Y * 0.5f; }
private void DrawCell(Vector3I grid, Color fill, float lineWidth)
{
var center = GridProjector.GridToScreen(
new Vector2I(grid.X, grid.Y),
CellSize.X,
CellSize.Y,
grid.Z);
var halfWidth = Math.Max(1.0f, CellSize.X * 0.5f - CellGapPixels);
var halfHeight = Math.Max(1.0f, CellSize.Y * 0.5f - CellGapPixels);
Vector2[] points = Vector2[] points =
[ [
center + new Vector2(0, -halfHeight), center + new Vector2(0, -halfHeight),