From 5f1be65512139c47a80c11474449222bab019004 Mon Sep 17 00:00:00 2001 From: milimoe Date: Thu, 24 Sep 2026 22:55:46 +0800 Subject: [PATCH] =?UTF-8?q?UI=E6=8F=90=E5=8D=87=EF=BC=8C=E8=BF=9B=E5=85=A5?= =?UTF-8?q?=E8=83=BD=E8=B7=91=E9=98=B6=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 + docs/Godot战斗竖切实施计划.md | 189 ++++++- project.godot | 14 +- src/Autoload/BattleStore.cs | 96 +++- src/Autoload/GameSession.cs | 254 +++++++-- src/Autoload/GameSettings.cs | 12 +- src/Contracts/BattleSnapshot.cs | 10 + src/Contracts/DecisionRequest.cs | 14 + src/Diagnostics/PhaseCDecisionSmokeTest.cs | 113 +++- .../PhaseCDecisionSmokeTest.cs.uid | 1 + src/Diagnostics/PhaseESmokeTest.cs | 338 ++++++++++++ src/Diagnostics/PhaseESmokeTest.cs.uid | 1 + src/Diagnostics/SoloConnectionSmokeTest.cs | 195 ++++++- .../SoloConnectionSmokeTest.cs.uid | 1 + src/Diagnostics/SoloReconnectSmokeTest.cs | 411 +++++++++++++++ src/Diagnostics/SoloReconnectSmokeTest.cs.uid | 1 + src/Diagnostics/SoloTestDriver.cs | 124 +++++ src/Diagnostics/SoloTestDriver.cs.uid | 1 + src/Diagnostics/SoloTrace.cs | 20 + src/Diagnostics/SoloTrace.cs.uid | 1 + src/Diagnostics/SoloVerticalSliceSmokeTest.cs | 473 +++++++++++++---- .../SoloVerticalSliceSmokeTest.cs.uid | 1 + src/GlobalUsings.cs.uid | 1 + src/Networking/IGameTransport.cs | 7 + src/Networking/MockTransport.cs | 12 + src/Networking/WebSocketTransport.cs | 44 +- src/README.md | 2 +- src/Resources/SilverFantasyTheme.tres | 156 ++++++ src/Screens/Battle/BattleAnimator.cs | 333 ++++++++++++ src/Screens/Battle/BattleAnimator.cs.uid | 1 + src/Screens/Battle/BattleScreen.Hud.cs | 291 +++++++++++ src/Screens/Battle/BattleScreen.Hud.cs.uid | 1 + src/Screens/Battle/BattleScreen.Overlays.cs | 455 ++++++++++++++++ .../Battle/BattleScreen.Overlays.cs.uid | 1 + src/Screens/Battle/BattleScreen.cs | 415 +++++++++++++-- src/Screens/Battle/BattleScreen.tscn | 492 ++++++++++++++++-- src/Screens/Battle/BattleSnapshotDiff.cs | 84 +++ src/Screens/Battle/BattleSnapshotDiff.cs.uid | 1 + src/Screens/Battle/DecisionUiRules.cs | 74 ++- src/Screens/Battle/DecisionUiRules.cs.uid | 1 + src/Screens/Main/Main.cs | 8 + src/Units/UnitView.cs | 71 ++- src/Units/UnitView.cs.uid | 1 + src/Units/UnitView.tscn | 16 +- src/World/BattleCameraController.cs | 89 +++- src/World/GreyboxMap2D.cs | 118 +++-- src/World/GridOverlay2D.cs | 52 +- 47 files changed, 4645 insertions(+), 354 deletions(-) create mode 100644 src/Diagnostics/PhaseCDecisionSmokeTest.cs.uid create mode 100644 src/Diagnostics/PhaseESmokeTest.cs create mode 100644 src/Diagnostics/PhaseESmokeTest.cs.uid create mode 100644 src/Diagnostics/SoloConnectionSmokeTest.cs.uid create mode 100644 src/Diagnostics/SoloReconnectSmokeTest.cs create mode 100644 src/Diagnostics/SoloReconnectSmokeTest.cs.uid create mode 100644 src/Diagnostics/SoloTestDriver.cs create mode 100644 src/Diagnostics/SoloTestDriver.cs.uid create mode 100644 src/Diagnostics/SoloTrace.cs create mode 100644 src/Diagnostics/SoloTrace.cs.uid create mode 100644 src/Diagnostics/SoloVerticalSliceSmokeTest.cs.uid create mode 100644 src/GlobalUsings.cs.uid create mode 100644 src/Resources/SilverFantasyTheme.tres create mode 100644 src/Screens/Battle/BattleAnimator.cs create mode 100644 src/Screens/Battle/BattleAnimator.cs.uid create mode 100644 src/Screens/Battle/BattleScreen.Hud.cs create mode 100644 src/Screens/Battle/BattleScreen.Hud.cs.uid create mode 100644 src/Screens/Battle/BattleScreen.Overlays.cs create mode 100644 src/Screens/Battle/BattleScreen.Overlays.cs.uid create mode 100644 src/Screens/Battle/BattleSnapshotDiff.cs create mode 100644 src/Screens/Battle/BattleSnapshotDiff.cs.uid create mode 100644 src/Screens/Battle/DecisionUiRules.cs.uid create mode 100644 src/Units/UnitView.cs.uid diff --git a/.gitignore b/.gitignore index 23acf3f..696839d 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,6 @@ logs/ # Game Assets assets/ + +# Others +.workbuddy/ diff --git a/docs/Godot战斗竖切实施计划.md b/docs/Godot战斗竖切实施计划.md index 48e2b7f..c18c19a 100644 --- a/docs/Godot战斗竖切实施计划.md +++ b/docs/Godot战斗竖切实施计划.md @@ -17,7 +17,7 @@ Godot 客户端当前已具备: - Godot 4.7 .NET / C# 工程与 `src/` 目录结构; - `GameSession`、`BattleStore`、`AssetCatalog`、`UiRouter` 和 `GameSettings` 五个 Autoload; - WebSocket 与 Mock 传输层; -- 默认连接地址 `ws://localhost:11030/ws/solo`; +- 默认连接地址 `ws://localhost:12030/ws/solo`; - `system.ping` / `system.pong` 心跳; - `gaming.start`、`gaming.state`、`gaming.request`、`gaming.action` 等真实协议消息; - 角色选择、基础行动、技能、物品、目标和逻辑格决策的初步控件; @@ -27,8 +27,11 @@ Godot 客户端当前已具备: 当前端到端验证结果: ```text -SOLO_SMOKE_OK game= round=0 characters=2 units=2 -SOLO_VERTICAL_OK game= moves=1 attackTargetSubmitted=true rejectionRecovered=true units=2 +SOLO_SMOKE_OK dialogFits=true clickableList=true clickSubmits=true game= round=0 characters=10 units=10 +SOLO_VERTICAL_OK game= moves=32 attackTargetSubmitted=true rejectionRecovered=true attackAttempts=1 attackCancelled=0 attackReachableRounds=1 attackGateVerified=True preciseAttackSignal=true continueObserved=true units=2 +SOLO_RECONNECT_OK game= 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= moves=1 attackTargetSubmitted=true rejectionRecov - [x] 阶段 A:`UnitView`、按 GUID 实例协调、格子定位、阵营/行动者/HP/淘汰/AI 托管显示; - [x] 阶段 B 基础:合法格集合高亮、单位直接点击选择目标、提交前确认; - [x] 阶段 B 完整:移动与普攻的真实端到端竖切回归、服务器拒绝后的决策恢复; -- [ ] 阶段 C:完整决策类型与行动配额; -- [ ] 阶段 D:断线恢复; -- [ ] 阶段 E:动画、日志、结算与输入完善。 +- [x] 阶段 C:完整决策类型与行动配额; +- [x] 阶段 D:断线恢复; +- [x] 阶段 E:动画、日志、结算与输入完善。 阶段 A 已通过真实 Solo WebAPI 冒烟测试:权威快照含 2 名角色时,`UnitsLayer` 生成且仅生成 2 个 `UnitView`。 阶段 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` 为准动态构建显示层。 ## 3. 竖切完成后的玩家流程 @@ -123,6 +141,10 @@ BattleScreen / UnitView / GridOverlay2D | `request.kind` | 输入状态机 | 决定当前允许的交互方式 | | `request.payload.gridIds` | `GridOverlay2D` | 只显示和接受合法格子 | | `request.payload.targets` | `UnitView` | 只允许选择合法单位 | +| `ActionType.enemyOptions` / `enemys` | 行动坞 | 当前位置攻击可达 ∪ 施法可达的敌人;为空则禁用普通攻击 | +| `ActionType.dp.quotas` | 行动坞按钮 | 每种行动类型的配额 / 剩余 / 决策点消耗 | +| `request.timeoutMs` | `TimeoutLabel` | 服务器决策倒计时 | +| `state.aiEscalated` | 角色 HUD、`UnitView` | 超时或打转后服务器接管角色的提示 | 服务器目前没有正式的 `stateRevision` 字段。第一阶段按 WebSocket 顺序处理完整快照;正式重连和增量同步前,应在协议中补充单调递增的状态版本。 @@ -302,4 +324,157 @@ UnitView (Node2D) ## 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 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。 diff --git a/project.godot b/project.godot index af43fdf..785e260 100644 --- a/project.godot +++ b/project.godot @@ -1,5 +1,10 @@ ; 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 @@ -19,8 +24,8 @@ GameSettings="*res://src/Autoload/GameSettings.cs" [display] -window/size/viewport_width=1920 -window/size/viewport_height=1080 +window/size/viewport_width=1280 +window/size/viewport_height=720 window/size/window_width_override=1280 window/size/window_height_override=720 window/stretch/mode="canvas_items" @@ -37,5 +42,4 @@ locale/fallback="zh_CN" renderer/rendering_method="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) diff --git a/src/Autoload/BattleStore.cs b/src/Autoload/BattleStore.cs index 6321836..fc13378 100644 --- a/src/Autoload/BattleStore.cs +++ b/src/Autoload/BattleStore.cs @@ -31,6 +31,14 @@ public partial class BattleStore : Node [Signal] public delegate void GameFinishedEventHandler(string winnerName); + /// 重连后完成恢复流程(已发出 gaming.resume,或在无进行中对局时直接返回)。 + [Signal] + public delegate void ConnectionRecoveredEventHandler(); + + /// 服务器单方面放弃了一条挂起决策(对局结束 / 接管 / 断线)。 + [Signal] + public delegate void DecisionDroppedEventHandler(string requestId, string reason); + private GameSession _session = null!; private bool _submissionInFlight; @@ -41,16 +49,25 @@ public partial class BattleStore : Node public string? GameId { get; private set; } public bool IsStarted { get; private set; } public bool IsWaitingForStart { get; private set; } + public bool IsResuming { get; private set; } public long LastPongTimestamp { get; private set; } public bool IsSubmittingDecision => _submissionInFlight; + /// 服务器放弃过的决策数;测试用它判断「不必再等这条决策」,而不是干等到超时。 + public int DroppedDecisionCount { get; private set; } + + public string? LastDroppedRequestId { get; private set; } + public string? LastDropReason { get; private set; } + private readonly List _logLines = []; + private readonly HashSet _answeredRequestIds = new(StringComparer.Ordinal); public override void _Ready() { _session = GetNode("/root/GameSession"); _session.MessageReceived += OnMessageReceived; _session.SessionError += OnSessionError; + _session.Reconnected += OnSessionReconnected; } public async Task StartGameAsync(SoloStartOptions? options = null) @@ -76,6 +93,7 @@ public partial class BattleStore : Node } _submissionInFlight = true; + _answeredRequestIds.Add(decision.RequestId); PendingDecision = null; SetSelectionMode(BattleSelectionMode.WaitingServer); EmitSignal(SignalName.DecisionChanged); @@ -123,6 +141,47 @@ public partial class BattleStore : Node { _session.MessageReceived -= OnMessageReceived; _session.SessionError -= OnSessionError; + _session.Reconnected -= OnSessionReconnected; + } + } + + /// + /// 重连成功后的恢复流程:对局还在跑就发 gaming.resume, + /// 服务器会把这条新连接接管到仍在运行的对局上,并补发完整快照与仍在等待的决策请求。 + /// 若本局已经结束(或根本没开局),只通知界面刷新,不发 resume。 + /// + 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: - PendingDecision = envelope.Data.Deserialize(ProtocolJson.Options); - ApplyDecisionMode(PendingDecision?.Kind); + { + var request = envelope.Data.Deserialize(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); break; + } case SoloMessageTypes.GamingResolved: { var resolved = envelope.Data.Deserialize(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; SetSelectionMode(BattleSelectionMode.Watching); EmitSignal(SignalName.DecisionChanged); } + + EmitSignal(SignalName.DecisionDropped, resolved.RequestId, resolved.Reason); break; } @@ -298,6 +387,7 @@ public partial class BattleStore : Node IsStarted = false; IsWaitingForStart = false; _logLines.Clear(); + _answeredRequestIds.Clear(); _submissionInFlight = false; SetSelectionMode(BattleSelectionMode.Watching); } diff --git a/src/Autoload/GameSession.cs b/src/Autoload/GameSession.cs index d8dc514..730a0ef 100644 --- a/src/Autoload/GameSession.cs +++ b/src/Autoload/GameSession.cs @@ -14,10 +14,18 @@ public enum SessionState Faulted } +/// +/// WebSocket 生命周期 + 心跳 + 退避重连。只负责「连接」这一层: +/// 重连成功后发出 ,是否要 gaming.resume +/// 由 按对局状态决定(会话层不该知道对局的存在)。 +/// public partial class GameSession : Node { private const ulong HeartbeatIntervalMs = 15_000; + /// 重连退避:1s → 2s → 4s → 8s → 之后固定 15s。 + private static readonly double[] ReconnectBackoffSeconds = [1, 2, 4, 8, 15]; + [Signal] public delegate void StateChangedEventHandler(int state); @@ -27,34 +35,53 @@ public partial class GameSession : Node [Signal] public delegate void SessionErrorEventHandler(string message); + /// 重连成功:新连接已建立,可以补发 gaming.resume 并等待服务器补发快照。 + [Signal] + public delegate void ReconnectedEventHandler(); + private readonly ConcurrentQueue _incomingMessages = new(); private readonly ConcurrentQueue _incomingErrors = new(); + private readonly ConcurrentQueue _pendingNotices = new(); private readonly ConcurrentQueue _pendingStates = new(); private IGameTransport? _transport; private int _sequence; private ulong _nextHeartbeatAt; 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 Uri? Endpoint { get; private set; } + /// 关闭后 与自动重连都不再生效(测试用 Mock 时仍可开启)。 + public bool AutoReconnect { get; set; } = true; + + public int ReconnectAttempt => _reconnectAttempt; + public bool IsReconnecting => State == SessionState.Reconnecting; + public string? LastNotice { get; private set; } + + /// 距离下一次重连尝试的剩余秒数(0 表示正在连接)。供重连遮罩显示倒计时。 + 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) { - while (_pendingStates.TryDequeue(out var state)) - { - 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); - } + DrainQueues(); if (State == SessionState.Connected && Time.GetTicksMsec() >= _nextHeartbeatAt) { @@ -64,6 +91,12 @@ public partial class GameSession : Node ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }); } + + if (_reconnectScheduled && !_reconnectInFlight && Time.GetTicksMsec() >= _nextReconnectAtMs) + { + _reconnectScheduled = false; + _ = AttemptReconnectAsync(); + } } public async Task ConnectAsync( @@ -75,16 +108,14 @@ public partial class GameSession : Node Endpoint = endpoint; _intentionalDisconnect = false; _sequence = 0; + _reconnectAttempt = 0; + _reconnectScheduled = false; + _reconnectInFlight = false; SetState(SessionState.Connecting); - _transport = useMock ? new MockTransport() : new WebSocketTransport(); - _transport.MessageReceived += OnMessageReceived; - _transport.Faulted += OnTransportFaulted; - _transport.Closed += OnTransportClosed; - try { - await _transport.ConnectAsync(endpoint, cancellationToken); + await OpenTransportAsync(endpoint, useMock, cancellationToken); _nextHeartbeatAt = Time.GetTicksMsec() + HeartbeatIntervalMs; _pendingStates.Enqueue(SessionState.Connected); return true; @@ -130,16 +161,48 @@ public partial class GameSession : Node public async Task DisconnectAsync() { _intentionalDisconnect = true; - if (_transport is not null) + _reconnectScheduled = false; + _reconnectInFlight = false; + _reconnectAttempt = 0; + _transportLost = false; + _transportFault = null; + + var transport = _transport; + _transport = null; + if (transport is not null) { - DetachTransport(_transport); - await _transport.DisposeAsync(); - _transport = null; + DetachTransport(transport); + await DisposeQuietlyAsync(transport); } SetState(SessionState.Disconnected); } + /// + /// 强制中断连接(不握手),用于验证断线恢复或清理已卡死的 socket。 + /// 与 的区别:这属于「非计划中断」,会触发自动重连。 + /// + public void AbortConnection() + { + if (_transport is null || _intentionalDisconnect) + { + return; + } + + _transport.Abort(); + } + + /// 跳过当前的退避等待,让下一次重连尝试立刻发生(遮罩上的「立即重连」按钮)。 + public void RequestImmediateReconnect() + { + if (!_reconnectScheduled) + { + return; + } + + _nextReconnectAtMs = Time.GetTicksMsec(); + } + public override void _ExitTree() { 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(string type, T data, CancellationToken cancellationToken = default) { if (_transport is null || !_transport.IsConnected) @@ -174,16 +353,14 @@ public partial class GameSession : Node private void OnMessageReceived(string message) => _incomingMessages.Enqueue(message); - private void OnTransportFaulted(Exception exception) => _incomingErrors.Enqueue(exception); - - private void OnTransportClosed() + private void OnTransportFaulted(Exception exception) { - if (!_intentionalDisconnect) - { - _pendingStates.Enqueue(SessionState.Disconnected); - } + _transportFault = exception; + _transportLost = true; } + private void OnTransportClosed() => _transportLost = true; + private void DetachTransport(IGameTransport transport) { transport.MessageReceived -= OnMessageReceived; @@ -191,6 +368,18 @@ public partial class GameSession : Node transport.Closed -= OnTransportClosed; } + private static async Task DisposeQuietlyAsync(IGameTransport transport) + { + try + { + await transport.DisposeAsync(); + } + catch (Exception) + { + // 旧连接已断,释放失败不影响重连。 + } + } + private void SetState(SessionState state) { if (State == state) @@ -202,4 +391,3 @@ public partial class GameSession : Node EmitSignal(SignalName.StateChanged, (int)state); } } - diff --git a/src/Autoload/GameSettings.cs b/src/Autoload/GameSettings.cs index f213383..4d1b6ee 100644 --- a/src/Autoload/GameSettings.cs +++ b/src/Autoload/GameSettings.cs @@ -7,9 +7,11 @@ public partial class GameSettings : Node private const string MasterVolumeKey = "master_volume"; private const string NetworkSection = "network"; 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 string SoloServerUrl { get; private set; } = "ws://localhost:11030/ws/solo"; + public string SoloServerUrl { get; private set; } = DefaultSoloServerUrl; public override void _Ready() { @@ -17,7 +19,13 @@ public partial class GameSettings : Node if (config.Load(SettingsPath) == Error.Ok) { 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(); diff --git a/src/Contracts/BattleSnapshot.cs b/src/Contracts/BattleSnapshot.cs index 77e9255..e794893 100644 --- a/src/Contracts/BattleSnapshot.cs +++ b/src/Contracts/BattleSnapshot.cs @@ -142,6 +142,8 @@ public sealed record SoloGameState public SoloMapDto? Map { get; init; } public IReadOnlyList Characters { get; init; } = []; public IReadOnlyList Queue { get; init; } = []; + public IReadOnlyDictionary> RoundRewards { get; init; } + = new Dictionary>(); [JsonPropertyName("playerDP")] public SoloDecisionPointsDto? PlayerDp { get; init; } public string? PlayerGuid { get; init; } public string? CurrentActorGuid { get; init; } @@ -166,10 +168,18 @@ public sealed record SoloStartEvent public SoloGameState? State { get; init; } } +/// +/// 服务器对一条挂起决策的最终交代。 +/// 既用于正常回答,也用于「服务器单方面放弃这条决策」(对局结束 / 接管 / 断线)—— +/// 后者让客户端不必靠超时去猜「为什么轮到我却什么都没发生」。 +/// public sealed record SoloResolvedEvent { public string RequestId { get; init; } = string.Empty; public string Kind { get; init; } = string.Empty; + + /// 放弃原因;正常回答时为空。 + public string Reason { get; init; } = string.Empty; } public sealed record SoloOverEvent diff --git a/src/Contracts/DecisionRequest.cs b/src/Contracts/DecisionRequest.cs index a018d0b..1b10280 100644 --- a/src/Contracts/DecisionRequest.cs +++ b/src/Contracts/DecisionRequest.cs @@ -50,6 +50,8 @@ public sealed record TargetOption public double Hp { get; init; } public double MaxHp { get; init; } public long GridId { get; init; } + public bool IsSelf { get; init; } + public bool IsTeammate { get; init; } } public sealed record TargetsPayload @@ -79,6 +81,18 @@ public sealed record ActionTypePayload public IReadOnlyList Teammates { get; init; } = []; public IReadOnlyList EnemyOptions { get; init; } = []; public IReadOnlyList TeammateOptions { get; init; } = []; + + /// + /// 普攻可达目标:严格按 ATR 算出的敌人子集,即「现在不移动就能打到的人」。 + /// 为空 ⇒ 提交普通攻击必然被服务器作废(引擎在选普攻目标前会用同一口径再收窄一次), + /// 客户端应直接禁用按钮,而不是让玩家白提交一轮。 + /// 为 null 表示服务端没有下发该字段(旧版服务端),此时只能退回 + /// 的宽口径(攻击可达 ∪ 施法可达)判断,那是不够精确的必要条件。 + /// + public IReadOnlyList? AttackTargets { get; init; } + + /// 普通攻击是否真的可达,等价于 非空;为 null 表示旧版服务端。 + public bool? CanNormalAttack { get; init; } } public sealed record SkillSelectionPayload diff --git a/src/Diagnostics/PhaseCDecisionSmokeTest.cs b/src/Diagnostics/PhaseCDecisionSmokeTest.cs index 6ceeb56..37be678 100644 --- a/src/Diagnostics/PhaseCDecisionSmokeTest.cs +++ b/src/Diagnostics/PhaseCDecisionSmokeTest.cs @@ -11,9 +11,14 @@ public partial class PhaseCDecisionSmokeTest : Node try { VerifyActionPayload(); + VerifyAttackReachability(); VerifyInquiryPayload(); + VerifyContinuePayload(); + VerifyCancellationDetection(); 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); } catch (Exception exception) @@ -63,6 +68,54 @@ public partial class PhaseCDecisionSmokeTest : Node } } + /// + /// 普攻可达判定必须「优先服务端的严格口径 attackTargets,旧服务端再退回宽口径」—— + /// 反过来(或无脑相信 enemyOptions)就会在「敌人只在施法射程内」时误开放按钮, + /// 让玩家白提交一轮;而完全不回退又会让旧服务端的按钮永久禁用。 + /// + 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() { const string json = """ @@ -81,6 +134,64 @@ public partial class PhaseCDecisionSmokeTest : Node } } + /// + /// Continue 的协议形状静态覆盖:真实对局里是否下发 Continue 取决于服务器流程(需要玩家回合正常结束 + /// 且未被 AI 托管),所以这里独立校验字段与倒计时,真实链路由 SoloVerticalSliceSmokeTest 观察记录。 + /// + private static void VerifyContinuePayload() + { + const string json = """ + {"requestId":"cont-1","kind":"Continue","timeoutMs":30000, + "payload":{"actorGuid":"actor","message":"本回合已结束,查看日志后点击继续. . ."}} + """; + var request = JsonSerializer.Deserialize(json, ProtocolJson.Options) + ?? throw new InvalidOperationException("Continue request could not be deserialized."); + var payload = request.ReadPayload(); + if (request.Kind != SoloDecisionKinds.Continue + || request.TimeoutMs != 30000 + || payload is null + || string.IsNullOrWhiteSpace(payload.Message)) + { + throw new InvalidOperationException("Continue payload fields were not preserved."); + } + } + + /// + /// 服务器对"提交了但不可行"的行动没有拒绝回执,客户端只能靠紧邻的决策类型判断是否被作废。 + /// 这里把这套判定钉死:正常链路不得误报,回到行动菜单才算取消。 + /// + 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() { var map = new SoloMapDto diff --git a/src/Diagnostics/PhaseCDecisionSmokeTest.cs.uid b/src/Diagnostics/PhaseCDecisionSmokeTest.cs.uid new file mode 100644 index 0000000..38f1348 --- /dev/null +++ b/src/Diagnostics/PhaseCDecisionSmokeTest.cs.uid @@ -0,0 +1 @@ +uid://ciew5mtwvhy7u diff --git a/src/Diagnostics/PhaseESmokeTest.cs b/src/Diagnostics/PhaseESmokeTest.cs new file mode 100644 index 0000000..4669d0b --- /dev/null +++ b/src/Diagnostics/PhaseESmokeTest.cs @@ -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; + +/// +/// 阶段 E 的静态自检:快照差分、表现队列行为、HUD 版面。 +/// 不连服务器,纯离线校验表现层规则——真实对局里的表现由 --solo-vertical-smoke-test +/// 与 --solo-reconnect-smoke-test 覆盖。 +/// +public partial class PhaseESmokeTest : Node +{ + private PackedScene _unitViewScene = null!; + private int _skips; + + public override void _Ready() + { + _unitViewScene = GD.Load("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 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 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(); + 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(); + } + + // ==================== 灰盒地面(只画服务器真实存在的格子) ==================== + + /// + /// 地面必须严格由权威地图数据驱动:稀疏地图只画那几个格,不按 Length×Width 铺满, + /// 也不画协议里并不存在的掩体(旧实现硬编码了 4 个掩体)。 + /// + 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("HudLayer/SafeArea/Layout"); + var dock = layout.GetNode("BottomRightActionDock"); + var context = layout.GetNode("BottomContextBar"); + var characterPanel = layout.GetNode("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($"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; + } +} diff --git a/src/Diagnostics/PhaseESmokeTest.cs.uid b/src/Diagnostics/PhaseESmokeTest.cs.uid new file mode 100644 index 0000000..01dd997 --- /dev/null +++ b/src/Diagnostics/PhaseESmokeTest.cs.uid @@ -0,0 +1 @@ +uid://cqfkviv3hgsw2 diff --git a/src/Diagnostics/SoloConnectionSmokeTest.cs b/src/Diagnostics/SoloConnectionSmokeTest.cs index eac0d35..9723bc7 100644 --- a/src/Diagnostics/SoloConnectionSmokeTest.cs +++ b/src/Diagnostics/SoloConnectionSmokeTest.cs @@ -8,6 +8,7 @@ public partial class SoloConnectionSmokeTest : Node private GameSession _session = null!; private BattleStore _store = null!; + public override void _Ready() { _session = GetNode("/root/GameSession"); @@ -19,7 +20,7 @@ public partial class SoloConnectionSmokeTest : Node { try { - var endpoint = new Uri("ws://localhost:11030/ws/solo"); + var endpoint = new Uri("ws://localhost:12030/ws/solo"); if (!await _session.ConnectAsync(endpoint)) { throw new InvalidOperationException("WebSocket connection failed."); @@ -28,7 +29,9 @@ public partial class SoloConnectionSmokeTest : Node await WaitUntilAsync(() => _session.State == SessionState.Connected, 5.0); await _store.StartGameAsync(new SoloStartOptions { - CharacterCount = 2, + // 与客户端默认一致:10 个候选角色 —— 选人弹窗里塞的是最长的详情文本, + // 布局问题(撑出窗口、按钮点不到)必须在这个规模下才能暴露。 + CharacterCount = 10, TeamMode = false, TeamSize = 1, MaxRound = 1, @@ -42,14 +45,13 @@ public partial class SoloConnectionSmokeTest : Node await WaitUntilAsync( () => _store.PendingDecision?.Kind == SoloDecisionKinds.SelectCharacter, 10.0); + await VerifyDecisionDialogFitsAsync(); - var character = _store.PendingDecision! - .ReadPayload()? - .Characters - .FirstOrDefault() - ?? throw new InvalidOperationException("Server returned no selectable characters."); + // 真正「点」一次:选第 2 个候选(故意不选第一个,防止「永远提交第 0 项」这类错), + // 再用真实鼠标事件点确认。这一步是为了覆盖「界面能不能把选择送出去」—— + // 之前的断言只看版面,测试又是直接调 BattleStore 提交,于是确认按钮里的守卫写错也照样全绿。 + await ClickThroughCharacterSelectionAsync(); - await _store.SubmitDecisionAsync(new { characterGuid = character.Guid }); await WaitUntilAsync( () => _store.Snapshot is { GameId.Length: > 0, Characters.Count: > 0 }, 10.0); @@ -58,7 +60,7 @@ public partial class SoloConnectionSmokeTest : Node 5.0); 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} " + $"units={GetTree().GetNodesInGroup("battle_unit").Count}"); @@ -74,6 +76,181 @@ public partial class SoloConnectionSmokeTest : Node } } + /// + /// 决策弹窗必须「看得到、点得到」:整块面板与确认按钮都要落在视口内。 + /// 详情文本是整张角色说明书(几十行),历史上它把没有任何上限的居中弹窗撑到超出窗口, + /// 确认/取消按钮被顶到屏幕外,玩家表现为「弹窗打不开也点不动」。 + /// 现在详情在 ScrollContainer 里滚动、面板按视口比例定位,这条断言就是防它退化。 + /// + private async Task VerifyDecisionDialogFitsAsync() + { + // 容器排版在下一帧才结算。 + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var dialog = GetNode("/root/Main/BattleScreen/OverlayLayer/DecisionDialog"); + if (!dialog.Visible) + { + throw new InvalidOperationException("SelectCharacter 决策没有弹出决策弹窗。"); + } + + var panel = dialog.GetNode("DialogPanel"); + var confirm = dialog.GetNode