From 54085c3df58a358dda5e71bfac637c9e0fe3f392 Mon Sep 17 00:00:00 2001 From: KUAI Date: Sat, 21 Nov 2026 16:02:11 +0800 Subject: [PATCH] =?UTF-8?q?fix(combat):=20=E8=BF=82=E5=9B=9E=E5=88=A4?= =?UTF-8?q?=E5=AE=9A=E6=94=B9=E4=B8=BA=E8=8A=82=E7=82=B9=E5=9C=B0=E5=9B=BE?= =?UTF-8?q?=E5=B1=9E=E6=80=A7=E4=BC=98=E5=85=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TrackingSession 保存已加载地图并提供 detour_available 查询 - 索敌页能否迂回取融合确认节点的 detour 属性,按钮漏检不再阻止迂回 - 旧 YAML 活动图缺少该属性时回退原有按钮识别,未知不等同不可迂回 - 节点资料与画面冲突时按节点处理并输出反馈告警 - 规则指定迂回但与节点冲突时,异常信息补充节点与判定来源 --- autowsgr/combat/README.md | 3 + autowsgr/combat/handlers.py | 65 ++++++++++-- autowsgr/combat/node_fusion/README.md | 5 + autowsgr/combat/node_fusion/integration.py | 16 +++ docs/architecture/combat-engine.md | 8 +- testing/combat/node_fusion/test_session.py | 113 +++++++++++++++++++++ 6 files changed, 196 insertions(+), 14 deletions(-) diff --git a/autowsgr/combat/README.md b/autowsgr/combat/README.md index cc8fb56f..9c6d33a3 100644 --- a/autowsgr/combat/README.md +++ b/autowsgr/combat/README.md @@ -205,6 +205,9 @@ Tracking JSON 不存在时自动读取旧 YAML 坐标。缺少敌情、迂回属 未知字段不会补成终点、空白点或不可迂回。缺少类型或路由时不按战斗次数推进节点, 仍无法确认当前位置时继续执行未知节点的撤退、SL 或回港处理。 +能否迂回由融合确认节点的地图属性决定,按钮模板漏检不再阻止迂回;只有旧 YAML +活动图缺少该属性时才回退按钮识别,节点资料与画面冲突时按节点处理并输出告警。 + 相关自动测试集中在 [`testing/combat/node_fusion/`](../../testing/combat/node_fusion/)。 完整回放默认关闭,配置 `log.node_fusion_replay: true` 后保存地图快照及逐帧观测。 每趟结束仍输出简短的识别核对统计和运行累计;回放时核对指纹,避免换图。 diff --git a/autowsgr/combat/handlers.py b/autowsgr/combat/handlers.py index 95d9ef72..dd41426e 100644 --- a/autowsgr/combat/handlers.py +++ b/autowsgr/combat/handlers.py @@ -44,6 +44,7 @@ if TYPE_CHECKING: from autowsgr.combat.node_fusion.enemy import EnemyObservation + from autowsgr.combat.node_fusion.integration import TrackingSession from autowsgr.combat.recognizer import CombatRecognizer from autowsgr.emulator import AndroidController from autowsgr.vision import OCREngine @@ -88,6 +89,7 @@ class PhaseHandlersMixin: _node_count: int _formation_by_rule: Formation | None _recognizer: CombatRecognizer + _tracking: TrackingSession | None """ # 类型提示 (供 IDE/mypy 在 Mixin 上下文使用) @@ -101,6 +103,7 @@ class PhaseHandlersMixin: _recognizer: CombatRecognizer _node_count: int _formation_by_rule: Formation | None + _tracking: TrackingSession | None def _make_decision(self, phase: CombatPhase) -> ConditionFlag: """根据当前状态做出决策并执行操作。 @@ -200,15 +203,53 @@ def _click_detour_with_timestamp(self) -> tuple[bool, float]: self._device, lambda device: click_image(device, TemplateKey.BYPASS, 2.5) ) + def _detour_capability(self, evidence: EnemyObservation | None) -> tuple[bool, str]: + """能否迂回:节点地图属性优先,资料缺失时才回退按钮识别。 + + 返回 ``(能否迂回, 判定来源)``,来源为 ``'node'`` 或 ``'image'``。 + 只有旧 YAML 坐标的活动图没有迂回属性,此时保持原有截图判定, + 不把未知属性当成不可迂回。 + """ + if self._tracking is not None: + attribute = self._tracking.detour_available(self._node) + if attribute is not None: + self._log_node_detour(attribute, evidence) + return attribute, 'node' + detected = ( + evidence.detour + if evidence is not None + else image_exist(self._device, TemplateKey.BYPASS, 0.8) + ) + return bool(detected), 'image' + + def _log_node_detour(self, available: bool, evidence: EnemyObservation | None) -> None: + """节点资料是唯一判据;与画面冲突时留痕供地图维护反馈。""" + _log.debug('[Combat] 节点 {} 地图迂回属性: {}', self._node, available) + if evidence is None: + return + if not available and evidence.detour: + _log.warning( + '[Combat] 节点 {} 地图标记为不可迂回, 但画面存在迂回按钮; ' + '已按节点资料处理, 请反馈该地图', + self._node, + ) + elif available and not evidence.detour: + _log.warning( + '[Combat] 节点 {} 地图标记为可迂回, 但画面未检测到迂回按钮; ' + '已按节点资料处理, 请反馈该地图', + self._node, + ) + def _handle_spot_enemy(self) -> ConditionFlag: # noqa: PLR0912 """处理索敌成功 — 核心决策节点。 决策顺序: 1. 采集敌方编成和阵型 2. 检查节点是否在白名单中 - 3. 检查阵型规则 (formation_rules) - 4. 检查敌舰规则 (enemy_rules) - 5. 根据结果执行: 撤退 / 迂回 / 设置阵型 / 进入战斗 + 3. 解析迂回能力 (节点地图属性优先, 缺失时回退按钮识别) + 4. 检查阵型规则 (formation_rules) + 5. 检查敌舰规则 (enemy_rules) + 6. 根据结果执行: 撤退 / 迂回 / 设置阵型 / 进入战斗 """ # ── 信息采集 ── enemies, enemy_formation, evidence = self._collect_spot_evidence() @@ -234,12 +275,8 @@ def _handle_spot_enemy(self) -> ConditionFlag: # noqa: PLR0912 ) return ConditionFlag.FIGHT_END - # 检查迂回按钮是否可用 - can_detour = ( - evidence.detour - if evidence is not None - else image_exist(self._device, TemplateKey.BYPASS, 0.8) - ) + # 能否迂回由已确认节点的地图属性决定,不再依赖按钮模板是否命中。 + can_detour, detour_source = self._detour_capability(evidence) want_detour = can_detour and decision.detour # 阵型规则优先 @@ -272,8 +309,14 @@ def _handle_spot_enemy(self) -> ConditionFlag: # noqa: PLR0912 if rule_action.result == RuleResult.DETOUR: if not can_detour: - _log.error('[Combat] 规则指定迂回, 但该点无法迂回') - raise ValueError('该点无法迂回, 但在规则中指定了迂回') + _log.error( + '[Combat] 规则指定迂回, 但节点 {} 判定为不可迂回 (来源={})', + self._node, + detour_source, + ) + raise ValueError( + f'节点 {self._node} 不可迂回 (来源={detour_source}), 但在规则中指定了迂回' + ) want_detour = True if rule_action.result == RuleResult.FORMATION and rule_action.formation: diff --git a/autowsgr/combat/node_fusion/README.md b/autowsgr/combat/node_fusion/README.md index 60580f4d..406e96e3 100644 --- a/autowsgr/combat/node_fusion/README.md +++ b/autowsgr/combat/node_fusion/README.md @@ -48,6 +48,11 @@ NULL、REWARD、LOSS 可以静默经过,几何证据按真实航段逐段评 作为缺失证据。整帧异常项保留相关误识别的可能;重复读取只更新同一遭遇的聚合因子, 不按轮询次数连乘。每次真实迂回点击仅分配一次结果先验。 +能否迂回以融合确认节点的地图 `detour` 属性为准,截图的迂回按钮只作为敌情证据参与定位, +不再决定是否点击:按钮漏检不会让可迂回节点被当成不可迂回。只有资料没有记录该属性 +(例如仅有旧 YAML 坐标的活动图)时才回退按钮识别;节点资料与画面冲突时按节点处理, +并在战斗日志中输出反馈告警。 + 模型默认参数集中在 `FusionProfile`。舰类/阵型正确识别率初值 0.9、整帧异常权重 0.1 都尚待校准,输出权重不是实测正确率。普通地图按已验证的一秒航行下限约束:匹配帧在 实际迂回点击后不足 0.95 秒出现时排除下一遭遇;更晚出现不直接证明迂回成功。活动图 diff --git a/autowsgr/combat/node_fusion/integration.py b/autowsgr/combat/node_fusion/integration.py index 68ac138a..b68e591c 100644 --- a/autowsgr/combat/node_fusion/integration.py +++ b/autowsgr/combat/node_fusion/integration.py @@ -110,6 +110,7 @@ class TrackingSession: def __init__(self) -> None: self.tracker: FusionTracker | None = None + self.map_data: TrackingMap | None = None self.detector = ShipPositionDetector() self.log_path: Path | None = None self._last_result: NodeEstimate | None = None @@ -137,6 +138,20 @@ def current_node(self) -> str: return '0' return self._decision_estimate.current_node or '0' + def detour_available(self, node: str | None = None) -> bool | None: + """节点地图声明的迂回属性,供战斗决策使用。 + + 只读取已加载的地图快照,不根据画面按钮改判:未知节点、未加载地图或 + 资料缺少该字段时返回 ``None``,由调用方自行降级(例如回退按钮识别)。 + """ + if self.tracker is None or self.map_data is None: + return None + name = self.current_node if node is None else node + if name == '0': + return None + node_data = self.map_data.nodes.get(name) + return None if node_data is None else node_data.detour + @classmethod def start( cls, @@ -174,6 +189,7 @@ def start( min_travel_seconds=1.0 if plan.mode == CombatMode.NORMAL else None ) session.tracker = FusionTracker(metadata, profile) + session.map_data = metadata session._history_tracker = session.tracker except Exception as exc: session.fail(f'初始化失败: {type(exc).__name__}: {exc}') diff --git a/docs/architecture/combat-engine.md b/docs/architecture/combat-engine.md index fdcbdb27..037fa2b4 100644 --- a/docs/architecture/combat-engine.md +++ b/docs/architecture/combat-engine.md @@ -248,7 +248,7 @@ nodes: | DOCK_FULL | `_handle_dock_full()` | 返回 DOCK_FULL flag | | PROCEED | `_handle_proceed()` | 检查修理需求 → 继续 / 回港 | | FIGHT_CONDITION | `_handle_fight_condition()` | 选择战况 | -| SPOT_ENEMY_SUCCESS | `_handle_spot_enemy()` | 识别敌方 → 规则引擎 → 战/迂回/撤退 | +| SPOT_ENEMY_SUCCESS | `_handle_spot_enemy()` | 识别敌方 → 规则引擎 → 战/迂回/撤退 (迂回取节点属性) | | FORMATION | `_handle_formation()` | 选择阵型 (规则优先 → 默认) | | MISSILE_ANIMATION | `_handle_missile_animation()` | 跳过或等待 | | FIGHT_PERIOD | `_handle_fight_period()` | 等待战斗结束 + 血量分类 | @@ -388,7 +388,8 @@ class CombatResult: MAP 模式由 `TrackingSession` 采集带解码帧号和单调时间的船位、页面、敌情和操作, 交给 `FusionTracker` 进行前向计算、Viterbi 回溯及后向平滑;完整地图资料约束合法路线。 距离、射线、敌情、历史路线约束和最终结果分别写入调试日志。融合确认的当前节点 -是唯一决策来源,航段的预测目的点不等于已经到达。 +是唯一决策来源,航段的预测目的点不等于已经到达。能否迂回同样取该节点的地图属性, +索敌截图的按钮只作为定位证据;只有地图没有记录该属性时才回退按钮识别。 决战通过小关级会话接入同一个模型,跨多次 `run_combat()` 保留历史。场景策略分别 处理普通/活动路线与决战固定推进,证据模块输出各候选的对数因子;历史和固定推进 @@ -403,7 +404,8 @@ MAP 模式由 `TrackingSession` 采集带解码帧号和单调时间的船位、 融合模型按资料自动启用可用部分。缺敌情或迂回属性仅省略相应节点的证据;缺起点、 节点类型或路由时,使用几何和已有敌情定位,不根据战斗次数推进。完整路由仍能约束 可达范围,缺路由则不采用拓扑硬约束。每次出征输出一次降级 WARNING,说明来源、 -缺失项及受限能力。推断异常或证据不足、歧义无法消除时,当前位置才保持未知。 +缺失项及受限能力。缺少迂回属性只影响该节点的资料证据,战斗决策仍回退按钮识别, +不会把未知当成不可迂回。推断异常或证据不足、歧义无法消除时,当前位置才保持未知。 底层设备仅提供通用帧元数据;融合状态、兼容策略、错误处理和日志都放在独立模块中。 完整标量回放日志默认关闭,由 `log.node_fusion_replay: true` 开启。启用后冻结地图 diff --git a/testing/combat/node_fusion/test_session.py b/testing/combat/node_fusion/test_session.py index 9da9daa8..f3d68c46 100644 --- a/testing/combat/node_fusion/test_session.py +++ b/testing/combat/node_fusion/test_session.py @@ -138,12 +138,24 @@ def map_decision_session( return session +def detour_map(detour: bool | None, node: str = 'Z') -> TrackingMap: + """最小地图:入口 0 与单个战斗节点;``detour=None`` 模拟旧 YAML 缺该属性。""" + raw: dict[str, dict[str, object]] = { + '0': {'position': [0.1, 0.2], 'next': [node], 'type': 'NULL'}, + node: {'position': [0.5, 0.2], 'next': [], 'type': 'FIGHT'}, + } + if detour is not None: + raw[node]['detour'] = detour + return TrackingMap.from_dict(raw) + + def make_engine( frame: CapturedFrame, tmp_path: Path, *, single: bool = False, detour: bool = False, + map_detour: bool | None = True, record_replay: bool = False, ) -> CombatEngine: context = SimpleNamespace( @@ -165,6 +177,7 @@ def make_engine( if not single: engine._tracking = TrackingSession() engine._tracking.tracker = RecordingFusion() + engine._tracking.map_data = detour_map(map_detour) if record_replay: engine._tracking.log_path = tmp_path / 'tracking.jsonl' engine._tracking.detector = MagicMock(detection_status='no_cluster') @@ -291,6 +304,106 @@ def click(device: AndroidController, *_args: object) -> bool: assert engine._tracking.current_node == ('0' if clicked else 'Z') +def test_detour_available_reads_node_attribute_and_keeps_unknown_none() -> None: + """会话只报告地图资料;未加载、未确认或缺少字段一律返回 None。""" + session = TrackingSession() + assert session.detour_available('Z') is None + session.tracker = RecordingFusion() + session.map_data = detour_map(True) + assert session.detour_available('Z') is True + assert session.detour_available('0') is None + assert session.detour_available('missing') is None + session._decision_estimate = estimate('Z') + assert session.detour_available() is True + session.map_data = detour_map(None) + assert session.detour_available('Z') is None + + +def test_node_detour_ignores_missing_button_detection( + monkeypatch: pytest.MonkeyPatch, + frame: CapturedFrame, + evidence: EnemyObservation, + tmp_path: Path, +) -> None: + """节点属性可迂回时,按钮模板未检出不再阻止迂回。""" + engine = make_engine(frame, tmp_path, detour=True, map_detour=True) + monkeypatch.setattr(integration_module, 'observe_enemy', lambda *_a, **_k: evidence) + monkeypatch.setattr( + handlers_module, 'image_exist', MagicMock(side_effect=AssertionError('应使用节点属性')) + ) + click = MagicMock(return_value=True) + monkeypatch.setattr(handlers_module, 'click_image', click) + monkeypatch.setattr(handlers_module, 'wait_leave_page', MagicMock(return_value=frame.image)) + engine._make_decision(CombatPhase.SPOT_ENEMY_SUCCESS) + click.assert_called_once() + assert engine._tracking.tracker.observations[-1].action == 'detour' + + +def test_node_detour_true_warns_when_button_not_detected( + monkeypatch: pytest.MonkeyPatch, + frame: CapturedFrame, + evidence: EnemyObservation, + tmp_path: Path, +) -> None: + """地图标记可迂回但画面未检测到按钮时,保留反向冲突的反馈告警。""" + engine = make_engine(frame, tmp_path, detour=True, map_detour=True) + monkeypatch.setattr(integration_module, 'observe_enemy', lambda *_a, **_k: evidence) + warning = MagicMock() + monkeypatch.setattr(handlers_module._log, 'warning', warning) + click = MagicMock(return_value=True) + monkeypatch.setattr(handlers_module, 'click_image', click) + monkeypatch.setattr(handlers_module, 'wait_leave_page', MagicMock(return_value=frame.image)) + engine._make_decision(CombatPhase.SPOT_ENEMY_SUCCESS) + click.assert_called_once() + messages = [call.args[0] for call in warning.call_args_list] + assert any('可迂回' in message and '未检测到' in message for message in messages) + + +def test_node_detour_false_overrides_detected_button_and_warns( + monkeypatch: pytest.MonkeyPatch, + frame: CapturedFrame, + evidence: EnemyObservation, + tmp_path: Path, +) -> None: + """地图标记不可迂回时不点击,并保留画面与资料不一致的反馈信息。""" + engine = make_engine(frame, tmp_path, detour=True, map_detour=False) + monkeypatch.setattr( + integration_module, 'observe_enemy', lambda *_a, **_k: replace(evidence, detour=True) + ) + click = MagicMock() + enter = MagicMock() + warning = MagicMock() + monkeypatch.setattr(handlers_module, 'click_image', click) + monkeypatch.setattr(handlers_module, 'click_enter_fight', enter) + monkeypatch.setattr(handlers_module._log, 'warning', warning) + engine._make_decision(CombatPhase.SPOT_ENEMY_SUCCESS) + click.assert_not_called() + enter.assert_called_once() + messages = [call.args[0] for call in warning.call_args_list] + assert any('不可迂回' in message and '反馈' in message for message in messages) + assert engine._last_action == 'fight' + assert engine._tracking.tracker.observations[-1].action == 'fight' + + +def test_missing_node_detour_falls_back_to_button_detection( + monkeypatch: pytest.MonkeyPatch, + frame: CapturedFrame, + tmp_path: Path, +) -> None: + """旧活动图没有迂回属性且本次未采到敌情时,仍按截图按钮决定。""" + engine = make_engine(frame, tmp_path, detour=True, map_detour=None) + monkeypatch.setattr(integration_module, 'observe_enemy', lambda *_a, **_k: None) + monkeypatch.setattr(handlers_module, 'get_enemy_info', MagicMock(return_value={'DD': 6})) + monkeypatch.setattr(handlers_module, 'get_enemy_formation', MagicMock(return_value='复纵阵')) + monkeypatch.setattr(handlers_module, 'image_exist', MagicMock(return_value=True)) + click = MagicMock(return_value=True) + monkeypatch.setattr(handlers_module, 'click_image', click) + monkeypatch.setattr(handlers_module, 'wait_leave_page', MagicMock(return_value=frame.image)) + engine._make_decision(CombatPhase.SPOT_ENEMY_SUCCESS) + click.assert_called_once() + assert engine._tracking.tracker.observations[-1].action == 'detour' + + def test_click_time_proxy_keeps_shared_click_interface( monkeypatch: pytest.MonkeyPatch, frame: CapturedFrame ) -> None: