Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions autowsgr/combat/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ Tracking JSON 不存在时自动读取旧 YAML 坐标。缺少敌情、迂回属
未知字段不会补成终点、空白点或不可迂回。缺少类型或路由时不按战斗次数推进节点,
仍无法确认当前位置时继续执行未知节点的撤退、SL 或回港处理。

能否迂回由融合确认节点的地图属性决定,按钮模板漏检不再阻止迂回;只有旧 YAML
活动图缺少该属性时才回退按钮识别,节点资料与画面冲突时按节点处理并输出告警。

相关自动测试集中在 [`testing/combat/node_fusion/`](../../testing/combat/node_fusion/)。
完整回放默认关闭,配置 `log.node_fusion_replay: true` 后保存地图快照及逐帧观测。
每趟结束仍输出简短的识别核对统计和运行累计;回放时核对指纹,避免换图。
Expand Down
65 changes: 54 additions & 11 deletions autowsgr/combat/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -88,6 +89,7 @@ class PhaseHandlersMixin:
_node_count: int
_formation_by_rule: Formation | None
_recognizer: CombatRecognizer
_tracking: TrackingSession | None
"""

# 类型提示 (供 IDE/mypy 在 Mixin 上下文使用)
Expand All @@ -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:
"""根据当前状态做出决策并执行操作。
Expand Down Expand Up @@ -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()
Expand All @@ -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

# 阵型规则优先
Expand Down Expand Up @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions autowsgr/combat/node_fusion/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ NULL、REWARD、LOSS 可以静默经过,几何证据按真实航段逐段评
作为缺失证据。整帧异常项保留相关误识别的可能;重复读取只更新同一遭遇的聚合因子,
不按轮询次数连乘。每次真实迂回点击仅分配一次结果先验。

能否迂回以融合确认节点的地图 `detour` 属性为准,截图的迂回按钮只作为敌情证据参与定位,
不再决定是否点击:按钮漏检不会让可迂回节点被当成不可迂回。只有资料没有记录该属性
(例如仅有旧 YAML 坐标的活动图)时才回退按钮识别;节点资料与画面冲突时按节点处理,
并在战斗日志中输出反馈告警。

模型默认参数集中在 `FusionProfile`。舰类/阵型正确识别率初值 0.9、整帧异常权重 0.1
都尚待校准,输出权重不是实测正确率。普通地图按已验证的一秒航行下限约束:匹配帧在
实际迂回点击后不足 0.95 秒出现时排除下一遭遇;更晚出现不直接证明迂回成功。活动图

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

该变更为文档说明,无实际代码逻辑,但作为评审,指出以下可改进点:

  1. 表述存在潜在歧义:文档称“按钮漏检不会让可迂回节点被当成不可迂回”,但后半段又允许“仅有旧 YAML 坐标的活动图”回退按钮识别,此时若按钮漏检仍可能导致误判。建议明确该结论仅适用于节点资料包含 detour 属性的情况,或补充说明回退场景下的兜底策略。

  2. “节点资料与画面冲突”未定义:未说明冲突的具体判定标准(例如按钮显示与资料属性不一致、坐标偏移等),建议补充明确冲突的触发条件,便于实现和测试。

  3. 建议增加操作记录维度:文档提到输出反馈告警,但未说明告警级别、频率限制或是否会影响后续流程。建议补充告警的触发阈值和使用方式,避免过度刷屏或掩盖真实问题。

其余内容无实质性错误,逻辑与现有设计兼容。

Expand Down
16 changes: 16 additions & 0 deletions autowsgr/combat/node_fusion/integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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}')
Expand Down
8 changes: 5 additions & 3 deletions docs/architecture/combat-engine.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()` | 等待战斗结束 + 血量分类 |
Expand Down Expand Up @@ -388,7 +388,8 @@ class CombatResult:
MAP 模式由 `TrackingSession` 采集带解码帧号和单调时间的船位、页面、敌情和操作,
交给 `FusionTracker` 进行前向计算、Viterbi 回溯及后向平滑;完整地图资料约束合法路线。
距离、射线、敌情、历史路线约束和最终结果分别写入调试日志。融合确认的当前节点
是唯一决策来源,航段的预测目的点不等于已经到达。
是唯一决策来源,航段的预测目的点不等于已经到达。能否迂回同样取该节点的地图属性,
索敌截图的按钮只作为定位证据;只有地图没有记录该属性时才回退按钮识别。

决战通过小关级会话接入同一个模型,跨多次 `run_combat()` 保留历史。场景策略分别
处理普通/活动路线与决战固定推进,证据模块输出各候选的对数因子;历史和固定推进
Expand All @@ -403,7 +404,8 @@ MAP 模式由 `TrackingSession` 采集带解码帧号和单调时间的船位、
融合模型按资料自动启用可用部分。缺敌情或迂回属性仅省略相应节点的证据;缺起点、
节点类型或路由时,使用几何和已有敌情定位,不根据战斗次数推进。完整路由仍能约束
可达范围,缺路由则不采用拓扑硬约束。每次出征输出一次降级 WARNING,说明来源、
缺失项及受限能力。推断异常或证据不足、歧义无法消除时,当前位置才保持未知。
缺失项及受限能力。缺少迂回属性只影响该节点的资料证据,战斗决策仍回退按钮识别,
不会把未知当成不可迂回。推断异常或证据不足、歧义无法消除时,当前位置才保持未知。

底层设备仅提供通用帧元数据;融合状态、兼容策略、错误处理和日志都放在独立模块中。
完整标量回放日志默认关闭,由 `log.node_fusion_replay: true` 开启。启用后冻结地图
Expand Down
113 changes: 113 additions & 0 deletions testing/combat/node_fusion/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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')
Expand Down Expand Up @@ -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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

以下是审核结果:

  • 兼容性问题:make_engine 新增参数 map_detour 默认值为 True,可能破坏现有测试/行为
    修改前 engine._tracking.map_data 未设置(或为 None),默认情况下 detour_available 应返回 None,即“未知”。修改后,所有未显式传 map_detour 的调用都会得到 detour_map(True),节点属性变为“可迂回”,这会改变既有决策逻辑(例如绕过按钮检测直接点击)。建议将默认值改为 None(或与旧行为一致),显式传入 True/False 时才启用新逻辑。

  • 测试用例存在不稳定因素:test_node_detour_true_warns_when_button_not_detected 与 test_node_detour_false_overrides_detected_button_and_warns 未 mock image_exist
    这两个测试依赖 image_exist 的真实执行结果来触发告警分支,但测试环境中的 frame 是否包含按钮模板并不确定,可能导致测试结果受外部环境影响。建议像其他测试一样,用 MagicMock(return_value=False)(或根据需要)显式 mock image_exist,保证测试确定性。

  • 类型注解 bool | None 需要 Python 3.10+,需确认项目支持版本
    新增代码中的 detour: bool | None、map_detour: bool | None 使用了 PEP 604 联合类型语法。若项目最低 Python 版本低于 3.10,应改用 Optional[bool] 或添加 from __future__ import annotations。

  • detour_map 函数未对 node == '0' 做保护,可能产生键冲突
    当 node 传入 '0' 时,raw 字典中 '0' 键会被后写的节点定义覆盖,导致地图数据错误。虽然是测试辅助函数,但建议在函数开头断言 node != '0',或补充文档说明约定。

  • 其他建议

    • detour_map 中 raw 的类型标注使用了 dict[str, object],可进一步细化,但影响不大。
    • 新增测试覆盖了主要场景,且命名清晰,整体方向合理;但需注意上述兼容性与稳定性问题。

Expand Down
Loading