using OSM.Client.Autoload; using OSM.Client.Contracts; using OSM.Client.Screens.Battle; namespace OSM.Client.Diagnostics; /// /// 阶段 C 真实 /ws/solo 竖切回归:移动、服务器拒绝恢复、普通攻击,并顺带观察 Continue。 /// 权威服务器原则:客户端不推算射程、合法性或可选目标,只依据服务器下发的内容决策—— /// /// ActionType.enemyOptions / enemys:当前位置「攻击可达 ∪ 施法可达」的敌人 /// (见 GamingQueue 中按 canAttackGrids/canCastGrids 过滤后的 enemys)。列表为空时普通攻击 /// 必然被服务器取消,因此不提交。 /// ActionType.dp.quotas:该行动类型本回合是否还可用(配额 + 决策点)。 /// TargetGrid.gridIds / Targets.targets:唯一合法的格子与目标。 /// /// 服务器对非法提交没有显式回执(gaming.resolved 尚未实现),被作废的行动只能在下一次 /// gaming.request 里看出来:又回到 ActionType 就说明上一个行动无效。所以这里用 /// 「同一回合内不重复提交刚被取消的行动」收敛,而不是让客户端猜距离——重复白提交会撞上服务端防打转 /// 护栏(同类决策连续 4 次 ⇒ 强制 AI 托管并结束回合),连 Continue 一起吃掉。 /// Continue 只记录、不作为通过条件:本局是否真的下发 Continue 取决于该回合是否正常结束且玩家 /// 未被托管;它的协议形状由 静态覆盖。 /// public partial class SoloVerticalSliceSmokeTest : Node { // 移动上限给足:种子固定后抽到的两名角色可能开局离得很远,而回归要求真实走到普攻射程内。 // 收敛由「朝敌人移动 + 敌人也朝你来」保证;服务器拒绝移动时会置 _moveCancelled 提前收手。 private const int MaxSteps = 900; private const int MaxMoves = 80; private const int MaxSettlingSteps = 12; /// 核心路径达成后,再给多少步专门去验证「普攻可达门控」(需要敌人真的走进 ATR)。 private const int MaxGateSettlingSteps = 200; /// 等服务器下发下一条决策的超时(**秒**)。别写成毫秒 —— 写错就是「永远卡住」。 private const double DecisionTimeoutSeconds = 20.0; private const double ShortTimeoutSeconds = 15.0; private const double TotalTimeoutSeconds = 240.0; /// 看门狗上限:超过它无论如何都要退出,并留下原因(否则工具只能 SIGTERM,输出全丢)。 private const double WatchdogSeconds = 300.0; private GameSession _session = null!; private BattleStore _store = null!; private SoloTestDriver _driver = null!; 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 _continueObserved; private int _lastRound = -1; private ulong _deadlineMs; private ulong _nextBeatAtMs; public override void _Ready() { _session = GetNode("/root/GameSession"); _store = GetNode("/root/BattleStore"); _driver = new SoloTestDriver(_store, this); _ = RunAsync(); _ = WatchdogAsync(); } /// /// 心跳:每 2 秒打一行当前状态。 /// 用途是把「主循环整个卡死」和「某个 await 永远不返回」区分开 —— /// 心跳停 = 主循环卡死(SceneTreeTimer 也不会触发);心跳继续 = 主循环活着但 await 链断了。 /// 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}"); } /// /// 看门狗:正常路径很快就能跑完,卡住时不能让进程一直挂着 —— /// 挂死会让工具 SIGTERM,而 Godot 失缓冲的 stdout 到时全丢,只剩「什么都没跑」。 /// 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() { try { _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."); } 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 = 30, // 协议层确认服务端接收 requireContinue;本局是否真的下发 Continue 由服务器流程决定。 RequireContinue = true, RoundDelayMs = 0, DropItemsIntervalSeconds = 0, Seed = 20260919 }); SoloTrace.Step("connected, gaming.start sent, waiting SelectCharacter"); var decision = await _driver.AwaitDecisionAsync(10.0); if (decision.Kind != SoloDecisionKinds.SelectCharacter) { throw new InvalidOperationException($"Expected SelectCharacter, got {decision.Kind}."); } var character = decision.ReadPayload()? .Characters .FirstOrDefault() ?? throw new InvalidOperationException("Server returned no selectable characters."); decision = await _driver.SubmitAndAwaitNextAsync( decision, new { characterGuid = character.Guid }, ShortTimeoutSeconds); await _driver.WaitOrThrowAsync( () => _store.Snapshot is { PlayerGuid.Length: > 0, Characters.Count: > 1, Map: not null }, ShortTimeoutSeconds); await _driver.WaitOrThrowAsync( () => GetTree().GetNodesInGroup("battle_unit").Count == _store.Snapshot!.Characters.Count, 5.0); SoloTrace.Step($"character selected, entering decision loop"); // 用可空局部变量承载「下一轮要处理的决策」:服务器放弃决策时它会变成 null,循环随之收尾。 SoloDecisionRequest? current = decision; var steps = 0; var settling = 0; var gateSettling = 0; while (steps++ < MaxSteps) { if (Time.GetTicksMsec() >= _deadlineMs) { SoloTrace.Step($"SOLO_VERTICAL_DEADLINE reached after {steps} steps"); GD.PushWarning($"SOLO_VERTICAL_DEADLINE reached after {steps} steps."); break; } if (!_store.IsStarted) { // 对局结束(gaming.over)或玩家被服务器托管:不会再有决策下发,收尾评估即可。 SoloTrace.Step($"server stopped asking for decisions after {steps} steps"); break; } if (IsCorePathSatisfied() && (_continueObserved || ++settling > MaxSettlingSteps) && (_attackGateVerified || ++gateSettling > MaxGateSettlingSteps)) { 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) { throw new InvalidOperationException("Vertical slice did not complete a movement."); } if (!_attackSubmitted) { 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) { throw new InvalidOperationException("Vertical slice did not recover from a rejected grid."); } if (_preciseAttackSignal && _attackCancelledCount > 0) { // 服务器下发了严格口径的 attackTargets,却仍有普攻被作废 ⇒ 该信号不可信 throw new InvalidOperationException( $"Server advertised precise attackTargets but {_attackCancelledCount} normal attack(s) were cancelled."); } var okLine = $"SOLO_VERTICAL_OK game={_store.Snapshot!.GameId} moves={_moves} " + "attackTargetSubmitted=true rejectionRecovered=true " + $"attackAttempts={_attackAttempts} attackCancelled={_attackCancelledCount} " + $"attackReachableRounds={_attackTargetsOffered} attackGateVerified={_attackGateVerified} " + $"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.DisconnectAsync(); GetTree().Quit(0); } catch (Exception exception) { // 先写 stderr(不带缓冲),保证即使后面清理步骤卡住、进程被强杀,失败原因也留得下来。 SoloTrace.Step($"SOLO_VERTICAL_FAILED {exception.Message}"); GD.PushError($"SOLO_VERTICAL_FAILED {exception.Message}"); await _session.DisconnectAsync(); GetTree().Quit(1); } } /// /// 处理一条决策;服务器在等待期间不再下发新决策时返回 null(对局结束 / 托管), /// 让循环优雅收尾而不是干等到超时 —— 这类「服务端主动静默」不是客户端故障。 /// private async Task TryHandleDecisionAsync(SoloDecisionRequest decision) { try { return await HandleDecisionAsync(decision); } catch (TimeoutException exception) { SoloTrace.Step($"no further decision from server: {exception.Message}"); return null; } } /// 核心路径:真实移动 + 真实普攻(按服务器给的 Targets)+ 拒绝恢复。 private bool IsCorePathSatisfied() => _moves > 0 && _attackSubmitted && _rejectionRecovered; /// /// 新回合清除「上一回合学到的不可行动作」:服务器每回合重新给一次机会, /// 上一回合的攻击/移动被取消不代表这一回合也不行。 /// private void ResetTurnGuards() { var round = _store.Snapshot?.Round ?? -1; if (round == _lastRound) { return; } _lastRound = round; _attackCancelled = false; _moveCancelled = false; } private async Task 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()?.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()), DecisionTimeoutSeconds); default: // Skill / Item / TargetGrids:本竖切不主动使用,按取消处理,让服务器回到行动菜单。 return await _driver.SubmitAndAwaitNextAsync(decision, new { cancelled = true }, DecisionTimeoutSeconds); } } private async Task HandleActionTypeAsync(SoloDecisionRequest decision) { var payload = decision.ReadPayload(); // 与 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 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++; } return next; } private static object BuildInquiryReply(InquiryPayload? payload) { if (payload is null || payload.CanCancel) { return new { cancel = true }; } if (!string.IsNullOrEmpty(payload.DefaultChoice)) { return new { choices = new[] { payload.DefaultChoice } }; } if (payload.Choices.Count > 0) { return new { choices = new[] { payload.Choices[0].Key } }; } return new { number = payload.DefaultNumber }; } }