Compare commits
5
Commits
main
..
5fdb9fd221
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5fdb9fd221 | ||
|
|
1aa823ea2e | ||
|
|
c4a42bcfaf | ||
|
|
58cd78cd9c | ||
|
|
13c038a175 |
@@ -98,7 +98,8 @@ $env:LCP_DRIVER_TRACE = "$env:USERPROFILE\lc_mcp\driver-input.log"
|
||||
模拟器不接管;拖拽、滚动、键盘以及 MCP 的独立 `click` 工具仍使用原后端。
|
||||
当前回归验证覆盖软件接线和异常处理,DLL、实际驱动及游戏响应需在 Windows 实机核验。
|
||||
|
||||
任务运行期间按 **F12** 急停,可用 `LCP_KILL_KEY` 改成 `f11`、`pause` 等键名。
|
||||
任务运行期间按 **End** 急停,可用 `LCP_KILL_KEY` 改成 `pause`、`scrolllock` 等键名。
|
||||
不要用 F12(Steam 截图键);监听用 `GetAsyncKeyState` 轮询,因为 pynput 钩子在该机器的会话里收不到按键。
|
||||
急停会终止任务子进程,保留游戏窗口;`task_status` 返回 `stopped`、退出码 `130`。
|
||||
刷取循环检测到用户停止后结束本轮,不再导航、升级或重试。急停前会尝试释放驱动
|
||||
按住的鼠标按钮,清理超过 250 毫秒仍强制退出;硬退出留下的临时配置恢复文件由
|
||||
@@ -108,6 +109,13 @@ $env:LCP_DRIVER_TRACE = "$env:USERPROFILE\lc_mcp\driver-input.log"
|
||||
|
||||
## 工具
|
||||
|
||||
MCP 初始化说明与工具描述均指导 AI 优先使用 AALC:常规日常、领奖、普通镜牢按
|
||||
`task_status` → `run_task` → 轮询 `task_status` 执行。只刷经验本时显式传 `thread: 0`,
|
||||
只刷纽本时传 `exp: 0`,避免沿用另一项配置。主线、特殊速通路线或故障恢复使用逐步输入。
|
||||
只看状态或截图不会启动任务;`all` 只用于明确要求全部任务,`enkephalin` 需要明确授权花狂气。
|
||||
启动成功不等于完成,最终还要检查 `errors` 和 `pending_restore`,用户停止后不自动重跑。
|
||||
更新后重启常驻服务并重连 MCP,客户端才能获取新的初始化说明和工具描述。
|
||||
|
||||
| 工具 | 说明 |
|
||||
|------|------|
|
||||
| `get_state` | 截图 + OCR,返回窗口内全部文字 `{text,x,y,w,h,score}` |
|
||||
@@ -137,14 +145,21 @@ $env:LCP_DRIVER_TRACE = "$env:USERPROFILE\lc_mcp\driver-input.log"
|
||||
|
||||
### 任务进程里的保护
|
||||
|
||||
`run_task` 启动的任务子进程在调用 AALC 之前会做三件事,都不改 `vendor/aalc` 源码:
|
||||
`run_task` 启动的任务子进程会做以下处理,都不改 `vendor/aalc` 源码:
|
||||
|
||||
- **配置预检**:发现下列问题就直接拒绝启动(退出码 3,原因写在 `errors` 里):
|
||||
- 镜牢队伍的 `sinner_order` 全是 0:这会让 AALC 选出空队伍,然后无限重试编队;
|
||||
- 镜牢队列为空,或队列里没有适用当前难度的队伍(按"固定用途"判断):AALC 会一局不打就以 0 退出;
|
||||
- `set_lunacy_to_enkephalin` 不为 0:体力不足时会花狂气换体力。确需使用时设 `LCP_ALLOW_LUNACY=1`;
|
||||
- `set_win_size` 加上标题栏后放不进当前桌面:窗口会被压扁成非 16:9。
|
||||
- 自动设置窗口时,目标尺寸放不进当前桌面:窗口会被压扁成非 16:9。
|
||||
`free` 位置计入标题栏,自动定位的无边框窗口只计客户区;`set_windows: false` 跳过此项。
|
||||
- **队伍名精确匹配**:AALC 按子串找队伍,`TEAMS #1` 会命中 `TEAMS #10`。补丁要求编号完全相同。
|
||||
- **窗口比例守护**:每 15 秒检查一次客户区。RDP 重连后窗口被拉伸时,自动调回 `set_win_size` 对应的 16:9 尺寸。
|
||||
- **HDR 提示**:`all` 任务检测到 HDR 时记录警告并继续,不等待 GUI 确认。
|
||||
- **镜牢完成核对**:监听 AALC 的镜牢进度信号统计实际完成局数。少于应打局数时记一条 `[ERROR]`
|
||||
并以退出码 4 结束,`task_status` 显示 `failed`;AALC 正常返回不再被当成打完。
|
||||
- **指定次数**:`mirror` 传 `count` 时本次临时关闭 `infinite_dungeons`(开着时 AALC 会把次数改成 9999),
|
||||
原值和次数一起写入恢复文件,结束或被强杀后都会写回。
|
||||
|
||||
## 无人值守
|
||||
|
||||
@@ -174,11 +189,16 @@ powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Every
|
||||
|
||||
看历史:`python scripts/modules_status.py`
|
||||
|
||||
合成脚本与 `run_task` 子进程通过 `~/lc_mcp/game.lock` 互斥,锁一直保持到操作和关闭游戏结束。
|
||||
已有任务占用时,后来启动的一方报告失败;合成脚本无法确认任务状态时也会退出,不接管游戏。
|
||||
进程退出后锁由系统释放,文件保留,无需手动删除。
|
||||
|
||||
**⚠️ 挂机值守前先读 [`docs/WATCH.md`](docs/WATCH.md)** —— 那里记着环境事实、
|
||||
界面坐标、狂气的三道防线、六种已知失败模式及处置,以及几条踩过的坑
|
||||
(比如 OCR 会把 `LUNACY` 读成 `UNACY`,曾让整条狂气防线静默失效)。
|
||||
|
||||
`scripts/levelup.py` 和 `auto_cycle.py` 里的坐标都按 1600×900 客户区书写,运行时会按实际客户区大小缩放。
|
||||
`levelup.py card`、`weakest` 和 `progress` 带 `--uptie` 时,同步失败会返回非零退出码。
|
||||
|
||||
## 环境变量
|
||||
|
||||
@@ -188,7 +208,7 @@ powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Every
|
||||
| `LCP_PORT` | 8765 | 服务/bridge 端口 |
|
||||
| `LCP_KEEP_SHOTS` | 30 | 截图保留张数 |
|
||||
| `LCP_ALLOW_LUNACY` | 未设置 | 设为 `1` 时允许预检放行 `set_lunacy_to_enkephalin` 不为 0 的配置 |
|
||||
| `LCP_KILL_KEY` | `f12` | 任务子进程的急停键,如 `f11` / `pause` |
|
||||
| `LCP_KILL_KEY` | `end` | 任务子进程的急停键,如 `pause` / `scrolllock`;认不出的键名会报错而不是换成默认键 |
|
||||
| `LC_PY` | 当前解释器 | `levelup.py`/`auto_cycle.py` 调用 MCP 用的 Python |
|
||||
|
||||
## 开发 / 测试
|
||||
@@ -232,18 +252,40 @@ vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\mcp_probe.py find_image '{"
|
||||
|
||||
## Jev 镜牢执行器与真实反馈
|
||||
|
||||
`scripts/jev_mirror_agent.py` 通过 MCP bridge 操作游戏,普通分支经统一接口交给 Jev 或执行模型;战斗采用 P → 回车宏,事件先 SKIP,回车失效时使用当前按钮。它保留用户已配好的队伍,商店无可替换出战角色时至多刷新 4 次,加载期间不读取旧库存继续操作。
|
||||
`scripts/jev_mirror_agent.py` 的 `--workflow auto` 默认把普通镜牢交给 AALC。
|
||||
没有配置、决策模型要求或未完成速通记录时,先查 `task_status`,空闲后调用
|
||||
`run_task({"task":"mirror","count":1})`,随即返回 `delegated` 和后续监控调用。
|
||||
调用方继续轮询 `task_status`;脚本退出不代表通关。已有镜牢任务时返回 `monitoring`,
|
||||
其他任务占用、用户停止、报错或状态不明时不会自动抢占或重试。
|
||||
|
||||
```powershell
|
||||
# 普通镜牢:默认转交 AALC,不需要 Jev 配置
|
||||
vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py
|
||||
# 明确启动新任务;先前有用户停止或失败时也需明确提出新任务
|
||||
vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py --workflow aalc --new-run
|
||||
# 查看已交给 AALC 的任务结果,不启动下一局
|
||||
vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py --workflow aalc --resume
|
||||
```
|
||||
|
||||
AALC 交接结果写入运行目录的 `aalc_mirror_status.json`;停止已交接的任务使用 `stop_task` 或急停键(默认 End)。
|
||||
`JEV_STOP` 会阻止新的交接,但交接后不再由此脚本监听。`--steps` / `--seconds` 仅限制逐步模式。
|
||||
|
||||
`--workflow speedrun` 使用原有的特殊速通流程。为兼容现有调用,提供 Jev 配置、
|
||||
`--decision-engine`、执行模型回调、`LC_FIXED_FALLBACK=1` 或未完成速通记录时,`auto` 保留逐步模式。
|
||||
`--resume` 沿用已保存的流程;已有未完成速通局时,切换 AALC 必须明确指定 `--new-run`。
|
||||
|
||||
逐步模式通过 MCP bridge 操作游戏,路线等分支交给 Jev 或执行模型;战斗采用 P → 回车宏,事件先 SKIP,回车失效时使用当前按钮。它保留用户已配好的队伍,商店无可替换出战角色时至多刷新 4 次,加载期间不读取旧库存继续操作。
|
||||
|
||||
安装 AALC 依赖并启动常驻服务后,把 `OPENCODE_API_KEY` 设为自己的凭据,再运行:
|
||||
|
||||
```powershell
|
||||
vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py scripts\jev_config.example.json --steps 250 --seconds 1800
|
||||
vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py scripts\jev_config.example.json --workflow speedrun --steps 250 --seconds 1800
|
||||
```
|
||||
|
||||
运行数据默认写到 `~/lc_mcp/jev`,可用 `LC_JEV_HOME` 指定其他目录。创建该目录下的 `JEV_STOP` 文件即可停止;续跑前移除它。不要与 AALC 完整任务或另一个游戏执行器同时操作。
|
||||
运行数据默认写到 `~/lc_mcp/jev`,可用 `LC_JEV_HOME` 指定其他目录。逐步模式下创建该目录的 `JEV_STOP` 文件即可停止;续跑前移除它。不要与 AALC 完整任务或另一个游戏执行器同时操作。
|
||||
工具调用失败(截图暂不可用、按钮已消失等)会记入日志并重新观察画面,同一画面上同一动作最多尝试两次,不会因单次失败整局退出。
|
||||
|
||||
每局运行现在有独立标识。默认续跑尚未结束且上下文一致的当前局;已完成或没有运行记录时建立新局。重新开一局时使用 `--new-run`,明确要求续跑时使用 `--resume`。旧版本未完成记录会保留楼层和强化进度,但旧的领取及战斗标记不会作为本局完成证据;只有上下文而没有运行记录时会重置它。领取截图和返回大厅截图必须属于当前局,才能记录完成。
|
||||
逐步模式每局运行有独立标识。默认续跑尚未结束且上下文一致的当前局;已完成或没有运行记录时建立新局。重新开一局时使用 `--new-run`,明确要求续跑时使用 `--resume`。旧版本未完成记录会保留楼层和强化进度,但旧的领取及战斗标记不会作为本局完成证据;只有上下文而没有运行记录时会重置它。领取截图和返回大厅截图必须属于当前局,才能记录完成。
|
||||
|
||||
```powershell
|
||||
# 新开一局:清除上一局的楼层、饰品与领取状态
|
||||
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
# 待开发计划(BACKLOG)
|
||||
|
||||
按「收益 / 风险」排序。每条都带**证据**和**验收标准**,云端改完直接照着验。
|
||||
最近一次实测记录见 [`feedback/2026-11-14/README.md`](feedback/2026-11-14/README.md),
|
||||
接口与队名表见 [`feedback/2026-11-14/HANDOVER.md`](feedback/2026-11-14/HANDOVER.md)。
|
||||
|
||||
图例:P0 = 现在是坏的/每天都在浪费;P1 = 明显影响质量;P2 = 打磨。
|
||||
|
||||
---
|
||||
|
||||
## P0-1 商店「必买 / 必卖 / 公式合成」清单恒为空
|
||||
|
||||
**现状**:`tasks/mirror/__init__.py` 用旧路径加载模板:
|
||||
|
||||
```python
|
||||
must_purchase_path = "./assets/images/share/mirror/shop/must_purchase"
|
||||
```
|
||||
|
||||
实际图片在 `./assets/images/default/share/mirror/shop/must_purchase/`(5 张:`carmilla`、`homeward`、
|
||||
`lithograph`、`phlebotomy_pack`、`piece_of_relationship`),`assets/images/share` 根本不存在。
|
||||
运行时实测:
|
||||
|
||||
```
|
||||
must_purchase 0
|
||||
must_be_abandoned 0
|
||||
fusion_result 0
|
||||
```
|
||||
|
||||
后果:`in_shop.py:157` 的购买循环、`:564` 的废弃识别、公式合成全部空转。2026-11-14 进店 51 秒、
|
||||
打印了三次「开始购买必买项」却没买一件。
|
||||
|
||||
**目标**:三个清单按当前 `path_manager` 的图片根(`default/share`、`dark/share`…)加载,且支持中英文资源目录。
|
||||
|
||||
**验收**:
|
||||
|
||||
- [ ] `python -c "import tasks.mirror as m; print(len(m.must_purchase), len(m.must_be_abandoned), len(m.fusion_result))"` → `5 19 31`
|
||||
- [ ] 单测覆盖:清单非空、路径含 `default/share`、`dark` 主题下也能解析
|
||||
- [ ] 实机进店日志能看到真正的购买动作(`购买` 后出现 `ego_gift_get_confirm`),且余额变化
|
||||
|
||||
**涉及**:`tasks/mirror/__init__.py`(`vendor`!)→ 若要遵守「不改 vendor」,就在 `lc_mcp/aalc_patches.py`
|
||||
里于 import 后重建这三个列表,并加一条注释说明上游路径缺陷。
|
||||
|
||||
**风险**:低。纯路径/清单;不改判定逻辑。
|
||||
|
||||
---
|
||||
|
||||
## P0-2 镜牢走位被配置降级成「只按 ↑」
|
||||
|
||||
**现状**:`config.yaml` 里 `mirror_keyboard_navigation: true` + `mirror_keyboard_simple_pathfinding: true`,
|
||||
`mirror.py:1128` 因此走 `search_road_simple_keyboard()`:每层按两次 ↑ 进最上面的节点,不看节点类型。
|
||||
Dijkstra 那套(`search_road.py:735`,代价 event 1 / shop 2 / battle 4 / boss·focused 6 / risky 7)完全没跑。
|
||||
|
||||
**目标**(二选一,云端定):
|
||||
|
||||
- A:默认改用 Dijkstra,只在检测到「鼠标拖地图卡死」时降级为简单键盘;
|
||||
- B:保留简单键盘,但把「↑ 的第一个节点」换成「按节点类型挑可达节点」。
|
||||
|
||||
**验收**:
|
||||
|
||||
- [ ] 一局里至少 3 层,日志能打印每层选中的节点类型与理由
|
||||
- [ ] 事件/商店节点占比 ≥ 现状(对比 11-14 这局:3 层只进过 1 次商店)
|
||||
- [ ] 不出现寻路卡死(连续 60 s 无 `enter_assets` 即算失败,应回退简单键盘)
|
||||
|
||||
**涉及**:`tasks/mirror/search_road.py`、`tasks/mirror/mirror.py:1128`、`config.yaml` 默认值(`assets/config/config.example.yaml`)
|
||||
|
||||
**风险**:中。`simple_pathfinding` 当初是为了规避鼠标拖拽卡死加的,去掉要有回退开关。
|
||||
|
||||
---
|
||||
|
||||
## P1-3 饰品三选一加「体系优先」
|
||||
|
||||
**现状**:`mirror.py:1360 acquire_ego_gift()` 只看两件事——是不是白棉花、是不是「已持有」,
|
||||
然后拿第一张。**完全不看 `team_system`**。
|
||||
|
||||
**目标**:可配置的关键词优先表(例如流血队:`流血 / 出血 / 血迹`),命中则加权;仍旧排除已持有与白棉花。
|
||||
|
||||
**验收**:
|
||||
|
||||
- [ ] 单测:给定候选文本列表 + 体系,选出预期那一张(含「全部已持有」「全是白棉花」边界)
|
||||
- [ ] 实机:流血队一局里,三选一命中体系关键词的比例 > 0(日志统计)
|
||||
- [ ] 关闭该配置时行为与现在完全一致(可回滚)
|
||||
|
||||
**涉及**:`tasks/mirror/mirror.py`、`lc_mcp/aalc_patches.py`(建议做成可配置关键词表,放 `config.yaml` 或独立 yaml)
|
||||
|
||||
**风险**:中。OCR 有误读(`震颐`/`沉论`/`编#16`),关键词要容忍错字。
|
||||
|
||||
---
|
||||
|
||||
## P1-4 事件选项策略可配
|
||||
|
||||
**现状**:`mirror.py:1230 event_handling()` 固定策略——能点「判定 / check」就点,然后**永远点第一个选项**,
|
||||
最后找 `continue/继续`。跟体系、跟当前血量都无关。
|
||||
|
||||
**目标**:支持一张「事件 → 选项」表(JSON/YAML),未收录的退回「第一个选项」。
|
||||
|
||||
**验收**:
|
||||
|
||||
- [ ] 表里命中的事件按配置点;未命中的行为不变
|
||||
- [ ] 单测:事件文本 → 选项索引映射,含缺省分支
|
||||
- [ ] 至少录入 5 个高频事件(可从 `docs/mirror_dungeon_speedrun_notes.md` 的既有结论里抄)
|
||||
|
||||
**涉及**:`tasks/mirror/mirror.py`、新增数据文件(建议 `lc_mcp/data/event_choices.yaml`,不要塞进 vendor)
|
||||
|
||||
**风险**:低-中。选项点错可能拿不到奖励,但不会卡死。
|
||||
|
||||
---
|
||||
|
||||
## P1-5 选队补丁的鲁棒性
|
||||
|
||||
**现状**:`_select_team_by_name()` 精确匹配 + 4 轮翻页。已知薄弱点:
|
||||
|
||||
- OCR 误读(实测把「震颤」读成「震颐」、「沉沦」读成「沉论」、「编队#16」读成「编#16」)
|
||||
- 队名带后缀(「流血队」「流血(X)」)会失配
|
||||
- 只按「顶栏名字」确认,若顶栏字号变化会误判
|
||||
|
||||
**目标**:别名表 + 归一化(去空格/全半角/常见误读)+ 失败时输出候选列表便于排查。
|
||||
|
||||
**验收**:
|
||||
|
||||
- [ ] 把队名临时改成「流血队」也能选中(别名/前缀匹配,仍需唯一)
|
||||
- [ ] 误读样本(`震颐`→`震颤`、`沉论`→`沉沦`)能正确归一
|
||||
- [ ] 失败日志里打印「这一屏看到了哪些名字」,而不是只说没找到
|
||||
|
||||
**涉及**:`lc_mcp/aalc_patches.py`、`tests/test_system_team_selection.py`
|
||||
|
||||
**风险**:低。只是匹配变宽,需保证「唯一命中」才点,避免选错队。
|
||||
|
||||
---
|
||||
|
||||
## P2-6 商店必买清单本地化
|
||||
|
||||
**现状**:必买靠 5 张**英文/图标模板**;汉化后商店里的名称是中文,模板匹配靠图标尚可,但新增饰品无法覆盖。
|
||||
|
||||
**目标**:支持「饰品中文名 → 优先级」的配置表,OCR 命中即买;模板作为兜底。
|
||||
|
||||
**验收**:单测 + 实机一局至少一次由名字命中的购买。
|
||||
|
||||
**涉及**:`lc_mcp/aalc_patches.py`(包一层购买判定)、新增数据文件。
|
||||
|
||||
---
|
||||
|
||||
## P2-7 观测饰品按体系自动勾选
|
||||
|
||||
**现状**:`observe_ego_gift_selected` 要人在 AALC 界面一个个勾;没勾就等于关闭观测。
|
||||
|
||||
**目标**:按 `team_system` 自动勾一组默认饰品(可覆盖),并在开跑前写回配置。
|
||||
|
||||
**验收**:`config.yaml` 里 `observe_ego_gift_selected` 与体系匹配;日志打印勾了哪些。
|
||||
|
||||
**涉及**:`lc_mcp/aalc_task.py`(apply_overrides 类似机制)、`app/observe_ego_gift_selection.py` 的序列化格式(只读参考)。
|
||||
|
||||
---
|
||||
|
||||
## P2-8 决策审计日志
|
||||
|
||||
**现状**:选队/卡包/饰品/商店的决策只散落在 DEBUG 日志里,事后要人肉 grep。
|
||||
|
||||
**目标**:每局写一份 `~/lc_mcp/runs/<task>.decisions.jsonl`:时间、阶段、画面摘要、候选、选中项、理由。
|
||||
|
||||
**验收**:一局结束后能直接统计「卡包选择理由 ×N」「三选一命中体系 ×N」「商店购买 ×N」。
|
||||
|
||||
**涉及**:`lc_mcp/aalc_patches.py`、`lc_mcp/tasks.py`(结果归档)。
|
||||
|
||||
---
|
||||
|
||||
## 已知但暂不做的
|
||||
|
||||
| 项 | 原因 |
|
||||
|---|---|
|
||||
| 让 AALC 原生支持自定义队名 | 要改 `vendor/aalc`,submodule 升级会丢;补丁层已够用 |
|
||||
| 自动识别「哪支队是流血队」 | 图像/文本都不可靠,靠命名约定(见 HANDOVER 第 4 节)更稳 |
|
||||
| 改 `mirror_dungeon_speedrun_notes.md` 的路线结论 | 那是人工速通笔记,和 AALC 的自动寻路是两套,别混 |
|
||||
@@ -0,0 +1,162 @@
|
||||
# 对接说明:镜牢选队(2026-11-14)
|
||||
|
||||
给**云端开发**看的交接文件。目标:云端改代码 → 我这边 `git pull` → 实机回归 → 回传结果。
|
||||
所以这里写清楚「改哪、别动哪、怎么验、验到什么程度算过」。
|
||||
|
||||
---
|
||||
|
||||
## 1. 仓库与运行环境
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 仓库 | `https://git.lingll.icu/yws/lc-mcp` |
|
||||
| 当前分支 | `codex/feedback-unattended-setup-20261004` |
|
||||
| 本机路径 | `D:\lc-mcp`(AALC 在 `vendor/aalc`,**submodule,不要改**) |
|
||||
| Python | `vendor\aalc\.venv\Scripts\python.exe`(3.13) |
|
||||
| 游戏 | `D:\SteamLibrary\steamapps\common\Limbus Company`(Steam build 26593955) |
|
||||
| 汉化 | `LLC_zh-CN` 2026111301(自定义语言,游戏基础语言 = 韩语,OCR 语言识别为 `zh_cn`) |
|
||||
| 分辨率 | 客户区 1280×720,`set_win_size: 720` |
|
||||
| 常驻服务 | 计划任务 `LcMCPServer`,`127.0.0.1:8765`,日志 `~/lc_mcp/server.log` |
|
||||
|
||||
**测试入口**(本机验证统一用这个,不要直接跑 `main.py`):
|
||||
|
||||
```powershell
|
||||
D:\lc-mcp\vendor\aalc\.venv\Scripts\python.exe -X utf8 -c "from lc_mcp import ..." # 单测
|
||||
# 实机:通过 MCP 工具 run_task mirror,或
|
||||
D:\lc-mcp\vendor\aalc\.venv\Scripts\python.exe -X utf8 -m lc_mcp.aalc_task mirror "{\"count\": 1}"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 本次改动(两个文件,均为增量,不改 vendor)
|
||||
|
||||
### `lc_mcp/aalc_patches.py`
|
||||
|
||||
新增一段(文件末尾,`install_default_battle_team` 之后):
|
||||
|
||||
```python
|
||||
SYSTEM_TEAM_NAMES = {...} # 体系(system 字符串) → 游戏内编队名元组
|
||||
TEAM_LIST_X_MAX / TEAM_LIST_Y_MIN / TEAM_LIST_Y_MAX # 左侧列表命中范围(客户区像素)
|
||||
TEAM_HEADER = (170, 520, 90, 150) # 顶栏队名位置,用来确认选中
|
||||
|
||||
_team_ocr(auto) -> [(text, x, y), ...] # 整屏 OCR 后清洗,不排序
|
||||
_in_list(x, y) / _in_header(x, y) # 区域判定
|
||||
_scroll_team_list(auto, direction, times, distance) # +1=回顶部, -1=往下翻
|
||||
_header_is(auto, name) / _wait_header(auto, name) # 顶栏确认(3 次 × 1.2s)
|
||||
_select_team_by_name(auto, names, log, rounds=4) # 主流程,返回 bool
|
||||
install_system_team_selection(log=print) # 安装补丁,返回原始 select_battle_team
|
||||
```
|
||||
|
||||
### `lc_mcp/aalc_task.py`
|
||||
|
||||
- import 里加 `install_system_team_selection`
|
||||
- `run()` 里、`install_default_battle_team` 之后:
|
||||
|
||||
```python
|
||||
if task in ('mirror', 'all'):
|
||||
install_system_team_selection(log=log)
|
||||
```
|
||||
|
||||
### 挂载点为什么是 `tasks.mirror.mirror`
|
||||
|
||||
`tasks/mirror/mirror.py` 在模块顶部 `from tasks.teams.team_formation import ... select_battle_team`,
|
||||
之后 `select_mirror_team()` 用的是**模块全局名**。所以补丁必须替换
|
||||
`tasks.mirror.mirror.select_battle_team`;改 `tasks.teams.team_formation.select_battle_team` 对镜牢无效
|
||||
(日常本那条补丁 patch 的是 `scheme` 命名空间,两者互不影响)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 接口契约(改的时候必须保住)
|
||||
|
||||
1. **`select_battle_team(num) -> bool`**:True = 已选中并确认在编队界面;False = 没选上,调用方会重试(最多 6 次)后抛 `unableToFindTeamError`。
|
||||
2. **不能有副作用**:补丁只点击,不写配置文件;`Mirror.__init__` 的包装只读 `team_setting`。
|
||||
3. **坐标空间**:一律按**客户区像素**(当前 1280×720)。缩放用 `cfg.set_win_size / 1440`,跟 AALC 其它地方一致。
|
||||
4. **`auto._run_ocr_for_text(my_crop=None)` 返回 `{text: [cx, cy]}`**:`cx/cy` 是 box 中心;同名文本会互相覆盖,**因此 `_team_ocr` 改成返回列表**,别再退回 dict。
|
||||
5. **不要用 `my_crop` 做界面裁剪**:实测裁剪坐标语义不可靠(裁 `(0,0,190,584)` 会读到右侧面板),统一「整屏 OCR + 坐标过滤」。
|
||||
6. **点完必须验顶栏**:只点不验会出现「日志说成功,其实没换队」。
|
||||
|
||||
---
|
||||
|
||||
## 4. 体系队名表(本机账号实际状态,2026-11-14 截图核对)
|
||||
|
||||
左侧编队列表,从上到下:
|
||||
|
||||
| 顺序 | 列表显示 | 说明 | `team_system` |
|
||||
|---|---|---|---|
|
||||
| 1 | 剧情关卡 | 剧情用预设 | — |
|
||||
| 2 | 斩击 | 打击体系队 | 7 |
|
||||
| 3 | 突刺 | 突刺体系队 | 8 |
|
||||
| 4 | 打击 | 打击体系队 | 9 |
|
||||
| 5 | 烧伤 | 烧伤体系队 | 0 |
|
||||
| 6 | 流血 | 流血体系队(**当前镜牢在用**) | 1 |
|
||||
| 7 | 震颤 | 震颤体系队 | 2 |
|
||||
| 8 | 破裂 | 破裂体系队 | 3 |
|
||||
| 9 | 沉沦 | 沉沦体系队 | 5 |
|
||||
| 10 | 呼吸法 | 呼吸体系队(代码里另有别名「呼吸」) | 4 |
|
||||
| 11 | 充能 | 充能体系队 | 6 |
|
||||
| 12+ | 编队#13 … 编队#40 | 默认名残留,未使用 | — |
|
||||
|
||||
> `#1`~`#12` 已不存在。任何按 `编队#N` 找队的逻辑在这个号上都会失败,这是本次问题的根。
|
||||
>
|
||||
> 队名改动后必须同步 `SYSTEM_TEAM_NAMES`;补丁只做**精确匹配**(`text == name`),不做子串。
|
||||
|
||||
---
|
||||
|
||||
## 5. 验证方法
|
||||
|
||||
### 5.1 单测(不需要游戏)
|
||||
|
||||
```powershell
|
||||
cd D:\lc-mcp
|
||||
vendor\aalc\.venv\Scripts\python.exe -m unittest discover -s tests -t tests -v
|
||||
```
|
||||
|
||||
本次新增 `tests/test_system_team_selection.py`,覆盖:映射表完整性、区域判定边界、
|
||||
`install_system_team_selection` 的挂载/回退行为(用假模块,不依赖 AALC/Windows)。
|
||||
|
||||
### 5.2 实机回归(需要游戏在运行)
|
||||
|
||||
```powershell
|
||||
# 1) 确认补丁挂上
|
||||
# 日志里应有:[lc_mcp] patch: 镜牢按体系名选队
|
||||
# 2) 起一局
|
||||
run_task(task="mirror", count=1)
|
||||
# 3) 看这几行
|
||||
# [lc_mcp] 镜牢体系 bleed -> 目标编队 流血
|
||||
# [lc_mcp] patch: 已按体系名选中编队 流血 (或「当前已经是编队 流血, 无需切换」)
|
||||
# [INFO] 楼层识别结果:当前为第1层
|
||||
```
|
||||
|
||||
### 5.3 验收清单
|
||||
|
||||
- [ ] `select_battle_team` 返回 True 后,顶栏队名 = 目标队名(截图为准,不看日志)
|
||||
- [ ] 连续两局:第二局走「已经是目标队,无需切换」分支
|
||||
- [ ] 把 `team_system` 改成 7(斩击)能选到「斩击」;改回 1 能选回「流血」
|
||||
- [ ] 目标名不存在时(例如临时改成 `编队#999`)能 4 轮内返回 False,不卡死、不乱点
|
||||
- [ ] 列表滚动后不会把队伍页留在错误位置(后续 `罪人编队` 步骤仍能正常执行)
|
||||
|
||||
---
|
||||
|
||||
## 6. 云端开发注意事项
|
||||
|
||||
- **不要改 `vendor/aalc`**:submodule 固定 commit,改了本地能跑、更新就丢。所有行为差异走 `lc_mcp/aalc_patches.py`。
|
||||
- **不要引入本机绝对路径**(`D:\...`、`C:\Users\YWS-HHH\...`);已有代码里 `LC_*` / `LCP_*` 环境变量是既有限制。
|
||||
- **失败要显式**:选队失败返回 False 让上层重试,不要静默 fallback 到 `编队#N`(这号没有 `#N`,会选中错的队)。
|
||||
- **日志格式**:沿用 `[lc_mcp] ...` 前缀,`task_status` 的 `errors` 扫描依赖 `[ERROR]`。
|
||||
- 新增依赖请加到 `pyproject.toml`,并确认 `uv sync` 后 `vendor/aalc/.venv` 能跑。
|
||||
|
||||
---
|
||||
|
||||
## 7. 拉取与回传
|
||||
|
||||
```powershell
|
||||
cd D:\lc-mcp
|
||||
git fetch origin
|
||||
git checkout <云端分支>
|
||||
git pull
|
||||
git submodule update --init --recursive
|
||||
vendor\aalc\.venv\Scripts\python.exe -m unittest discover -s tests -t tests
|
||||
# 实机回归 → 结果写回 docs/feedback/<日期>/
|
||||
```
|
||||
|
||||
我这边回归后会补:跑团日志、截图路径、验收清单勾选结果,以及新发现的问题。
|
||||
@@ -0,0 +1,189 @@
|
||||
# 2026-11-14 汉化更新 + 镜牢选队根因与局内决策实测
|
||||
|
||||
本次两件事:**更新游戏汉化**,以及**把「镜牢一直选不上队」查清楚并修掉**。
|
||||
后半段顺带核了镜牢局内的四类决策(走位 / 卡包 / 饰品 / 商店),发现两处真实缺陷,一并记在
|
||||
[`BACKLOG.md`](../../BACKLOG.md) 里。
|
||||
|
||||
## 环境
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 系统 | Windows 10 Pro 19045,远程会话,无人值守 |
|
||||
| 游戏 | Steam 版 Limbus Company,`D:\SteamLibrary\steamapps\common\Limbus Company` |
|
||||
| 游戏版本 | 更新前 build `26318463`(1.118.1,11-05)→ 更新后 build `26593955`(11-14 08:20 落盘) |
|
||||
| 汉化 | `LimbusCompany_Data\Lang\LLC_zh-CN`,2026101602 → **2026111301** |
|
||||
| AALC | `vendor/aalc`(git submodule,未改源码) |
|
||||
| 运行方式 | MCP `run_task mirror`,AALC 子进程,前台点击 + 罗技驱动点击 |
|
||||
|
||||
## 一、汉化更新
|
||||
|
||||
上游:`LocalizeLimbusCompany/LocalizeLimbusCompany` release `2026111301`(2026-11-13 发布)。
|
||||
装法按官方手动流程:**干净重装**(移走旧 `LLC_zh-CN` → 解压新包到游戏根目录),字体包不随
|
||||
release 发布,单独从 `Fonts/LLCCN-Font.7z` 来(自 2025-04 未变,直接沿用旧文件)。
|
||||
|
||||
| 步骤 | 结果 |
|
||||
|---|---|
|
||||
| 旧包备份 | `D:\codex\_limbus_l10n_dl\backup-LLC_zh-CN-2026101602`(2350 文件 / 45.1 MB) |
|
||||
| 下载 | `LimbusLocalize_2026111301.zip` 6,080,228 B,SHA256 `E63782A0…6E14665` |
|
||||
| 解压 | 2385 个文件,全部 SHA256 与 zip 内一致(0 不匹配) |
|
||||
| JSON 校验 | 2384 个 JSON 全部可解析,0 空文件 |
|
||||
| 字体 | `Font\Context\ChineseFont.ttf` 22.8 MB,TTF 头 `00 01 00 00` 正常 |
|
||||
| 配置 | `Lang\config.json` 未动,仍 `"lang": "LLC_zh-CN"` |
|
||||
|
||||
相对旧版新增:`walpu10` 系列事件/敌人/EGO、`Mirror8` 成就与卡包、`StoryData E100X–E103X`、
|
||||
新人格语音(`P10316/P10617/P10717/P11017/P11116`)、`SynergyKeyword`、`EventVerificationUIText` 等 35 个文件。
|
||||
|
||||
> 注:游戏第一次启动时弹「当前游戏客户端不是最新版本」,必须先更 Steam 客户端;更完再跑就正常了。
|
||||
|
||||
## 二、镜牢选队:为什么一直「选不上」
|
||||
|
||||
### 症状
|
||||
|
||||
`run_task mirror` 后 AALC 卡在选队:每 5 秒对左侧列表 OCR 一次,页码一路往上爬,然后重来。
|
||||
|
||||
```text
|
||||
08:34:27 开始执行 寻找队伍
|
||||
08:34:50 OCR: 编队#13 编队#14 编队#15 编#16
|
||||
08:35:00 OCR: 编队#19 编队#20 编队#21 …
|
||||
08:35:15 OCR: 编队#33 编队#34 编队#35 …
|
||||
08:37:00 又回到 编队#19 … ← 第 N 轮
|
||||
```
|
||||
|
||||
### 根因
|
||||
|
||||
`config.yaml` 里 `team_number: 1`,AALC 的 `select_battle_team()` 只会按
|
||||
`编队#N` / `TEAMS #N` 这个**字面名字**去 OCR 找队(`tasks/teams/team_formation.py:167`)。
|
||||
|
||||
而这个号的编队**是按体系命名的**,不是默认名;`编队#1`~`#12` 也已经不存在:
|
||||
|
||||
```text
|
||||
左侧列表(从上到下):
|
||||
剧情关卡
|
||||
斩击 突刺 打击 烧伤 流血 震颤 破裂 沉沦 呼吸法 充能 ← 10 支按体系命名
|
||||
编队#13 … 编队#40 ← 默认名残留
|
||||
```
|
||||
|
||||
所以找 `编队#1` 永远找不到 → 翻满 10 页 → 重试 6 轮 → `无法寻得队伍,请检查队伍名称是否为默认名称`。
|
||||
|
||||
### 修复
|
||||
|
||||
新增 `install_system_team_selection()`(`lc_mcp/aalc_patches.py`),在 `mirror`/`all` 任务里挂载。
|
||||
**不改 `vendor/aalc` 源码**,只替换 `tasks.mirror.mirror` 命名空间里的 `select_battle_team`:
|
||||
|
||||
```
|
||||
team_system → 队名
|
||||
0 烧伤 / 1 流血 / 2 震颤 / 3 破裂 / 4 呼吸法(兼容"呼吸")
|
||||
5 沉沦 / 6 充能 / 7 斩击 / 8 突刺 / 9 打击
|
||||
```
|
||||
|
||||
选队流程:
|
||||
|
||||
1. 先看顶栏是不是已经是这支队(是就直接返回,不动列表)
|
||||
2. 不是 → 点空白、把列表向下拖回顶部
|
||||
3. 整屏 OCR,只保留左侧列表区域(`x<260`,`300<y<640`)里的条目
|
||||
4. **精确匹配**队名 → 点击 → 轮询顶栏最多 3 次 × 1.2 s,顶栏变成该名字才算成功
|
||||
5. 没找到就往下翻(每次 3 拖),最多 4 轮;4 轮都失败返回 False,交给 AALC 原来那层重试
|
||||
|
||||
两个细节是踩出来的:
|
||||
|
||||
- **不能用 `my_crop`**:AALC 里裁剪坐标的语义跟客户区像素对不上(实测裁 `(0,0,190,584)` 会 OCR 出右侧面板的文字),所以改成整屏 OCR 再按坐标过滤。
|
||||
- **点完不能立刻判**:顶栏要 1~2 帧才刷新,实测 0.8 s 时还没变,1.2 s×3 才稳。
|
||||
|
||||
实测日志:
|
||||
|
||||
```text
|
||||
[lc_mcp] 镜牢体系 bleed -> 目标编队 流血
|
||||
[lc_mcp] 编队列表里找到 流血 @(130,492)
|
||||
[lc_mcp] patch: 已按体系名选中编队 流血
|
||||
[INFO] 楼层识别结果:当前为第1层
|
||||
[INFO] 此次选择卡包关键词:信仰
|
||||
```
|
||||
|
||||
(第二次跑因为上一次已经停在「流血」上,直接命中「当前已经是编队 流血, 无需切换」。)
|
||||
|
||||
## 三、局内四类决策:代码实际怎么走
|
||||
|
||||
| 决策 | 现状 | 代码位置 |
|
||||
|---|---|---|
|
||||
| 走位 | **被配置降级成瞎走**:`mirror_keyboard_simple_pathfinding: true` → 每层只按 ↑ 选最上面节点 | `mirror.py:1128` → `search_road.py:145` |
|
||||
| 卡包 | 规则明确:关键词权重表取最高,低于阈值就刷新(≤3 次) | `select_theme_pack.py` |
|
||||
| 饰品三选一 | **不看体系**:排白棉花 → 排「已持有」→ 拿第一张 | `mirror.py:1360` |
|
||||
| 商店 | 必买/必卖清单为 **0**(路径写错),只剩体系强化/刷新/合成/治疗 | `in_shop.py:157`、`tasks/mirror/__init__.py` |
|
||||
| 事件 | 固定:能「判定」就判定,然后永远点第一个选项 | `mirror.py:1230` |
|
||||
|
||||
### 3.1 走位
|
||||
|
||||
```python
|
||||
# search_road.py:145
|
||||
for attempt in range(2):
|
||||
auto.key_press("up")
|
||||
if _keyboard_enter_succeeded():
|
||||
return True
|
||||
```
|
||||
|
||||
关掉 `mirror_keyboard_simple_pathfinding` 才会走 Dijkstra(`search_road.py:735`),节点代价表
|
||||
(`search_road.py:609`,越小越优先):
|
||||
|
||||
| 节点 | 代价 |
|
||||
|---|---|
|
||||
| event | 1 |
|
||||
| shop | 2 |
|
||||
| battle | 4 |
|
||||
| boss / focused / abnormality | 6 |
|
||||
| risky_encounter | 7 |
|
||||
| 未知 | 999(不可达) |
|
||||
|
||||
### 3.2 卡包
|
||||
|
||||
`preferred_thresholds: 0`,权重表在 `theme_pack_list.yaml`(多数 0、`chick: 1`、未知 -5)。
|
||||
本次三次选择:`信仰` → `赌徒` → `情感懒`。
|
||||
|
||||
### 3.3 饰品三选一
|
||||
|
||||
`acquire_ego_gift()`:排除白棉花(除非 `not_skip_whitegossypium`)→ OCR「已持有 / Owned」→
|
||||
优先没持有的 → 都一样拿第一张。**没有任何体系判断**。
|
||||
|
||||
### 3.4 商店(真实缺陷)
|
||||
|
||||
`tasks/mirror/__init__.py` 用的是旧路径:
|
||||
|
||||
```python
|
||||
must_purchase_path = "./assets/images/share/mirror/shop/must_purchase"
|
||||
```
|
||||
|
||||
实际图片在 `./assets/images/default/share/mirror/shop/must_purchase/`,`assets/images/share` 不存在。
|
||||
运行时验证:
|
||||
|
||||
```
|
||||
must_purchase 0
|
||||
must_be_abandoned 0
|
||||
fusion_result 0
|
||||
```
|
||||
|
||||
本次日志实锤(进店 51 秒,一件没买):
|
||||
|
||||
```text
|
||||
10:03:03 开始执行 镜牢商店
|
||||
10:03:16 开始购买必买项
|
||||
10:03:54 结束执行 镜牢商店 耗时 00:00:51
|
||||
```
|
||||
|
||||
## 四、本次跑团(进行中记录)
|
||||
|
||||
```text
|
||||
09:39:53 task mirror start
|
||||
09:40:07 选队 → 流血(已是目标队,跳过切换)
|
||||
09:41:16 第1层
|
||||
09:54:33 第1层结束 13:07,卡包:赌徒
|
||||
09:55:20 寻路出错 → 自动重进镜牢,恢复
|
||||
10:03:54 第2层商店 51 秒(未购买,见 3.4)
|
||||
10:07:32 第2层结束 12:59,卡包:情感懒
|
||||
10:17:37 第3层战斗中
|
||||
```
|
||||
|
||||
## 五、仍未验证的边界
|
||||
|
||||
- 选队补丁只在「流血」上实测过;其它 9 个体系名未实跑(队列切换、`teams_active_queue` 轮转时尤其没验)。
|
||||
- 队名如果被改(比如改成「流血队」),补丁会失配 → 需要同步改 `SYSTEM_TEAM_NAMES`。
|
||||
- `my_crop` 语义不一致这件事只在这个界面验证过,别的界面不一定。
|
||||
- 关掉 `mirror_keyboard_simple_pathfinding` 后 Dijkstra 的稳定性没验(当初开它就是为躲鼠标拖地图卡死)。
|
||||
@@ -1,12 +1,23 @@
|
||||
---
|
||||
name: limbus-mirror-speedrun
|
||||
description: 继续或重开边狱公司(Limbus Company)的镜像迷宫/镜牢,按破裂黎明与黑兽纯 P 攻略追求整局通关速度;处理开局配置、卡包、事件、必要强化、技能替换与战斗快捷键。用于用户要求代打镜牢或优化此速通流程时,不用于一般配队讨论或主线事件。
|
||||
description: 执行或优化边狱公司(Limbus Company)的特殊镜牢速通,按用户指定的破裂黎明、黑兽纯 P 或具体路线逐步控制,并续跑该速通的未完成局。普通刷镜牢、日常和领奖使用 AALC run_task;一般配队讨论和主线事件不使用本 skill。
|
||||
---
|
||||
|
||||
# 镜牢破裂纯 P 速通
|
||||
|
||||
目标是尽快完成用户授权的一局镜牢。接着当前画面推进;只有用户明确要求重开时才放弃当前局。用户后续纠正覆盖本 skill 的默认配置。
|
||||
|
||||
## 选择执行方式
|
||||
|
||||
用户只要求普通刷镜牢且没有特殊路线时,先查 MCP `task_status`;空闲后用 `run_task`,
|
||||
例如一局为 `{"task":"mirror","count":1}`,随后轮询 `task_status` 并检查 `errors`、
|
||||
`pending_restore`,不进入下方逐步速通规则。完成局数不足时任务报 `failed`,不能当作已通关。
|
||||
已有任务时监控它;用户停止后不自动重跑。
|
||||
日常与领奖分别用 `daily`、`reward`,`all` 和花狂气的 `enkephalin` 必须符合明确要求。
|
||||
|
||||
只有特殊速通要求或续跑该速通局时使用下方规则,调用执行器时指定 `--workflow speedrun`。
|
||||
自动流程卡住时,先 `stop_task` 并确认停止,再观察画面恢复;不同时运行两个执行器。
|
||||
|
||||
## 读取与续局
|
||||
|
||||
- 执行前读取 [破裂黎明配置与楼层规划](references/rupture-route.md)。沿用用户配好的队伍、难度、出战顺序,不为了通用攻略改动配置。
|
||||
|
||||
@@ -21,6 +21,57 @@ from contextlib import contextmanager
|
||||
TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def headless_hdr_warning(scheme, log=print):
|
||||
"""Acknowledge upstream's GUI-only HDR prompt without a Qt event loop."""
|
||||
from PySide6.QtCore import Qt
|
||||
|
||||
def acknowledge(event):
|
||||
try:
|
||||
log('[lc_mcp] HDR 已开启,可能影响图像识别;命令行任务继续运行')
|
||||
finally:
|
||||
event.set()
|
||||
|
||||
signal = scheme.mediator.hdr_warning
|
||||
signal.connect(acknowledge, Qt.ConnectionType.DirectConnection)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
signal.disconnect(acknowledge)
|
||||
|
||||
|
||||
class MirrorProgress:
|
||||
"""AALC 镜牢的实际完成局数。total 为 None 表示本次没有进入镜牢循环。"""
|
||||
|
||||
def __init__(self):
|
||||
self.total = None
|
||||
self.finished = 0
|
||||
|
||||
def record(self, finished, remaining):
|
||||
# Mirror_task 开始时发 (0, 总局数), 每完成一局发 (已完成, 剩余)
|
||||
if self.total is None:
|
||||
self.total = finished + remaining
|
||||
self.finished = max(self.finished, finished)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def mirror_progress(scheme):
|
||||
"""监听 mirror_signal 统计完成局数。
|
||||
|
||||
AALC 没有可用队伍或队列为空时 Mirror_task 直接跳出循环, 进程仍以 0 退出;
|
||||
只看退出码会把"一局没打"报成 succeeded。
|
||||
"""
|
||||
from PySide6.QtCore import Qt
|
||||
|
||||
progress = MirrorProgress()
|
||||
signal = scheme.mediator.mirror_signal
|
||||
signal.connect(progress.record, Qt.ConnectionType.DirectConnection)
|
||||
try:
|
||||
yield progress
|
||||
finally:
|
||||
signal.disconnect(progress.record)
|
||||
|
||||
|
||||
def team_number(text):
|
||||
"""'TEAMS #12' / 'TFAMS#3' / '编队#1' -> '12' / '3' / '1'; 不是队伍名返回 None。"""
|
||||
m = TEAM_TARGET.fullmatch(text.replace(' ', '').strip())
|
||||
@@ -63,12 +114,61 @@ class WindowGuard(threading.Thread):
|
||||
size = int(self.cfg.set_win_size)
|
||||
return int(size * 16 / 9), size
|
||||
|
||||
def check_position(self):
|
||||
"""窗口有一截跑到屏幕外时挪回工作区。
|
||||
|
||||
背景(2026-10-22 实测): 游戏会恢复自己保存的窗口位置, 出现过 (-8, 39) 这种
|
||||
—— 左边 8 像素在屏幕外。前台模式(background_click=false)下 AALC 从**屏幕**
|
||||
抓图, 窗口一出界抓到的画面就整体错位, 模板匹配相似度掉到 0.2~0.5, 表现是
|
||||
"日志一直在动但几乎不点击"(实测 30 秒只点 1 次, 挪回来立刻恢复)。
|
||||
set_win_position=free 时 AALC 不碰位置, 所以这里补上。
|
||||
|
||||
返回 'ok' / 'fixed' / None(没法判断)。
|
||||
"""
|
||||
try:
|
||||
import win32con
|
||||
import win32gui
|
||||
except ImportError:
|
||||
return None
|
||||
handle = self.screen.handle
|
||||
hwnd = handle._hwnd
|
||||
try:
|
||||
left, top, right, bottom = handle.monitor_info["Work"]
|
||||
except Exception:
|
||||
return None
|
||||
try:
|
||||
x, y, r, b = win32gui.GetWindowRect(hwnd)
|
||||
except Exception:
|
||||
return None
|
||||
width, height = r - x, b - y
|
||||
if width <= 0 or height <= 0:
|
||||
return None
|
||||
# 已经完整落在工作区内就不动
|
||||
if x >= left and y >= top and r <= right and b <= bottom:
|
||||
return 'ok'
|
||||
new_x = max(left, min(x, right - width))
|
||||
new_y = max(top, min(y, bottom - height))
|
||||
try:
|
||||
win32gui.SetWindowPos(hwnd, 0, new_x, new_y, 0, 0,
|
||||
win32con.SWP_NOSIZE | win32con.SWP_NOZORDER |
|
||||
win32con.SWP_NOACTIVATE)
|
||||
except Exception as e:
|
||||
self.log('[lc_mcp] window guard: 挪窗口失败 %s: %s' % (type(e).__name__, e))
|
||||
return None
|
||||
self.fixes += 1
|
||||
self.log('[lc_mcp] window guard: 窗口 (%d,%d) 有部分在屏幕外, 已挪到 (%d,%d)'
|
||||
% (x, y, new_x, new_y))
|
||||
return 'fixed'
|
||||
|
||||
def check_once(self):
|
||||
"""返回 'ok' / 'fixed' / 'failed' / None(没有可检查的窗口)。"""
|
||||
handle = self.screen.handle
|
||||
# set_windows 关闭表示用户自己管窗口, AALC 也不调, 这里同样不插手
|
||||
if self.cfg.simulator or not self.cfg.set_windows or not handle._hwnd or handle.isMinimized:
|
||||
return None
|
||||
# 位置先修: 出界会让抓图错位, 那种情况下尺寸检查也没意义
|
||||
if self.check_position() == 'fixed':
|
||||
time.sleep(0.5)
|
||||
current = (handle.width(True), handle.height(True))
|
||||
want = self.want()
|
||||
if current == want or 0 in current:
|
||||
@@ -133,6 +233,10 @@ class DriverClickProxy:
|
||||
handle.setForeground()
|
||||
if foreground_window() != hwnd:
|
||||
raise OSError('无法激活游戏窗口, 未发送驱动输入')
|
||||
# 游戏重启后句柄会变; 每次按当前句柄重新绑定, 免得前台校验拿旧句柄拒绝所有点击。
|
||||
bind = getattr(self._driver, 'bind_window', None)
|
||||
if bind is not None:
|
||||
bind(hwnd)
|
||||
return client_to_screen(hwnd, x, y)
|
||||
|
||||
def _trace(self, msg):
|
||||
@@ -205,6 +309,13 @@ def install_driver_click(auto, screen, driver=None, log=print):
|
||||
if not ok:
|
||||
log('[lc_mcp] 驱动级输入未启用: %s' % why)
|
||||
return None
|
||||
# 绑定目标窗口: click() 靠它做句柄级前台校验。
|
||||
# 只比矩形是不够的 —— 窗口互相重叠时, 同一个屏幕坐标会同时落在两边,
|
||||
# 实测把浏览器切到前台后, 几何校验照样通过(2026-10-23)。
|
||||
try:
|
||||
drv.bind_window(screen.handle.hwnd)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
proxy = DriverClickProxy(auto.input_handler, drv, screen, log=log)
|
||||
trace = os.environ.get('LCP_DRIVER_TRACE')
|
||||
@@ -305,3 +416,190 @@ def install_robust_set_foreground(screen, log=print):
|
||||
handle.setForeground = setForeground
|
||||
log('[lc_mcp] patch: SetForegroundWindow 加 AttachThreadInput 兜底')
|
||||
return handle
|
||||
|
||||
# ---------------------------------------------------------------- 日常本用默认队伍
|
||||
|
||||
|
||||
def install_default_battle_team(scheme, log=print):
|
||||
"""日常本不再翻队伍列表, 直接用界面上已经选中的默认队伍。
|
||||
|
||||
背景(2026-11-06): 这账号的队伍是自定义名字(不是 "编队#N"), 而
|
||||
select_battle_team 按名字找队伍, 找不到就来回滑动 10 次(实测 61 秒), 滑完还把
|
||||
队伍页留在滚动后的位置; 紧接着 battle.to_battle() 在 15 次循环里都找不到
|
||||
"进入战斗" 按钮, 报 "超出最大尝试次数, 未能进入战斗", 整个日常就这样空转。
|
||||
|
||||
经验本/纽本本来就是用界面默认队伍打的, 跳过选队伍这一步即可。
|
||||
"""
|
||||
try:
|
||||
from tasks.teams import team_formation as tf
|
||||
except Exception as e:
|
||||
log('[lc_mcp] 默认队伍补丁跳过: 无法导入 team_formation: %s' % e)
|
||||
return None
|
||||
original = getattr(tf, 'select_battle_team', None)
|
||||
if original is None:
|
||||
log('[lc_mcp] 默认队伍补丁跳过: 找不到 select_battle_team')
|
||||
return None
|
||||
|
||||
def select_battle_team(*args, **kwargs):
|
||||
log('[lc_mcp] patch: 日常本跳过选队伍, 直接用默认队伍')
|
||||
return True
|
||||
|
||||
tf.select_battle_team = select_battle_team
|
||||
scheme.select_battle_team = select_battle_team
|
||||
log('[lc_mcp] patch: 日常本使用默认队伍')
|
||||
return original
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 镜牢按体系名选队
|
||||
|
||||
# 这账号把编队按体系命名(流血的队就叫 "流血"), AALC 却只会找 "编队#N" / "TEAMS #N"。
|
||||
# 2026-11-14 实测: 列表里是 剧情关卡/斩击/突刺/打击/烧伤/流血/震颤/破裂/沉沦/呼吸法/充能
|
||||
# 再接 编队#13..#38, 根本没有 "编队#1" —— AALC 翻满 10 页也找不到, 报 "无法寻得队伍"。
|
||||
SYSTEM_TEAM_NAMES = {
|
||||
'burn': ('烧伤',),
|
||||
'bleed': ('流血',),
|
||||
'tremor': ('震颤',),
|
||||
'rupture': ('破裂',),
|
||||
'poise': ('呼吸法', '呼吸'),
|
||||
'sinking': ('沉沦',),
|
||||
'charge': ('充能',),
|
||||
'slash': ('斩击',),
|
||||
'pierce': ('突刺',),
|
||||
'blunt': ('打击',),
|
||||
}
|
||||
|
||||
# 左侧编队列表的 OCR 命中范围(客户区像素, 1280x720 实测)
|
||||
TEAM_LIST_X_MAX = 260
|
||||
TEAM_LIST_Y_MIN = 300
|
||||
TEAM_LIST_Y_MAX = 640
|
||||
# 顶栏 "编队名" 的位置, 用来确认真的选中了
|
||||
TEAM_HEADER = (170, 520, 90, 150)
|
||||
|
||||
|
||||
def _team_ocr(auto):
|
||||
"""整屏 OCR, 返回 [(文本, x, y), ...]。用列表而不是 dict: 同名条目(列表里的队名和顶栏队名)
|
||||
落在不同位置, dict 会把它们覆盖成一条。不用 my_crop: 裁剪区的坐标系不可靠。"""
|
||||
ocr = auto._run_ocr_for_text(my_crop=None)
|
||||
result = []
|
||||
for text, pos in (ocr or {}).items():
|
||||
clean = str(text).replace(' ', '').strip()
|
||||
if not clean:
|
||||
continue
|
||||
try:
|
||||
x, y = float(pos[0]), float(pos[1])
|
||||
except (TypeError, IndexError, ValueError):
|
||||
continue
|
||||
result.append((clean, x, y))
|
||||
return result
|
||||
|
||||
|
||||
def _in_list(x, y):
|
||||
return x < TEAM_LIST_X_MAX and TEAM_LIST_Y_MIN < y < TEAM_LIST_Y_MAX
|
||||
|
||||
|
||||
def _in_header(x, y):
|
||||
x1, x2, y1, y2 = TEAM_HEADER
|
||||
return x1 < x < x2 and y1 < y < y2
|
||||
|
||||
|
||||
def _scroll_team_list(auto, direction, times=6, distance=250):
|
||||
"""direction=+1 向下拖(回到列表顶部), -1 向上拖(往下翻)。"""
|
||||
for _ in range(times):
|
||||
auto.mouse_swipe_for_team_scroll(130, 430, dy=direction * distance, duration=0.3)
|
||||
time.sleep(0.35)
|
||||
|
||||
|
||||
def _header_is(auto, name):
|
||||
"""顶栏当前队伍名就是 name。"""
|
||||
if auto.take_screenshot() is None:
|
||||
return False
|
||||
return any(text == name and _in_header(x, y) for text, x, y in _team_ocr(auto))
|
||||
|
||||
|
||||
def _wait_header(auto, name, tries=3, delay=1.2):
|
||||
"""点完之后顶栏要过一两帧才刷新, 多等几次。"""
|
||||
for _ in range(tries):
|
||||
time.sleep(delay)
|
||||
if _header_is(auto, name):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _select_team_by_name(auto, names, log=print, rounds=4):
|
||||
"""在编队列表里按名字点选。成功返回 True, 没找到返回 False。"""
|
||||
if auto.take_screenshot() is None:
|
||||
return False
|
||||
if not auto.find_element('teams/identify_assets.png'):
|
||||
log('[lc_mcp] 不在编队界面, 跳过按名字选队')
|
||||
return False
|
||||
for name in names: # 已经是这支队就不用动列表
|
||||
if _header_is(auto, name):
|
||||
log('[lc_mcp] patch: 当前已经是编队 %s, 无需切换' % name)
|
||||
return True
|
||||
auto.mouse_click(1, 1)
|
||||
time.sleep(0.3)
|
||||
_scroll_team_list(auto, +1) # 先回到顶部
|
||||
for round_index in range(rounds):
|
||||
if auto.take_screenshot() is None:
|
||||
continue
|
||||
items = _team_ocr(auto)
|
||||
hit = None
|
||||
for name in names:
|
||||
for text, x, y in items:
|
||||
if text == name and _in_list(x, y):
|
||||
hit = (name, x, y)
|
||||
break
|
||||
if hit:
|
||||
break
|
||||
if hit:
|
||||
name, x, y = hit
|
||||
log('[lc_mcp] 编队列表里找到 %s @(%d,%d)' % (name, x, y))
|
||||
auto.mouse_action_with_pos([x, y], offset=False)
|
||||
if _wait_header(auto, name):
|
||||
log('[lc_mcp] patch: 已按体系名选中编队 %s' % name)
|
||||
return True
|
||||
log('[lc_mcp] 点了 %s 但顶栏没变, 继续往下翻' % name)
|
||||
_scroll_team_list(auto, -1, times=3)
|
||||
log('[lc_mcp] 编队列表里没找到 %s(共 %d 轮)' % ('/'.join(names), rounds))
|
||||
return False
|
||||
|
||||
|
||||
def install_system_team_selection(log=print):
|
||||
"""镜牢选队改成"按队伍体系对应的中文名"在列表里点。
|
||||
|
||||
AALC 原生只认 编队#N; 本账号的编队是自定义名字(流血/斩击/...), 原生逻辑永远选不上。
|
||||
"""
|
||||
try:
|
||||
from tasks.mirror import mirror as mirror_mod
|
||||
from module.automation import auto
|
||||
except Exception as e:
|
||||
log('[lc_mcp] 体系选队补丁跳过: 无法导入 %s' % e)
|
||||
return None
|
||||
original = getattr(mirror_mod, 'select_battle_team', None)
|
||||
if original is None:
|
||||
log('[lc_mcp] 体系选队补丁跳过: mirror 模块没有 select_battle_team')
|
||||
return None
|
||||
wanted = {'names': ()}
|
||||
original_init = mirror_mod.Mirror.__init__
|
||||
|
||||
def __init__(self, team_setting, team_num):
|
||||
original_init(self, team_setting, team_num)
|
||||
wanted['names'] = SYSTEM_TEAM_NAMES.get(getattr(self, 'system', ''), ())
|
||||
log('[lc_mcp] 镜牢体系 %s -> 目标编队 %s'
|
||||
% (getattr(self, 'system', '?'), '/'.join(wanted['names']) or '(无配置)'))
|
||||
|
||||
def select_battle_team(num):
|
||||
names = wanted['names']
|
||||
if names:
|
||||
try:
|
||||
if _select_team_by_name(auto, names, log=log):
|
||||
return True
|
||||
except Exception as e:
|
||||
log('[lc_mcp] 按名字选队出错: %s: %s' % (type(e).__name__, e))
|
||||
return False
|
||||
return original(num)
|
||||
|
||||
mirror_mod.Mirror.__init__ = __init__
|
||||
mirror_mod.select_battle_team = select_battle_team
|
||||
log('[lc_mcp] patch: 镜牢按体系名选队')
|
||||
return original
|
||||
|
||||
+52
-8
@@ -11,8 +11,11 @@ import sys
|
||||
|
||||
from . import killswitch, preflight
|
||||
from .aalc_engine import bootstrap
|
||||
from .aalc_patches import (WindowGuard, driver_click_tasks, install_exact_team_match,
|
||||
install_robust_set_foreground, stop_driver_click)
|
||||
from .aalc_patches import (WindowGuard, driver_click_tasks, headless_hdr_warning,
|
||||
install_default_battle_team, install_exact_team_match,
|
||||
install_robust_set_foreground, install_system_team_selection,
|
||||
mirror_progress, stop_driver_click)
|
||||
from .game_lock import GameBusyError, exclusive_game
|
||||
|
||||
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
|
||||
TASKS = {
|
||||
@@ -22,8 +25,11 @@ TASKS = {
|
||||
'enkephalin': {'times': 'set_lunacy_to_enkephalin'},
|
||||
'mirror': {'count': 'set_mirror_count'},
|
||||
}
|
||||
# 用户给了镜牢次数时一并临时关闭的配置: 开着无限刷牢, AALC 会把次数改成 9999
|
||||
EXPLICIT_COUNT_OVERRIDES = {'mirror': {'count': {'infinite_dungeons': False}}}
|
||||
RESTORE_ENV = 'LCP_RESTORE_FILE'
|
||||
PREFLIGHT_EXIT = 3
|
||||
INCOMPLETE_EXIT = 4 # AALC 正常返回, 但镜牢完成局数少于应打局数
|
||||
|
||||
|
||||
def log(msg):
|
||||
@@ -36,17 +42,37 @@ def apply_overrides(cfg, task, params, restore_path=None):
|
||||
AALC 运行中会整份保存配置(如镜牢后 rotate_team_queue), 覆盖值会被写进 config.yaml。
|
||||
所以先把原值落盘: 进程被 stop_task 强杀、finally 来不及执行时, TaskRunner 据此写回。
|
||||
"""
|
||||
originals = {TASKS[task][name]: cfg.get_value(TASKS[task][name]) for name in params}
|
||||
overrides = {TASKS[task][name]: int(value) for name, value in params.items()}
|
||||
for name in params:
|
||||
overrides.update(EXPLICIT_COUNT_OVERRIDES.get(task, {}).get(name, {}))
|
||||
originals = {key: cfg.get_value(key) for key in overrides}
|
||||
if originals and restore_path:
|
||||
tmp = restore_path + '.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
json.dump(originals, f, ensure_ascii=False)
|
||||
os.replace(tmp, restore_path)
|
||||
for name, value in params.items():
|
||||
cfg.unsaved_set_value(TASKS[task][name], int(value))
|
||||
for key, value in overrides.items():
|
||||
if key == 'infinite_dungeons' and originals.get(key):
|
||||
log('[lc_mcp] 本次按指定次数运行镜牢, 临时关闭无限刷牢, 结束后恢复')
|
||||
cfg.unsaved_set_value(key, value)
|
||||
return originals
|
||||
|
||||
|
||||
def mirror_result(task, progress):
|
||||
"""按 AALC 实际完成局数给出退出码; 退出码 0 不再代表"一局没打"。"""
|
||||
if progress.total is None:
|
||||
if task != 'mirror':
|
||||
return 0 # all 没勾选镜牢
|
||||
log('[ERROR] [lc_mcp] 镜牢任务结束, 但没收到 AALC 的镜牢进度, 不能确认完成局数')
|
||||
return INCOMPLETE_EXIT
|
||||
log('[lc_mcp] 镜牢完成 %d/%d 局' % (progress.finished, progress.total))
|
||||
if progress.finished < progress.total:
|
||||
log('[ERROR] [lc_mcp] 镜牢只完成 %d/%d 局: AALC 正常返回, 但没有打完'
|
||||
'(常见原因: 没有适用当前难度的队伍、队列为空)' % (progress.finished, progress.total))
|
||||
return INCOMPLETE_EXIT
|
||||
return 0
|
||||
|
||||
|
||||
def restore(cfg, originals, restore_path=None):
|
||||
for key, value in originals.items():
|
||||
cfg.set_value(key, value)
|
||||
@@ -66,6 +92,15 @@ def restore_file(path, cfg=None):
|
||||
|
||||
|
||||
def run(task, params):
|
||||
try:
|
||||
with exclusive_game():
|
||||
return _run(task, params)
|
||||
except GameBusyError as e:
|
||||
log('[ERROR] [lc_mcp] %s' % e)
|
||||
return PREFLIGHT_EXIT
|
||||
|
||||
|
||||
def _run(task, params):
|
||||
bootstrap()
|
||||
from module.automation import auto
|
||||
from module.config import cfg
|
||||
@@ -85,15 +120,24 @@ def run(task, params):
|
||||
|
||||
install_exact_team_match(auto, log)
|
||||
install_robust_set_foreground(screen, log=log)
|
||||
# 日常本(经验/纽本)不翻队伍列表: 队伍是自定义名字时按名字找必然失败,
|
||||
# 白等 60 秒还会把界面滚乱, 后面 to_battle 就找不到 "进入战斗" 了。
|
||||
if task in ('daily', 'all'):
|
||||
install_default_battle_team(scheme, log=log)
|
||||
# 镜牢: 编队是自定义名字(体系名), AALC 只会找 "编队#N"; 改成按体系名点选。
|
||||
if task in ('mirror', 'all'):
|
||||
install_system_team_selection(log=log)
|
||||
guard = WindowGuard(screen, cfg, log=log)
|
||||
guard.start()
|
||||
restore_path = os.environ.get(RESTORE_ENV)
|
||||
originals = apply_overrides(cfg, task, params, restore_path)
|
||||
with driver_click_tasks(scheme, auto, screen, cfg, log=log):
|
||||
with driver_click_tasks(scheme, auto, screen, cfg, log=log), \
|
||||
mirror_progress(scheme) as progress:
|
||||
try:
|
||||
if task == 'all':
|
||||
with headless_hdr_warning(scheme, log=log):
|
||||
scheme.script_task()
|
||||
return 0
|
||||
return mirror_result(task, progress)
|
||||
# 与 script_task() 相同的前置步骤
|
||||
scheme.init_game()
|
||||
path_manager.initialize_paths()
|
||||
@@ -109,7 +153,7 @@ def run(task, params):
|
||||
'enkephalin': scheme.Buy_enkephalin,
|
||||
'mirror': scheme.Mirror_task,
|
||||
}[task]()
|
||||
return 0
|
||||
return mirror_result(task, progress)
|
||||
finally:
|
||||
guard.stop()
|
||||
retry_monitor.stop()
|
||||
|
||||
+72
-3
@@ -61,6 +61,14 @@ def foreground_window():
|
||||
return _api('user32', 'GetForegroundWindow', wintypes.HWND, [])()
|
||||
|
||||
|
||||
def window_title(hwnd, limit=64):
|
||||
"""窗口标题, 只用于报错说明; 取不到返回空串。"""
|
||||
buf = ctypes.create_unicode_buffer(limit)
|
||||
_api('user32', 'GetWindowTextW', ctypes.c_int,
|
||||
[wintypes.HWND, wintypes.LPWSTR, ctypes.c_int])(hwnd, buf, limit)
|
||||
return buf.value
|
||||
|
||||
|
||||
def is_console_session():
|
||||
current = wintypes.DWORD()
|
||||
query = _api('kernel32', 'ProcessIdToSessionId', wintypes.BOOL,
|
||||
@@ -110,6 +118,14 @@ class DriverInput:
|
||||
self._stopped = False
|
||||
self._input_lock = threading.RLock()
|
||||
self._pressed = set()
|
||||
# 目标窗口句柄。有它才能做句柄级前台校验 —— 几何校验在窗口重叠时没用:
|
||||
# 实测把浏览器切到前台, 点游戏里同一个坐标, 只比矩形的话校验照样通过。
|
||||
self.hwnd = 0
|
||||
|
||||
def bind_window(self, hwnd):
|
||||
"""绑定目标窗口。绑定后 click() 会做句柄级前台校验。"""
|
||||
self.hwnd = int(hwnd or 0)
|
||||
return self
|
||||
|
||||
# ---------------------------------------------------------------- 生命周期
|
||||
|
||||
@@ -203,8 +219,20 @@ class DriverInput:
|
||||
self._dll.mouse_up(int(button))
|
||||
self._pressed.discard(int(button))
|
||||
|
||||
def click(self, sx, sy, times=1, tol=1):
|
||||
"""先确认到位置, 再按下抬起。没到位就不点, 免得点错地方。"""
|
||||
def click(self, sx, sy, times=1, tol=1, require_foreground=True,
|
||||
press_ms=60, settle=0.05):
|
||||
"""先确认到位置, 再按下抬起。
|
||||
|
||||
⛔ 三个已验证的"位置对却点不上"原因(2026-10-23 实测):
|
||||
1. **前台不是游戏** —— 点击会送给当前前台窗口。实测: 窗口位置正确、坐标
|
||||
换算正确, 但前台是别的窗口, 结果点了个寂寞, 而旧版这里照样返回 True。
|
||||
现在用 require_foreground 检查: 点击点必须落在**前台窗口的客户区**内,
|
||||
否则拒绝并报错 —— 宁可失败也不要静默点错地方。
|
||||
2. **移动后立刻按下** —— 游戏按帧采样, 移动还没被处理就点击, 会算在旧位置。
|
||||
所以定位成功后先 settle 再按。
|
||||
3. **按下时间太短** —— 默认 30ms 在掉帧时会漏; 改成 60ms。
|
||||
实测 30/60/120ms 在干净环境下都能中, 但 60ms 对负载高的情况更稳。
|
||||
"""
|
||||
if not self.ready:
|
||||
return False
|
||||
if not self.move_to(sx, sy, tol=tol):
|
||||
@@ -212,11 +240,18 @@ class DriverInput:
|
||||
self.log('[driver] 定位失败: 目标(%d,%d) 实际(%d,%d), 不点击'
|
||||
% (sx, sy, cx, cy))
|
||||
return False
|
||||
if require_foreground:
|
||||
ok, why = click_point_is_on_foreground(sx, sy, self.hwnd or None)
|
||||
if not ok:
|
||||
self.log('[driver] 拒绝点击(%d,%d): %s' % (sx, sy, why))
|
||||
return False
|
||||
if settle:
|
||||
time.sleep(settle)
|
||||
for _ in range(int(times)):
|
||||
try:
|
||||
if not self.down(1):
|
||||
return False
|
||||
time.sleep(0.03)
|
||||
time.sleep(press_ms / 1000.0)
|
||||
finally:
|
||||
self.up(1)
|
||||
return not self._stopped
|
||||
@@ -234,6 +269,40 @@ class DriverInput:
|
||||
self._dll.scroll(int(amount))
|
||||
|
||||
|
||||
def click_point_is_on_foreground(sx, sy, hwnd=None):
|
||||
"""(屏幕坐标) 是否安全可点。
|
||||
|
||||
返回 (是否安全, 原因)。
|
||||
|
||||
⛔ 为什么必须比对句柄而不是比对矩形(2026-10-23 实测教训):
|
||||
最初只判断"点击点落在前台窗口的矩形内", 结果把浏览器切到前台、点游戏里
|
||||
同一个坐标, 校验**照样通过** —— 因为那个屏幕坐标同时也落在浏览器窗口的
|
||||
矩形里。几何判断在窗口互相重叠时毫无意义。
|
||||
|
||||
所以: 给了 hwnd 就要求前台窗口**就是它**(或是它的子窗口); 没给 hwnd 时
|
||||
退化成"有前台窗口且点在它矩形内", 可用性有限, 仅作兜底。
|
||||
"""
|
||||
fg = foreground_window()
|
||||
if not fg:
|
||||
return False, '当前没有前台窗口(GetForegroundWindow=0)'
|
||||
if hwnd:
|
||||
if fg == hwnd or _api('user32', 'IsChild', wintypes.BOOL,
|
||||
[wintypes.HWND, wintypes.HWND])(hwnd, fg):
|
||||
return True, 'ok'
|
||||
return False, ('前台不是目标窗口(前台=%r, 目标=%r) —— 这次点击会打到别的窗口'
|
||||
% (window_title(fg), window_title(hwnd)))
|
||||
pt = wintypes.POINT(int(sx), int(sy))
|
||||
rect = wintypes.RECT()
|
||||
get_rect = _api('user32', 'GetWindowRect', wintypes.BOOL,
|
||||
[wintypes.HWND, ctypes.POINTER(wintypes.RECT)])
|
||||
if not get_rect(fg, ctypes.byref(rect)):
|
||||
return False, '取不到前台窗口的区域'
|
||||
if not (rect.left <= pt.x < rect.right and rect.top <= pt.y < rect.bottom):
|
||||
return False, ('点击点(%d,%d)不在前台窗口内(区域 %d,%d-%d,%d)'
|
||||
% (pt.x, pt.y, rect.left, rect.top, rect.right, rect.bottom))
|
||||
return True, 'ok'
|
||||
|
||||
|
||||
def client_to_screen(hwnd, x, y):
|
||||
"""游戏客户区坐标 -> 屏幕坐标。"""
|
||||
if not hwnd:
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Cross-process ownership of the game during tasks and module conversion."""
|
||||
import errno
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
|
||||
|
||||
class GameBusyError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def default_lock_path():
|
||||
return os.path.expanduser('~/lc_mcp/game.lock')
|
||||
|
||||
|
||||
@contextmanager
|
||||
def exclusive_game(path=None):
|
||||
"""Acquire without waiting; closing the file also releases a crashed owner's lock.
|
||||
|
||||
Keep the file in place: unlinking it would let another process lock a different
|
||||
inode. The OS owns the lock, so a leftover file is not a stale reservation.
|
||||
"""
|
||||
path = os.path.abspath(path or default_lock_path())
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, 'a+b') as lock:
|
||||
lock.seek(0)
|
||||
try:
|
||||
if os.name == 'nt':
|
||||
import msvcrt
|
||||
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError as e:
|
||||
if e.errno in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
|
||||
raise GameBusyError('游戏正由其他任务或合成脚本使用,本次不接管') from e
|
||||
raise
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if os.name == 'nt':
|
||||
lock.seek(0)
|
||||
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
|
||||
+147
-71
@@ -1,109 +1,185 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""全局急停热键。
|
||||
|
||||
为什么需要: 驱动级点击是闭环定位的 —— 手一动,下一次点击前会读到新位置、
|
||||
算出偏差、再把你推回目标点。所以任务运行期间鼠标和人是"拔河"状态,用户没法
|
||||
用鼠标去点停止按钮。键盘不受影响,所以用键盘热键做急停。
|
||||
为什么需要: 驱动级点击是闭环定位的 —— 手一动, 下一次点击前会读到新位置、算出
|
||||
偏差、再把你推回目标点。所以任务运行期间鼠标是"拔河"状态, 用户没法用鼠标去点
|
||||
停止按钮。键盘不受影响, 所以急停必须走键盘。
|
||||
|
||||
⛔ AALC 自带的 pause_hotkey 帮不上忙: 那个配置项只在 GUI(app/farming_interface.py)
|
||||
里注册, lc_mcp 走的是命令行子进程, 那条路径上没有热键监听。
|
||||
⛔ 为什么不用 pynput / 全局钩子(2026-10-22 实测):
|
||||
pynput 的 GlobalHotKeys 在这台机器上**收不到任何键盘事件** —— 静态注册成功、
|
||||
线程也活着, 但 keybd_event 和 SendInput 两种注入都触发不了它。钩子依赖
|
||||
WH_KEYBOARD_LL, 在当前会话下不工作。
|
||||
改用 GetAsyncKeyState 轮询: 不装钩子、不需要消息循环, 实测能正确看到注入的
|
||||
按键。用 0x8000 位判断"当前按下"。
|
||||
|
||||
默认 F12, 可用环境变量 LCP_KILL_KEY 改(取 pynput 的键名, 如 f11 / pause / esc)。
|
||||
按下后终止任务子进程, 游戏保留。硬退出不会执行任务的 finally;
|
||||
临时配置由 TaskRunner 的恢复文件机制处理。退出前给驱动释放鼠标的短暂机会,
|
||||
清理卡住时仍强制退出。
|
||||
另外 AALC 自带的 pause_hotkey 也帮不上忙: 那个配置项只在 GUI
|
||||
(app/farming_interface.py) 里注册, lc_mcp 走命令行子进程, 那条路径上没有监听。
|
||||
|
||||
默认 End(小键盘区右下角, 好按且不冲突), 可用环境变量 LCP_KILL_KEY 改成 pause / scrolllock / f11 等。
|
||||
⛔ 不要用 F12: 那是 Steam 的截图键(用户 2026-10-22 指出), 按下去会弹 Steam 截图
|
||||
覆盖层, 而且可能被 Steam 抢先消费。Esc / F11 也不合适 —— 游戏里分别是关菜单
|
||||
和切全屏。
|
||||
|
||||
按下后终止任务子进程, 游戏保留。硬退出不会执行任务的 finally; 临时配置由
|
||||
TaskRunner 的恢复文件机制处理。退出前先给驱动释放按住的鼠标键(on_stop),
|
||||
清理或日志卡住时 STOP_TIMEOUT 后仍强制退出。监听器活在任务进程内, 所以即使
|
||||
MCP 服务出问题、用户联系不上调用方, 按热键仍然能停。
|
||||
"""
|
||||
import ctypes
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from functools import lru_cache
|
||||
|
||||
DEFAULT_KEY = 'f12'
|
||||
DEFAULT_KEY = 'end'
|
||||
EXIT_CODE = 130 # 与 SIGINT 一致, 便于上层识别"被用户中止"
|
||||
STOP_TIMEOUT = 0.25
|
||||
POLL_INTERVAL = 0.05 # 50ms 轮询, 人手按一下不会漏
|
||||
STOP_TIMEOUT = 0.25 # 释放鼠标/写日志最多等这么久, 然后强退
|
||||
START_DELAY = 0.3 # 先等一会儿, 避免把启动时按住的键当成急停
|
||||
|
||||
# 常用键 -> 虚拟键码。f12 保留是为了兼容旧配置, 但**不推荐** —— Steam 占用它。
|
||||
VK = {
|
||||
'f1': 0x70, 'f2': 0x71, 'f3': 0x72, 'f4': 0x73, 'f5': 0x74, 'f6': 0x75,
|
||||
'f7': 0x76, 'f8': 0x77, 'f9': 0x78, 'f10': 0x79, 'f11': 0x7A, 'f12': 0x7B,
|
||||
'esc': 0x1B, 'escape': 0x1B,
|
||||
'pause': 0x13, 'break': 0x13,
|
||||
'end': 0x23, 'home': 0x24, 'delete': 0x2E, 'insert': 0x2D,
|
||||
'scrolllock': 0x91, 'numlock': 0x90, 'capslock': 0x14,
|
||||
}
|
||||
|
||||
|
||||
def _key_spec(name):
|
||||
"""'f12' -> '<f12>',pynput 的 GlobalHotKeys 要求尖括号形式。"""
|
||||
name = (name or '').strip().lower() or DEFAULT_KEY
|
||||
if name.startswith('<') and name.endswith('>'):
|
||||
return name
|
||||
return '<%s>' % name
|
||||
def resolve_vk(key):
|
||||
"""键名 -> 虚拟键码。认不出返回 None(调用方负责报错, 不要静默用默认值)。"""
|
||||
name = (key or '').strip().lower().strip('<>')
|
||||
if not name:
|
||||
name = DEFAULT_KEY
|
||||
return VK.get(name)
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _key_state_api():
|
||||
"""独立绑定 GetAsyncKeyState, 不改共用的 ctypes.windll 的类型声明。"""
|
||||
fn = ctypes.WinDLL('user32', use_last_error=True).GetAsyncKeyState
|
||||
fn.argtypes = [ctypes.c_int]
|
||||
fn.restype = ctypes.c_short
|
||||
return fn
|
||||
|
||||
|
||||
def _pressed(vk):
|
||||
"""GetAsyncKeyState 的最高位 = 当前是否按下(低位只表示"按过", 不算)。"""
|
||||
return bool(_key_state_api()(vk) & 0x8000)
|
||||
|
||||
|
||||
class KillSwitch:
|
||||
"""轮询线程。按住热键会立刻退出, 不会重复触发。"""
|
||||
|
||||
def __init__(self, vk, log=print, key_name=DEFAULT_KEY, on_stop=None):
|
||||
self.vk = vk
|
||||
self.log = log
|
||||
self.key_name = key_name
|
||||
self.on_stop = on_stop
|
||||
self.fired = False
|
||||
self._stopped = threading.Event()
|
||||
self._thread = threading.Thread(target=self._run, daemon=True,
|
||||
name='lc_mcp-killswitch')
|
||||
|
||||
def start(self):
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def is_alive(self):
|
||||
return self._thread.is_alive()
|
||||
|
||||
def stop(self):
|
||||
self._stopped.set()
|
||||
|
||||
def _run(self):
|
||||
if self._stopped.wait(START_DELAY):
|
||||
return
|
||||
while not self._stopped.is_set():
|
||||
try:
|
||||
pressed = _pressed(self.vk)
|
||||
except Exception as e: # 接口失效: 说清楚后退出, 不刷满异常
|
||||
try:
|
||||
self.log('[lc_mcp] 急停热键失效(%s: %s), 请用 stop_task 或 Ctrl+Alt+Del 停止'
|
||||
% (type(e).__name__, e))
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
if pressed:
|
||||
self._fire()
|
||||
return
|
||||
self._stopped.wait(POLL_INTERVAL)
|
||||
|
||||
def _fire(self):
|
||||
if self.fired:
|
||||
return
|
||||
self.fired = True
|
||||
# 释放驱动按键或写日志卡住时, 由计时器按时强退。
|
||||
timer = threading.Timer(STOP_TIMEOUT, os._exit, args=(EXIT_CODE,))
|
||||
timer.daemon = True
|
||||
try:
|
||||
timer.start()
|
||||
try:
|
||||
if self.on_stop is not None:
|
||||
self.on_stop()
|
||||
except Exception:
|
||||
pass # 释放失败也必须退出
|
||||
try:
|
||||
self.log('[lc_mcp] ⛔ 急停热键 %s 被按下, 终止任务; 游戏窗口保留, 可用 run_task 重新开始'
|
||||
% self.key_name.upper())
|
||||
except Exception:
|
||||
pass # 日志坏了不能拦住急停
|
||||
finally:
|
||||
try:
|
||||
os._exit(EXIT_CODE)
|
||||
finally:
|
||||
timer.cancel() # 仅在测试替换 _exit 时才会走到
|
||||
|
||||
|
||||
def install(log=print, key=None, on_stop=None):
|
||||
"""启动急停监听线程。返回监听器对象(可用于测试), 失败返回 None。
|
||||
"""启动急停轮询线程。返回 KillSwitch, 失败返回 None(不抛异常)。
|
||||
|
||||
任何异常都不向外抛 —— 急停装不上不该让任务起不来, 但必须把原因说清楚。
|
||||
急停装不上不该让任务起不来, 但必须把原因和应急手段说清楚。
|
||||
"""
|
||||
key = key or os.environ.get('LCP_KILL_KEY') or DEFAULT_KEY
|
||||
spec = _key_spec(key)
|
||||
|
||||
vk = resolve_vk(key)
|
||||
if vk is None:
|
||||
log('[lc_mcp] 急停热键不可用: 认不出键名 %r(可用: %s), 请用 Ctrl+Alt+Del 强制停止'
|
||||
% (key, ', '.join(sorted(VK))))
|
||||
return None
|
||||
try:
|
||||
from pynput import keyboard
|
||||
except Exception as e: # pynput 缺失/无显示环境
|
||||
log('[lc_mcp] 急停热键不可用(pynput 加载失败: %s: %s), 请用 Ctrl+Alt+Del 强制停止'
|
||||
_key_state_api()
|
||||
except Exception as e: # 非 Windows / user32 不可用
|
||||
log('[lc_mcp] 急停热键不可用(读取键盘状态失败: %s: %s), 请用 Ctrl+Alt+Del 强制停止'
|
||||
% (type(e).__name__, e))
|
||||
return None
|
||||
|
||||
state = {'fired': False}
|
||||
|
||||
def on_activate():
|
||||
if state['fired']:
|
||||
return
|
||||
state['fired'] = True
|
||||
# Windows 在系统输入线程上调用此函数, 不在这里写日志或等待清理。
|
||||
# 即使日志锁/驱动清理卡住, 也必须按时退出。
|
||||
timer = threading.Timer(STOP_TIMEOUT, os._exit, args=(EXIT_CODE,))
|
||||
timer.daemon = True
|
||||
|
||||
def shutdown():
|
||||
try:
|
||||
if on_stop is not None:
|
||||
on_stop()
|
||||
finally:
|
||||
try:
|
||||
os._exit(EXIT_CODE)
|
||||
finally:
|
||||
timer.cancel() # 仅供 _exit 被测试替换的情况
|
||||
|
||||
try:
|
||||
timer.start()
|
||||
worker = threading.Thread(target=shutdown, name='lc-mcp-emergency-stop', daemon=True)
|
||||
state['worker'] = worker
|
||||
worker.start()
|
||||
except Exception:
|
||||
timer.cancel()
|
||||
os._exit(EXIT_CODE)
|
||||
|
||||
try:
|
||||
listener = keyboard.GlobalHotKeys({spec: on_activate})
|
||||
listener.daemon = True
|
||||
listener.start()
|
||||
switch = KillSwitch(vk, log=log, key_name=key, on_stop=on_stop).start()
|
||||
except Exception as e:
|
||||
log('[lc_mcp] 急停热键注册失败(%s: %s), 请用 Ctrl+Alt+Del 强制停止'
|
||||
log('[lc_mcp] 急停热键启动失败(%s: %s), 请用 Ctrl+Alt+Del 强制停止'
|
||||
% (type(e).__name__, e))
|
||||
return None
|
||||
|
||||
log('[lc_mcp] 急停监听已启动: 按 %s 终止任务, 游戏窗口保留; 可用 run_task 重新开始'
|
||||
% key.upper())
|
||||
listener._lc_state = state
|
||||
return listener
|
||||
log('[lc_mcp] 急停热键已就绪: 按 %s 终止任务, 游戏窗口保留; 可用 run_task 重新开始'
|
||||
'(键盘可用, 不需要鼠标, 也不依赖 MCP 服务)' % key.upper())
|
||||
return switch
|
||||
|
||||
|
||||
def stop(listener):
|
||||
"""停止监听(任务正常结束时调用, 免得线程残留)。"""
|
||||
if listener is None:
|
||||
def stop(switch):
|
||||
"""停止轮询(任务结束时调用, 免得线程残留)。"""
|
||||
if switch is None:
|
||||
return
|
||||
try:
|
||||
listener.stop()
|
||||
switch.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@contextmanager
|
||||
def listening(log=print, on_stop=None):
|
||||
listener = install(log=log, on_stop=on_stop)
|
||||
switch = install(log=log, on_stop=on_stop)
|
||||
try:
|
||||
yield listener
|
||||
yield switch
|
||||
finally:
|
||||
stop(listener)
|
||||
stop(switch)
|
||||
|
||||
+30
-7
@@ -21,13 +21,23 @@ def collect(cfg):
|
||||
return {
|
||||
'simulator': bool(cfg.get_value('simulator')),
|
||||
'mirror': bool(cfg.get_value('mirror')),
|
||||
'set_windows': bool(cfg.get_value('set_windows')),
|
||||
'set_win_position': cfg.get_value('set_win_position') or 'free',
|
||||
'set_win_size': int(cfg.get_value('set_win_size')),
|
||||
'set_lunacy_to_enkephalin': int(cfg.get_value('set_lunacy_to_enkephalin') or 0),
|
||||
'hard_mirror': bool(cfg.get_value('hard_mirror')),
|
||||
'teams_active_queue': list(cfg.get_value('teams_active_queue') or []),
|
||||
'teams': teams,
|
||||
}
|
||||
|
||||
|
||||
def team_fits_difficulty(team, hard):
|
||||
"""与 AALC Mirror_task 的可用判定一致: 固定用途 0=只打困难, 1=只打普通。"""
|
||||
if not team.get('fixed_team_use'):
|
||||
return True
|
||||
return int(team.get('fixed_team_use_select') or 0) == (0 if hard else 1)
|
||||
|
||||
|
||||
def desktop_size():
|
||||
"""主显示器分辨率(进程已由 bootstrap 设为 DPI aware, 取到的是物理像素)。"""
|
||||
from ctypes import windll
|
||||
@@ -48,25 +58,38 @@ def check(values, task, desktop=None, env=None):
|
||||
# all 只在 AALC 里勾选了镜牢时才会编队
|
||||
if task == 'mirror' or (task == 'all' and values.get('mirror')):
|
||||
teams = values.get('teams', {})
|
||||
for num in values.get('teams_active_queue', []):
|
||||
queue = list(values.get('teams_active_queue', []))
|
||||
hard = bool(values.get('hard_mirror'))
|
||||
usable = []
|
||||
for num in queue:
|
||||
team = teams.get(str(num))
|
||||
if team is None:
|
||||
# AALC 归一化队列时丢弃非整数和不存在的编号
|
||||
if team is None or type(num) is not int:
|
||||
problems.append('teams_active_queue 里的队伍 %s 没有配置' % num)
|
||||
continue
|
||||
if team_fits_difficulty(team, hard):
|
||||
usable.append(num)
|
||||
order = list(team.get('sinner_order') or [])
|
||||
# team_formation 从 1 开始按顺序找罪人, 缺 1 就一个都不选, 然后无限重试编队
|
||||
if 1 not in order:
|
||||
problems.append(
|
||||
'队伍 %s 的 sinner_order 没有罪人(全是 0): 镜牢编队会选空队伍并无限重试。'
|
||||
'在 AALC 队伍设置里勾选罪人并排序' % num)
|
||||
# 没有可用队伍时 Mirror_task 直接跳出循环, 进程照样 exit 0 报 succeeded
|
||||
if not usable:
|
||||
problems.append(
|
||||
'镜牢没有可用队伍(teams_active_queue=%s, 当前%s镜牢): AALC 会一局不打就正常退出。'
|
||||
'在 AALC 里启用队伍, 或调整队伍的"固定用途"' % (queue, '困难' if hard else '普通'))
|
||||
|
||||
if not values.get('simulator') and desktop:
|
||||
if not values.get('simulator') and values.get('set_windows', True) and desktop:
|
||||
size = values.get('set_win_size', 0)
|
||||
need_w = int(size * 16 / 9) + FRAME_W
|
||||
need_h = size + FRAME_H
|
||||
# AALC removes the title bar and borders for every automatic position.
|
||||
framed = values.get('set_win_position', 'free') == 'free'
|
||||
need_w = int(size * 16 / 9) + (FRAME_W if framed else 0)
|
||||
need_h = size + (FRAME_H if framed else 0)
|
||||
if need_w > desktop[0] or need_h > desktop[1]:
|
||||
problems.append(
|
||||
'set_win_size=%s 需要 %sx%s 的窗口(含标题栏), 桌面只有 %sx%s: 窗口会被压扁成非 16:9,'
|
||||
'set_win_size=%s 需要 %sx%s 的窗口(%s), 桌面只有 %sx%s: 窗口会被压扁成非 16:9,'
|
||||
' 模板匹配全部失效。改小 set_win_size(如 720)或调大桌面分辨率'
|
||||
% (size, need_w, need_h, desktop[0], desktop[1]))
|
||||
% (size, need_w, need_h, '含标题栏' if framed else '无边框', desktop[0], desktop[1]))
|
||||
return problems
|
||||
|
||||
+36
-7
@@ -14,6 +14,23 @@ WAIT_INTERVAL = 1.0
|
||||
INPUT_TOOLS = {'click', 'click_text', 'click_image', 'keypress', 'type_text', 'drag', 'show_game_background'}
|
||||
TASK_TOOLS = {'run_task', 'task_status', 'stop_task'}
|
||||
|
||||
AUTOMATION_INSTRUCTIONS = (
|
||||
'常规日常刷取、领奖励、普通镜牢优先使用 AALC 的 run_task 自动流程。'
|
||||
'先用 task_status 检查是否已有任务;已有任务时查看进度,不重复启动或为抢占而停止它。'
|
||||
'日常用 task="daily",领奖用 task="reward",镜牢用 task="mirror";次数按用户要求传入。'
|
||||
'例如一局镜牢调用 run_task({"task":"mirror","count":1});'
|
||||
'只刷经验本时传 exp 次数和 thread=0,只刷纽本时传 thread 次数和 exp=0,避免沿用另一项配置。'
|
||||
'启动成功仅表示任务已启动,随后轮询 task_status,最终同时检查 state、errors 和 pending_restore;'
|
||||
'succeeded 带 errors 不能报告完整成功;镜牢完成局数不足时报 failed 并在 errors 写明 已完成/应打 局数。'
|
||||
'运行中不用逐帧 get_state/click/keypress 重做流程。'
|
||||
'出现 stall 时先 stop_task 并确认停止,再 get_state 排障;停止失败不发送输入。'
|
||||
'用户停止或退出码130时结束,不自动重试。'
|
||||
'主线、特殊速通路线、用户明确要求逐步控制或自动流程不支持的操作,才使用低层观察与输入;'
|
||||
'这时先 get_state 核对当前画面。只查看状态或截图的请求不启动任务。'
|
||||
'all 仅用于用户明确要求按配置运行全部任务;enkephalin 会花狂气,仅在明确授权消费时使用。'
|
||||
'免费体力合成模块不属于 enkephalin;不把它改派为刷取或花狂气。'
|
||||
)
|
||||
|
||||
|
||||
def _obj(props=None, required=()):
|
||||
s = {'type': 'object', 'properties': props or {}}
|
||||
@@ -33,9 +50,11 @@ _IMG = {'name': {'type': 'string', 'description': 'AALC 模板图相对路径,
|
||||
TOOLS = [
|
||||
{'name': 'show_game_background', 'description': '后台显示/恢复游戏窗口,使隐藏窗口继续渲染;不激活前台、不发送鼠标或键盘输入。',
|
||||
'inputSchema': _obj()},
|
||||
{'name': 'get_state', 'description': '截图 + OCR, 返回游戏窗口内全部文字(含坐标/置信度)。决策前先调这个, 不要猜坐标',
|
||||
{'name': 'get_state', 'description': '截图 + OCR,返回窗口文字、坐标和置信度。用于观察、故障诊断和逐步控制前核对画面。'
|
||||
'常规日常/领奖/普通镜牢优先 run_task,运行进度用 task_status,无需逐帧操作。',
|
||||
'inputSchema': _obj()},
|
||||
{'name': 'click_text', 'description': '按文字点击: OCR 定位后点中心。子串匹配、忽略空格, 完全相同的优先; index 选第几个命中',
|
||||
{'name': 'click_text', 'description': '逐步控制/故障恢复用:按文字定位后点中心,完全匹配优先,index 选命中。'
|
||||
'常规日常/领奖/普通镜牢优先 run_task。',
|
||||
'inputSchema': _obj({'text': _STR, 'index': {'type': 'number', 'default': 0}}, ['text'])},
|
||||
{'name': 'wait_for_text', 'description': '轮询 OCR 直到文字出现', 'inputSchema': _obj({'text': _STR, 'timeout': _TIMEOUT}, ['text'])},
|
||||
{'name': 'wait_for_text_gone', 'description': '轮询 OCR 直到文字消失', 'inputSchema': _obj({'text': _STR, 'timeout': _TIMEOUT}, ['text'])},
|
||||
@@ -45,9 +64,11 @@ TOOLS = [
|
||||
{'name': 'list_images', 'description': '列出 AALC 模板图(按前缀过滤, 如 mirror/ battle/ home/)',
|
||||
'inputSchema': _obj({'prefix': {'type': 'string', 'default': ''}})},
|
||||
{'name': 'screenshot', 'description': '截游戏窗口, 返回 PNG 路径和尺寸', 'inputSchema': _obj()},
|
||||
{'name': 'click', 'description': '按窗口截图像素坐标点击(优先用 click_text / click_image)',
|
||||
{'name': 'click', 'description': '逐步控制/故障恢复用:按最新窗口截图的像素坐标点击,优先 click_text / click_image。'
|
||||
'常规日常/领奖/普通镜牢优先 run_task。',
|
||||
'inputSchema': _obj({'x': _NUM, 'y': _NUM, 'times': {'type': 'number', 'default': 1}}, ['x', 'y'])},
|
||||
{'name': 'keypress', 'description': '按一次键: a-z 0-9 enter esc space tab shift ctrl alt up down left right',
|
||||
{'name': 'keypress', 'description': '逐步控制/故障恢复用:按一次 a-z 0-9 enter esc space tab shift ctrl alt up down left right。'
|
||||
'常规日常/领奖/普通镜牢优先 run_task,无需自行循环战斗按键。',
|
||||
'inputSchema': _obj({'key': _STR}, ['key'])},
|
||||
{'name': 'drag', 'description': '在游戏客户区保持左键按下并缓慢拖动,适用于卡包下拉;duration 是移动秒数,0.1–10,默认 1。先 get_state 核对坐标',
|
||||
'inputSchema': _obj({'from_x': _NUM, 'from_y': _NUM, 'to_x': _NUM, 'to_y': _NUM,
|
||||
@@ -55,13 +76,20 @@ TOOLS = [
|
||||
['from_x', 'from_y', 'to_x', 'to_y'])},
|
||||
{'name': 'type_text', 'description': '向游戏窗口输入文本', 'inputSchema': _obj({'text': _STR}, ['text'])},
|
||||
{'name': 'run_task', 'description': (
|
||||
'常规日常刷取、领奖励、普通镜牢的首选工具;自动完成流程,无需逐按钮点击。先 task_status 确认没有任务在跑。'
|
||||
'后台运行 AALC 现成的完整任务流程(会自动启动游戏、处理战斗/掉线重试)。立即返回, 用 task_status 看进度。'
|
||||
'all=按 AALC config.yaml 勾选的全部任务; daily=经验本+纽本(exp/thread 次数); reward=领奖励; '
|
||||
'enkephalin=狂气换体力(times); mirror=镜牢(count 次数)。任务运行期间禁止手动点击类工具'),
|
||||
'enkephalin=狂气换体力(times); mirror=镜牢(count 次数)。一局镜牢传 task=mirror,count=1;'
|
||||
'传 count 时本次临时关闭 AALC 无限刷牢,结束后恢复;完成局数不足时任务报 failed。'
|
||||
'只刷一种日常时把另一种次数显式设为0,省略次数沿用配置。'
|
||||
'all 需明确要求全部任务;enkephalin 需明确授权花狂气,免费合成模块不能用它。'
|
||||
'任务运行期间禁止手动点击类工具;最终 succeeded 也要检查 errors,用户停止后不自动重跑。'),
|
||||
'inputSchema': _obj({'task': {'type': 'string', 'enum': sorted(TASKS)},
|
||||
'exp': _NUM, 'thread': _NUM, 'times': _NUM, 'count': _NUM}, ['task'])},
|
||||
{'name': 'task_status', 'description': '查看任务状态(idle/running/succeeded/failed/stopped)和日志尾部。'
|
||||
'succeeded 也要看 errors; running 时出现 stall 说明 AALC 在空转(如选中空队伍), 应 stop_task',
|
||||
{'name': 'task_status', 'description': '启动 run_task 前检查占用,启动后轮询此工具监控,避免逐帧截图和重复启动。'
|
||||
'返回 idle/running/succeeded/failed/stopped、日志及异常。'
|
||||
'succeeded 也要看 errors 和 pending_restore;running 出现 stall 应 stop_task 并确认停止后排障;'
|
||||
'stopped/退出码130 表示用户停止,不自动重跑。',
|
||||
'inputSchema': _obj({'lines': {'type': 'number', 'default': 30}})},
|
||||
{'name': 'stop_task', 'description': '强制停止当前任务(杀掉任务进程)', 'inputSchema': _obj()},
|
||||
]
|
||||
@@ -96,6 +124,7 @@ class Server:
|
||||
if method == 'initialize':
|
||||
return _ok(mid, {'protocolVersion': '2024-11-05',
|
||||
'capabilities': {'tools': {'listChanged': False}},
|
||||
'instructions': AUTOMATION_INSTRUCTIONS,
|
||||
'serverInfo': {'name': 'lc-mcp', 'version': VERSION}})
|
||||
if method == 'ping':
|
||||
return _ok(mid, {})
|
||||
|
||||
@@ -33,6 +33,10 @@ from lc_ui import HERE, click, items, keypress, probe, screen_text
|
||||
GAME_EXE = r'D:\SteamLibrary\steamapps\common\Limbus Company\LimbusCompany.exe'
|
||||
GAME_PROC = 'LimbusCompany'
|
||||
REPO = os.path.dirname(HERE) if os.path.basename(HERE) == 'scripts' else HERE
|
||||
if REPO not in sys.path:
|
||||
sys.path.insert(0, REPO)
|
||||
from lc_mcp.game_lock import exclusive_game
|
||||
|
||||
PYW = os.path.join(REPO, 'vendor', 'aalc', '.venv', 'Scripts', 'pythonw.exe')
|
||||
SERVER_PORT = 8765
|
||||
|
||||
@@ -760,8 +764,20 @@ def main(argv=None):
|
||||
|
||||
log('=== 开始: 体力换模块 ===')
|
||||
|
||||
try:
|
||||
with exclusive_game():
|
||||
return run_conversion(args, done)
|
||||
except (OSError, RuntimeError, subprocess.SubprocessError) as e:
|
||||
return done(1, '%s: %s' % (type(e).__name__, e))
|
||||
|
||||
|
||||
def run_conversion(args, done):
|
||||
if not ensure_server():
|
||||
return done(1, 'MCP 服务连不上, 也没能拉起来')
|
||||
# Also refuse older task processes started before the shared lock was added.
|
||||
status = probe('task_status', {'lines': 1})
|
||||
if not status.get('ok') or status.get('state') not in ('idle', 'succeeded', 'failed', 'stopped'):
|
||||
return done(1, 'AALC 任务仍在运行或状态无法确认,本轮不接管游戏')
|
||||
# 断线会让截图全黑, 那之后什么都做不了 —— 先确认桌面在出图再动游戏
|
||||
if not ensure_display():
|
||||
return done(1, '桌面不在出图(会话被断开), 本轮跳过')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Validated scene actions for Jev decisions and fixed speedrun macros."""
|
||||
"""Delegate ordinary mirror runs to AALC; retain Jev control for special speedruns."""
|
||||
import argparse
|
||||
import functools
|
||||
import json
|
||||
@@ -9,7 +9,8 @@ from pathlib import Path
|
||||
|
||||
from mcp_session import Session as Bridge, SessionCancelled, SessionTimeout
|
||||
from game_scenes import battle_is_terminal, battle_is_visible, death_retry_screen
|
||||
from run_state import prepare_run, save_json, record_claim, claim_is_current, complete_run
|
||||
from run_state import (RESUMABLE, load_json, prepare_run, save_json, record_claim,
|
||||
claim_is_current, complete_run)
|
||||
from decision_router import DecisionRouter, DecisionRequired
|
||||
from jev_client import request_answer
|
||||
from lc_scene_aliases import normalize
|
||||
@@ -797,22 +798,104 @@ def acquire_single_instance():
|
||||
return lambda: kernel.CloseHandle(lease)
|
||||
|
||||
|
||||
def execution_workflow(args, executor_decider=None):
|
||||
"""Keep explicit speedrun requirements and unfinished runs on their old path."""
|
||||
if args.workflow != 'auto':
|
||||
return args.workflow
|
||||
if (args.config or args.decision_engine or executor_decider is not None
|
||||
or os.environ.get('LC_FIXED_FALLBACK') == '1'):
|
||||
return 'speedrun'
|
||||
previous = None if args.new_run else load_json(RUNTIME_HOME / 'mirror_current_run.json')
|
||||
if previous and previous.get('workflow') == 'aalc':
|
||||
return 'aalc'
|
||||
if args.resume or previous and previous.get('status') in RESUMABLE:
|
||||
return 'speedrun'
|
||||
return 'aalc'
|
||||
|
||||
|
||||
def delegate_mirror(new_run=False, resume=False):
|
||||
"""Start or inspect AALC once; the calling agent monitors task_status afterward."""
|
||||
record = {'workflow': 'aalc', 'next_call': {'tool': 'task_status', 'args': {'lines': 30}},
|
||||
'note': '启动或接管监控不代表通关。继续轮询 task_status,检查 errors 和 pending_restore;'
|
||||
'停止用 stop_task 或急停键(默认 End)。调用超时或用户停止后不自动重试或转为逐步输入。'}
|
||||
bridge = None
|
||||
try:
|
||||
if STOP_FILE.exists():
|
||||
return dict(record, state='stopped', reason='stop_requested')
|
||||
# An explicit workflow switch must not silently discard a special route.
|
||||
previous = None if new_run else load_json(RUNTIME_HOME / 'mirror_current_run.json')
|
||||
if previous and previous.get('status') in RESUMABLE:
|
||||
return dict(record, state='requires_analysis', reason='unfinished_speedrun',
|
||||
error='存在未完成的速通局;使用 --workflow speedrun --resume,明确新开任务时用 --new-run')
|
||||
bridge = Bridge(cancelled=STOP_FILE.exists, raise_on_error=False)
|
||||
current = bridge.call('task_status', {'lines': 30})
|
||||
state = current.get('state')
|
||||
if not current.get('ok') or state not in ('idle', 'running', 'succeeded', 'failed', 'stopped'):
|
||||
return dict(record, state='requires_analysis', task_status=current)
|
||||
if (resume and previous and previous.get('workflow') == 'aalc' and previous.get('task_log')
|
||||
and current.get('log') != previous['task_log']):
|
||||
return dict(record, state='requires_analysis', reason='task_changed', task_status=current)
|
||||
if state == 'running':
|
||||
return dict(record, state='monitoring' if current.get('task') == 'mirror' else 'busy',
|
||||
task_status=current)
|
||||
if state == 'stopped' or current.get('exit_code') == 130:
|
||||
if not new_run:
|
||||
return dict(record, state='stopped', task_status=current, reason='user_stopped')
|
||||
if resume:
|
||||
return dict(record, state='requires_analysis' if current.get('errors') or current.get('pending_restore')
|
||||
or current.get('task') != 'mirror' else state, task_status=current)
|
||||
if state == 'failed' or current.get('errors') or current.get('pending_restore'):
|
||||
if not new_run or current.get('pending_restore'):
|
||||
return dict(record, state='requires_analysis', task_status=current)
|
||||
started = bridge.call('run_task', {'task': 'mirror', 'count': 1})
|
||||
if not started.get('ok'):
|
||||
return dict(record, state='requires_analysis', result=started)
|
||||
record['result'] = started
|
||||
run, _ = prepare_run(RUNTIME_HOME, new_run=True)
|
||||
run.update(status='delegated', workflow='aalc', task_log=started.get('log'))
|
||||
save_json(RUNTIME_HOME / 'mirror_current_run.json', run)
|
||||
return dict(record, state='delegated')
|
||||
except Exception as error:
|
||||
record.update(state='stopped' if isinstance(error, SessionCancelled) else 'requires_analysis',
|
||||
error='%s: %s' % (type(error).__name__, error))
|
||||
if isinstance(error, (SessionCancelled, SessionTimeout)):
|
||||
record.update(outcome_unknown=error.outcome_unknown, pending_tool=getattr(error, 'tool', None))
|
||||
return record
|
||||
finally:
|
||||
if bridge is not None:
|
||||
bridge.close()
|
||||
|
||||
|
||||
def main(executor_decider=None):
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('config', nargs='?', help='Optional Jev JSON config; omit for execution-model handoff')
|
||||
parser.add_argument('config', nargs='?', help='Optional Jev JSON config for stepwise speedrun control')
|
||||
parser.add_argument('--workflow', choices=('auto', 'aalc', 'speedrun'), default='auto',
|
||||
help='Default: AALC for ordinary mirror runs; explicit model/config or unfinished speedrun keeps stepwise control')
|
||||
parser.add_argument('--decision-engine', choices=('auto', 'jev', 'executor', 'fixed'))
|
||||
parser.add_argument('--steps', type=int, default=250)
|
||||
parser.add_argument('--seconds', type=int, default=1200)
|
||||
parser.add_argument('--steps', type=int, default=250, help='Stepwise speedrun action budget')
|
||||
parser.add_argument('--seconds', type=int, default=1200, help='Stepwise speedrun time budget')
|
||||
mode = parser.add_mutually_exclusive_group()
|
||||
mode.add_argument('--new-run', action='store_true', help='Start fresh state for a new dungeon')
|
||||
mode.add_argument('--resume', action='store_true', help='Require an unfinished run with matching state')
|
||||
args = parser.parse_args()
|
||||
if args.steps <= 0 or args.seconds <= 0:
|
||||
parser.error('--steps and --seconds must be positive')
|
||||
try:
|
||||
workflow = execution_workflow(args, executor_decider)
|
||||
except (OSError, ValueError) as error:
|
||||
parser.error(str(error))
|
||||
release = acquire_single_instance()
|
||||
if release is None:
|
||||
print(json.dumps({'state':'already_running'}), flush=True)
|
||||
return
|
||||
if workflow == 'aalc':
|
||||
try:
|
||||
record = delegate_mirror(new_run=args.new_run, resume=args.resume)
|
||||
save_json(RUNTIME_HOME / 'aalc_mirror_status.json', record)
|
||||
print(json.dumps(record, ensure_ascii=False), flush=True)
|
||||
finally:
|
||||
release()
|
||||
return
|
||||
log = RUNTIME_HOME / 'jev_mirror_log.jsonl'
|
||||
status = RUNTIME_HOME / 'jev_mirror_status.json'
|
||||
deadline = time.monotonic() + args.seconds
|
||||
|
||||
+2
-1
@@ -297,6 +297,7 @@ def cmd_card(ci, ri, uptie=False):
|
||||
print('详情页已打开')
|
||||
ok, desc = do_level_up()
|
||||
print('升级: %s (%s)' % ('OK' if ok else 'FAIL', desc))
|
||||
ok2 = True
|
||||
if uptie:
|
||||
ok2, desc2 = do_uptie()
|
||||
print('同步: %s (%s)' % ('OK' if ok2 else 'FAIL', desc2))
|
||||
@@ -318,7 +319,7 @@ def cmd_card(ci, ri, uptie=False):
|
||||
txt = screen_text(items)
|
||||
if not ('IDENTITIES' in txt and 'Facades' in txt):
|
||||
print('[warn] 未能回到 Identities 网格, 当前: ' + txt[:160])
|
||||
return 0 if ok else 1
|
||||
return 0 if ok and ok2 else 1
|
||||
|
||||
|
||||
# 每级升级所需经验(来源 wiki "EXP per Level" 表)。
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Ordinary mirror requests delegate to AALC without entering the click loop."""
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
import jev_mirror_agent as agent
|
||||
from mcp_session import SessionTimeout
|
||||
from run_state import save_json
|
||||
|
||||
|
||||
class AutomationDispatchTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.home = Path(folder.name)
|
||||
for patch in (mock.patch.object(agent, 'RUNTIME_HOME', self.home),
|
||||
mock.patch.object(agent, 'STOP_FILE', self.home / 'JEV_STOP'),
|
||||
mock.patch.dict(os.environ, {'LC_FIXED_FALLBACK': '0'})):
|
||||
patch.start()
|
||||
self.addCleanup(patch.stop)
|
||||
|
||||
def workflow(self, **overrides):
|
||||
args = dict(workflow='auto', config=None, decision_engine=None, new_run=False, resume=False)
|
||||
args.update(overrides)
|
||||
return agent.execution_workflow(SimpleNamespace(**args))
|
||||
|
||||
def test_ordinary_request_defaults_to_aalc(self):
|
||||
self.assertEqual(self.workflow(), 'aalc')
|
||||
|
||||
def test_special_requirements_preserve_speedrun(self):
|
||||
for args in ({'config': 'jev.json'}, {'decision_engine': 'executor'}, {'resume': True},
|
||||
{'workflow': 'speedrun'}):
|
||||
with self.subTest(args=args):
|
||||
self.assertEqual(self.workflow(**args), 'speedrun')
|
||||
save_json(self.home / 'mirror_current_run.json', {'status': 'requires_decision'})
|
||||
self.assertEqual(self.workflow(), 'speedrun')
|
||||
self.assertEqual(self.workflow(new_run=True), 'aalc')
|
||||
|
||||
def delegate(self, current, started=None, **kwargs):
|
||||
bridge = mock.Mock()
|
||||
bridge.call.side_effect = [current, started or {'ok': True, 'log': 'new.log', 'task': 'mirror'}]
|
||||
with mock.patch.object(agent, 'Bridge', return_value=bridge):
|
||||
result = agent.delegate_mirror(**kwargs)
|
||||
bridge.close.assert_called_once()
|
||||
return result, bridge
|
||||
|
||||
def test_launches_only_mirror_and_returns_monitoring_contract(self):
|
||||
result, bridge = self.delegate({'ok': True, 'state': 'idle'})
|
||||
self.assertEqual(result['state'], 'delegated')
|
||||
self.assertEqual(result['next_call']['tool'], 'task_status')
|
||||
self.assertEqual(bridge.call.call_args_list, [mock.call('task_status', {'lines': 30}),
|
||||
mock.call('run_task', {'task': 'mirror', 'count': 1})])
|
||||
run = json.loads((self.home / 'mirror_current_run.json').read_text())
|
||||
self.assertFalse(run['dungeon_completed'])
|
||||
self.assertFalse(run['final_reward_claimed'])
|
||||
self.assertEqual(self.workflow(resume=True), 'aalc')
|
||||
|
||||
def test_running_mirror_is_monitored_without_duplicate_start(self):
|
||||
result, bridge = self.delegate({'ok': True, 'state': 'running', 'task': 'mirror'})
|
||||
self.assertEqual(result['state'], 'monitoring')
|
||||
self.assertEqual(bridge.call.call_count, 1)
|
||||
|
||||
def test_other_running_task_is_not_stopped_or_replaced(self):
|
||||
result, bridge = self.delegate({'ok': True, 'state': 'running', 'task': 'daily'})
|
||||
self.assertEqual(result['state'], 'busy')
|
||||
self.assertEqual(bridge.call.call_count, 1)
|
||||
|
||||
def test_user_stop_never_restarts_without_new_request(self):
|
||||
for current in ({'ok': True, 'state': 'stopped', 'task': 'mirror'},
|
||||
{'ok': True, 'state': 'failed', 'exit_code': 130}):
|
||||
with self.subTest(current=current):
|
||||
result, bridge = self.delegate(current)
|
||||
self.assertEqual(result['state'], 'stopped')
|
||||
self.assertEqual(bridge.call.call_count, 1)
|
||||
result, bridge = self.delegate({'ok': True, 'state': 'stopped'}, new_run=True)
|
||||
self.assertEqual(result['state'], 'delegated')
|
||||
|
||||
def test_unknown_or_failed_status_never_triggers_blind_retry(self):
|
||||
for current in ({}, {'ok': False, 'error': 'offline'}, {'ok': True, 'state': 'unexpected'},
|
||||
{'ok': True, 'state': 'failed'},
|
||||
{'ok': True, 'state': 'succeeded', 'errors': ['battle failed']},
|
||||
{'ok': True, 'state': 'succeeded', 'pending_restore': ['x.restore.json']}):
|
||||
with self.subTest(current=current):
|
||||
result, bridge = self.delegate(current)
|
||||
self.assertEqual(result['state'], 'requires_analysis')
|
||||
self.assertEqual(bridge.call.call_count, 1)
|
||||
|
||||
def test_resume_checks_errors_without_launching_another_run(self):
|
||||
current = {'ok': True, 'state': 'succeeded', 'task': 'mirror', 'errors': ['battle failed']}
|
||||
result, bridge = self.delegate(current, resume=True)
|
||||
self.assertEqual(result['state'], 'requires_analysis')
|
||||
self.assertEqual(bridge.call.call_count, 1)
|
||||
|
||||
def test_resume_does_not_accept_a_different_task_as_its_result(self):
|
||||
save_json(self.home / 'mirror_current_run.json', {
|
||||
'workflow': 'aalc', 'status': 'delegated', 'task_log': 'original.log'})
|
||||
result, bridge = self.delegate({'ok': True, 'state': 'succeeded', 'task': 'mirror',
|
||||
'log': 'another.log'}, resume=True)
|
||||
self.assertEqual(result['reason'], 'task_changed')
|
||||
self.assertEqual(bridge.call.call_count, 1)
|
||||
|
||||
def test_unfinished_speedrun_blocks_unrequested_workflow_switch(self):
|
||||
save_json(self.home / 'mirror_current_run.json', {'status': 'requires_decision'})
|
||||
with mock.patch.object(agent, 'Bridge') as factory:
|
||||
result = agent.delegate_mirror()
|
||||
self.assertEqual(result['reason'], 'unfinished_speedrun')
|
||||
factory.assert_not_called()
|
||||
|
||||
def test_stop_marker_prevents_even_connecting(self):
|
||||
agent.STOP_FILE.touch()
|
||||
with mock.patch.object(agent, 'Bridge') as factory:
|
||||
self.assertEqual(agent.delegate_mirror()['state'], 'stopped')
|
||||
factory.assert_not_called()
|
||||
|
||||
def test_timeout_after_start_is_reported_without_retry_or_clicks(self):
|
||||
bridge = mock.Mock()
|
||||
error = SessionTimeout('reply lost')
|
||||
error.tool = 'run_task'
|
||||
bridge.call.side_effect = [{'ok': True, 'state': 'idle'}, error]
|
||||
with mock.patch.object(agent, 'Bridge', return_value=bridge):
|
||||
result = agent.delegate_mirror()
|
||||
self.assertEqual(result['state'], 'requires_analysis')
|
||||
self.assertTrue(result['outcome_unknown'])
|
||||
self.assertEqual(result['pending_tool'], 'run_task')
|
||||
self.assertEqual(bridge.call.call_count, 2)
|
||||
bridge.close.assert_called_once()
|
||||
|
||||
def test_plain_cli_takes_aalc_path_without_model_or_ocr(self):
|
||||
bridge = mock.Mock()
|
||||
bridge.call.side_effect = [{'ok': True, 'state': 'idle'}, {'ok': True, 'log': 'mirror.log'}]
|
||||
release = mock.Mock()
|
||||
with mock.patch.object(sys, 'argv', ['agent']), \
|
||||
mock.patch.object(agent, 'Bridge', return_value=bridge), \
|
||||
mock.patch.object(agent, 'acquire_single_instance', return_value=release), \
|
||||
mock.patch.object(agent, 'DecisionRouter') as router, \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
agent.main()
|
||||
router.assert_not_called()
|
||||
release.assert_called_once()
|
||||
result = json.loads((self.home / 'aalc_mirror_status.json').read_text())
|
||||
self.assertEqual(result['state'], 'delegated')
|
||||
self.assertEqual([call.args[0] for call in bridge.call.call_args_list], ['task_status', 'run_task'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -14,6 +14,7 @@ from unittest import mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
import convert_modules as cm # noqa: E402
|
||||
from lc_mcp import game_lock
|
||||
|
||||
|
||||
class QuietLogMixin:
|
||||
@@ -28,6 +29,62 @@ class QuietLogMixin:
|
||||
patcher = mock.patch.object(cm, 'log', lambda m: None)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
patcher = mock.patch.object(game_lock, 'default_lock_path',
|
||||
return_value=os.path.join(tmp.name, 'game.lock'))
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
patcher = mock.patch.object(cm, 'probe', return_value={'ok': True, 'state': 'idle'})
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
|
||||
class GameOwnershipTest(QuietLogMixin, unittest.TestCase):
|
||||
def test_running_task_is_not_navigated_or_closed(self):
|
||||
from lc_mcp.fake_engine import FakeEngine
|
||||
from lc_mcp.protocol import Server
|
||||
from lc_mcp.tasks import TaskRunner
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
runner = TaskRunner(tmp, argv_factory=lambda *a: [
|
||||
sys.executable, '-c', 'import time; time.sleep(30)'])
|
||||
server = Server(FakeEngine(), runner)
|
||||
runner.start('daily', {}) # Emulate an older process without the shared lock.
|
||||
try:
|
||||
with mock.patch.object(cm, 'probe', side_effect=server.call_tool), \
|
||||
mock.patch.object(cm, 'ensure_server', return_value=True), \
|
||||
mock.patch.object(cm, 'ensure_display') as display, \
|
||||
mock.patch.object(cm, 'launch_game') as launch, \
|
||||
mock.patch.object(cm, 'close_game') as close:
|
||||
self.assertEqual(cm.main(['--report-dir', tmp]), 1)
|
||||
display.assert_not_called()
|
||||
launch.assert_not_called()
|
||||
close.assert_not_called()
|
||||
self.assertTrue(runner.running())
|
||||
self.assertEqual(server.engine.actions, [])
|
||||
finally:
|
||||
runner.stop()
|
||||
|
||||
def test_unknown_status_does_not_touch_the_game(self):
|
||||
for status in ({}, {'ok': False}, {'ok': True, 'state': 'unknown'}):
|
||||
with self.subTest(status=status), tempfile.TemporaryDirectory() as tmp, \
|
||||
mock.patch.object(cm, 'probe', return_value=status), \
|
||||
mock.patch.object(cm, 'ensure_server', return_value=True), \
|
||||
mock.patch.object(cm, 'ensure_display') as display, \
|
||||
mock.patch.object(cm, 'close_game') as close:
|
||||
self.assertEqual(cm.main(['--report-dir', tmp]), 1)
|
||||
display.assert_not_called()
|
||||
close.assert_not_called()
|
||||
|
||||
def test_existing_owner_prevents_even_service_startup(self):
|
||||
with tempfile.TemporaryDirectory() as tmp, \
|
||||
mock.patch.object(cm, 'ensure_server') as server, \
|
||||
mock.patch.object(cm, 'close_game') as close, \
|
||||
game_lock.exclusive_game():
|
||||
self.assertEqual(cm.main(['--report-dir', tmp]), 1)
|
||||
server.assert_not_called()
|
||||
close.assert_not_called()
|
||||
|
||||
|
||||
class ScreenDetectTest(QuietLogMixin, unittest.TestCase):
|
||||
@@ -603,6 +660,14 @@ class CliRoutingTest(QuietLogMixin, unittest.TestCase):
|
||||
done = []
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
|
||||
def close_owned_game():
|
||||
# Ownership must cover shutdown too, so a new task cannot start here.
|
||||
with self.assertRaises(game_lock.GameBusyError):
|
||||
with game_lock.exclusive_game():
|
||||
pass
|
||||
closed.append(1)
|
||||
|
||||
with mock.patch.object(cm, 'read_enkephalin', lambda: 4), \
|
||||
mock.patch.object(cm, 'read_lunacy', lambda **k: 9699), \
|
||||
mock.patch.object(cm, 'ensure_server', lambda *a: True), \
|
||||
@@ -611,7 +676,7 @@ class CliRoutingTest(QuietLogMixin, unittest.TestCase):
|
||||
mock.patch.object(cm, 'wait_main_menu', lambda *a: True), \
|
||||
mock.patch.object(cm, 'ensure_window_size', lambda *a: (1600, 900)), \
|
||||
mock.patch.object(cm, 'close_panel', lambda: True), \
|
||||
mock.patch.object(cm, 'close_game', lambda: closed.append(1)), \
|
||||
mock.patch.object(cm, 'close_game', close_owned_game), \
|
||||
mock.patch.object(cm.time, 'sleep', lambda s: None):
|
||||
code = cm.main(argv + ['--report-dir', tmp])
|
||||
done.append(os.listdir(tmp))
|
||||
|
||||
+182
-4
@@ -10,6 +10,7 @@
|
||||
关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。
|
||||
"""
|
||||
import sys
|
||||
import contextlib
|
||||
import os
|
||||
import ast
|
||||
import inspect
|
||||
@@ -132,7 +133,8 @@ class ClickTest(unittest.TestCase):
|
||||
{'v': (pos['v'][0] + dx, pos['v'][1] + dy)})
|
||||
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
|
||||
mock.patch.object(di.time, 'sleep', lambda s: None):
|
||||
self.assertTrue(d.click(500, 400))
|
||||
# 这里只测定位逻辑, 前台校验另有 ForegroundCheckTest
|
||||
self.assertTrue(d.click(500, 400, require_foreground=False))
|
||||
self.assertEqual(pos['v'], (500, 400))
|
||||
d._dll.mouse_down.assert_called_once_with(1)
|
||||
d._dll.mouse_up.assert_called_once_with(1)
|
||||
@@ -141,7 +143,7 @@ class ClickTest(unittest.TestCase):
|
||||
d = self._drv(False)
|
||||
with mock.patch.object(di, 'get_cursor', lambda: (0, 0)), \
|
||||
mock.patch.object(di.time, 'sleep', lambda s: None):
|
||||
self.assertFalse(d.click(500, 400))
|
||||
self.assertFalse(d.click(500, 400, require_foreground=False))
|
||||
d._dll.mouse_down.assert_not_called()
|
||||
d._dll.mouse_up.assert_not_called()
|
||||
|
||||
@@ -325,6 +327,10 @@ class DriverWiringTest(unittest.TestCase):
|
||||
with mock.patch.dict(sys.modules, modules), \
|
||||
mock.patch.dict(os.environ, LCP_DRIVER_INPUT='1', LCP_RESTORE_FILE=''), \
|
||||
mock.patch.object(aalc_task, 'bootstrap'), \
|
||||
mock.patch.object(aalc_task, 'exclusive_game'), \
|
||||
mock.patch.object(aalc_task, 'headless_hdr_warning') as hdr_warning, \
|
||||
mock.patch.object(aalc_task, 'mirror_progress',
|
||||
lambda scheme: contextlib.nullcontext(ap.MirrorProgress())), \
|
||||
mock.patch.object(aalc_task, 'install_exact_team_match'), \
|
||||
mock.patch.object(aalc_task, 'install_robust_set_foreground'), \
|
||||
mock.patch.object(aalc_task, 'WindowGuard'), \
|
||||
@@ -337,6 +343,7 @@ class DriverWiringTest(unittest.TestCase):
|
||||
mock.patch.object(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)):
|
||||
self.assertEqual(aalc_task.run(task, {}), 3 if problems else 0)
|
||||
install_hotkey.return_value.stop.assert_called_once()
|
||||
self.assertEqual(hdr_warning.call_count, int(task == 'all' and not problems))
|
||||
if problems:
|
||||
drv.click.assert_not_called()
|
||||
else:
|
||||
@@ -360,8 +367,10 @@ class DriverFailureTest(unittest.TestCase):
|
||||
drv = di.DriverInput()
|
||||
drv._open, drv._dll = True, mock.Mock()
|
||||
with mock.patch.object(drv, 'move_to', return_value=True), \
|
||||
mock.patch.object(di, 'click_point_is_on_foreground', lambda *a, **k: (True, 'ok')), \
|
||||
mock.patch.object(di.time, 'sleep', side_effect=lambda _: drv.emergency_stop()):
|
||||
self.assertFalse(drv.click(10, 20, times=3))
|
||||
# settle=0: 第一次 sleep 是按下后的按住时长, 急停发生在按住期间
|
||||
self.assertFalse(drv.click(10, 20, times=3, settle=0))
|
||||
drv._dll.mouse_down.assert_called_once_with(1)
|
||||
drv._dll.mouse_up.assert_called_with(1)
|
||||
self.assertFalse(drv.ready)
|
||||
@@ -375,9 +384,12 @@ class DriverFailureTest(unittest.TestCase):
|
||||
drv = di.DriverInput()
|
||||
drv._open, drv._dll = True, mock.Mock()
|
||||
with mock.patch.object(drv, 'move_to', return_value=True), \
|
||||
mock.patch.object(di, 'click_point_is_on_foreground',
|
||||
lambda *a, **k: (True, '')), \
|
||||
mock.patch.object(di.time, 'sleep', side_effect=InterruptedError):
|
||||
with self.assertRaises(InterruptedError):
|
||||
drv.click(1, 2)
|
||||
# settle=0 让第一个 sleep 出现在按下之后, 测的才是 try/finally
|
||||
drv.click(1, 2, require_foreground=False, settle=0)
|
||||
drv._dll.mouse_up.assert_called_once_with(1)
|
||||
|
||||
def test_release_even_if_coordinate_lookup_fails(self):
|
||||
@@ -455,5 +467,171 @@ class ForegroundFallbackTest(unittest.TestCase):
|
||||
[mock.call(33, 11, True), mock.call(33, 11, False)])
|
||||
|
||||
|
||||
|
||||
def win_api(**functions):
|
||||
"""按 API 名替换 driver_input._api 返回的函数。"""
|
||||
return mock.patch.object(di, '_api', side_effect=lambda library, name, result, args: functions[name])
|
||||
|
||||
|
||||
def window_rect(left, top, right, bottom):
|
||||
def get_window_rect(hwnd, ptr):
|
||||
r = ptr._obj
|
||||
r.left, r.top, r.right, r.bottom = left, top, right, bottom
|
||||
return 1
|
||||
return get_window_rect
|
||||
|
||||
|
||||
class ForegroundCheckTest(unittest.TestCase):
|
||||
"""位置对却点不上 —— 头号原因是前台不是游戏。
|
||||
|
||||
2026-10-23 实测: 窗口位置和坐标换算都正确, 但前台是浏览器, 点击全部落到
|
||||
浏览器里, 而旧版 click() 照样返回 True。这组测试守住"必须拒绝"这一条。
|
||||
"""
|
||||
|
||||
def _drv(self):
|
||||
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
|
||||
d._dll = mock.Mock()
|
||||
d._open = True
|
||||
return d
|
||||
|
||||
def test_rejects_when_no_foreground_window(self):
|
||||
with mock.patch.object(di, 'foreground_window', return_value=None):
|
||||
ok, why = di.click_point_is_on_foreground(100, 100)
|
||||
self.assertFalse(ok)
|
||||
self.assertIn('前台窗口', why)
|
||||
|
||||
def test_rejects_when_point_outside_foreground_window(self):
|
||||
with mock.patch.object(di, 'foreground_window', return_value=12345), \
|
||||
win_api(GetWindowRect=window_rect(0, 0, 50, 50)):
|
||||
ok, why = di.click_point_is_on_foreground(999, 999)
|
||||
self.assertFalse(ok)
|
||||
self.assertIn('不在前台窗口内', why)
|
||||
|
||||
def test_accepts_when_point_inside_foreground_window(self):
|
||||
with mock.patch.object(di, 'foreground_window', return_value=12345), \
|
||||
win_api(GetWindowRect=window_rect(0, 0, 1920, 1080)):
|
||||
ok, why = di.click_point_is_on_foreground(500, 500)
|
||||
self.assertTrue(ok)
|
||||
self.assertEqual(why, 'ok')
|
||||
|
||||
def test_click_refuses_when_check_fails(self):
|
||||
"""校验不过 -> 一个按键都不许发。"""
|
||||
pos = {'v': (500, 400)}
|
||||
d = self._drv()
|
||||
d._dll.moveR.side_effect = lambda dx, dy, _: None
|
||||
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
|
||||
mock.patch.object(di.time, 'sleep', lambda s: None), \
|
||||
mock.patch.object(di, 'click_point_is_on_foreground',
|
||||
lambda *a, **k: (False, '')):
|
||||
self.assertFalse(d.click(500, 400))
|
||||
d._dll.mouse_down.assert_not_called()
|
||||
d._dll.mouse_up.assert_not_called()
|
||||
|
||||
def test_click_proceeds_when_check_passes(self):
|
||||
pos = {'v': (500, 400)}
|
||||
d = self._drv()
|
||||
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
|
||||
mock.patch.object(di.time, 'sleep', lambda s: None), \
|
||||
mock.patch.object(di, 'click_point_is_on_foreground',
|
||||
lambda *a, **k: (True, '')):
|
||||
self.assertTrue(d.click(500, 400))
|
||||
d._dll.mouse_down.assert_called_once_with(1)
|
||||
d._dll.mouse_up.assert_called_once_with(1)
|
||||
|
||||
def test_press_duration_is_passed_through(self):
|
||||
"""按下时长必须真的用上 —— 30ms 在掉帧时会漏点。"""
|
||||
pos = {'v': (500, 400)}
|
||||
d = self._drv()
|
||||
slept = []
|
||||
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
|
||||
mock.patch.object(di.time, 'sleep', lambda s: slept.append(s)), \
|
||||
mock.patch.object(di, 'click_point_is_on_foreground',
|
||||
lambda *a, **k: (True, '')):
|
||||
d.click(500, 400, press_ms=120, settle=0)
|
||||
self.assertIn(0.12, slept, '按下时长没生效')
|
||||
|
||||
def test_settle_delay_happens_before_press(self):
|
||||
"""定位成功到按下之间要有间隔, 否则游戏把这次点击算在旧位置。"""
|
||||
pos = {'v': (500, 400)}
|
||||
d = self._drv()
|
||||
order = []
|
||||
d._dll.mouse_down.side_effect = lambda b: order.append('down')
|
||||
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
|
||||
mock.patch.object(di, 'click_point_is_on_foreground',
|
||||
lambda *a, **k: (True, '')), \
|
||||
mock.patch.object(di.time, 'sleep',
|
||||
lambda s: order.append('sleep%.2f' % s)):
|
||||
d.click(500, 400, settle=0.08)
|
||||
self.assertIn('down', order)
|
||||
self.assertTrue(any(x.startswith('sleep') for x in order[:order.index('down')]),
|
||||
'按下之前必须有 sleep')
|
||||
|
||||
class HwndForegroundCheckTest(unittest.TestCase):
|
||||
"""句柄级前台校验。
|
||||
|
||||
⛔ 为什么不能只比矩形(2026-10-23 实测): 把浏览器切到前台, 点游戏里同一个
|
||||
坐标, 只判断"点在不在前台窗口矩形内"的话**照样通过** —— 因为那个屏幕坐标
|
||||
同时也落在浏览器窗口的矩形里。窗口重叠时几何判断毫无意义。
|
||||
|
||||
给了 hwnd 就必须要求前台窗口就是它。
|
||||
"""
|
||||
|
||||
def test_accepts_when_foreground_is_the_target(self):
|
||||
with mock.patch.object(di, 'foreground_window', return_value=999):
|
||||
ok, why = di.click_point_is_on_foreground(100, 100, 999)
|
||||
self.assertTrue(ok)
|
||||
self.assertEqual(why, 'ok')
|
||||
|
||||
def test_accepts_child_window_of_target(self):
|
||||
"""游戏可能有子窗口拿到焦点, 也算在目标窗口上。"""
|
||||
is_child = mock.Mock(return_value=True)
|
||||
with mock.patch.object(di, 'foreground_window', return_value=1000), \
|
||||
win_api(IsChild=is_child):
|
||||
ok, _ = di.click_point_is_on_foreground(100, 100, 999)
|
||||
is_child.assert_called_once_with(999, 1000)
|
||||
self.assertTrue(ok)
|
||||
|
||||
def test_rejects_when_foreground_is_another_window(self):
|
||||
titles = {1000: 'Browser', 999: 'LimbusCompany'}
|
||||
with mock.patch.object(di, 'foreground_window', return_value=1000), \
|
||||
win_api(IsChild=mock.Mock(return_value=False)), \
|
||||
mock.patch.object(di, 'window_title', side_effect=titles.get):
|
||||
ok, why = di.click_point_is_on_foreground(100, 100, 999)
|
||||
self.assertFalse(ok)
|
||||
self.assertIn('前台不是目标窗口', why)
|
||||
self.assertIn('Browser', why)
|
||||
|
||||
def test_bind_window_is_used_by_click(self):
|
||||
"""绑定窗口后, click() 必须走句柄级校验。"""
|
||||
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
|
||||
d._dll = mock.Mock()
|
||||
d._open = True
|
||||
d.bind_window(4242)
|
||||
self.assertEqual(d.hwnd, 4242)
|
||||
seen = {}
|
||||
|
||||
def fake_check(sx, sy, hwnd=None):
|
||||
seen['hwnd'] = hwnd
|
||||
return False, '前台不是目标窗口'
|
||||
|
||||
with mock.patch.object(di, 'get_cursor', lambda: (10, 10)), \
|
||||
mock.patch.object(di, 'click_point_is_on_foreground', fake_check), \
|
||||
mock.patch.object(di.time, 'sleep', lambda s: None):
|
||||
self.assertFalse(d.click(10, 10))
|
||||
self.assertEqual(seen['hwnd'], 4242, 'click 没把绑定的句柄传下去')
|
||||
d._dll.mouse_down.assert_not_called()
|
||||
|
||||
def test_proxy_rebinds_current_window_before_each_click(self):
|
||||
"""游戏重启后句柄会变; 代理复用时若仍拿安装时的旧句柄, 前台校验会拒绝所有点击。"""
|
||||
drv = di.DriverInput(dll_path='X.dll', log=lambda m: None).bind_window(111)
|
||||
handle = SimpleNamespace(hwnd=222, isMinimized=False, setForeground=mock.Mock())
|
||||
proxy = ap.DriverClickProxy(mock.Mock(), drv, SimpleNamespace(handle=handle), log=lambda _: None)
|
||||
with mock.patch.object(di, 'is_console_session', return_value=True), \
|
||||
mock.patch.object(di, 'foreground_window', return_value=222), \
|
||||
mock.patch.object(di, 'client_to_screen', return_value=(5, 6)):
|
||||
self.assertEqual(proxy._screen_pos(1, 2), (5, 6))
|
||||
self.assertEqual(drv.hwnd, 222)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from lc_mcp import aalc_task, game_lock
|
||||
|
||||
|
||||
class GameLockTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.path = os.path.join(tmp.name, 'game.lock')
|
||||
|
||||
def test_exception_releases_lock_without_deleting_file(self):
|
||||
with self.assertRaisesRegex(RuntimeError, 'failed'):
|
||||
with game_lock.exclusive_game(self.path):
|
||||
raise RuntimeError('failed')
|
||||
self.assertTrue(os.path.exists(self.path))
|
||||
with game_lock.exclusive_game(self.path):
|
||||
with self.assertRaises(game_lock.GameBusyError):
|
||||
with game_lock.exclusive_game(self.path):
|
||||
self.fail('second owner acquired the game')
|
||||
|
||||
def test_process_lock_is_released_after_hard_exit(self):
|
||||
ready = self.path + '.ready'
|
||||
code = '''
|
||||
import os, sys, time
|
||||
from lc_mcp.game_lock import exclusive_game
|
||||
with exclusive_game(sys.argv[1]):
|
||||
with open(sys.argv[2], 'w') as marker:
|
||||
marker.write('ready')
|
||||
time.sleep(30)
|
||||
'''
|
||||
with subprocess.Popen([sys.executable, '-c', code, self.path, ready],
|
||||
cwd=Path(__file__).resolve().parents[1],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
while not os.path.exists(ready) and proc.poll() is None and time.monotonic() < deadline:
|
||||
time.sleep(.01)
|
||||
self.assertTrue(os.path.exists(ready), 'child did not acquire the lock')
|
||||
with self.assertRaises(game_lock.GameBusyError):
|
||||
with game_lock.exclusive_game(self.path):
|
||||
self.fail('parent acquired a live child lock')
|
||||
finally:
|
||||
proc.kill()
|
||||
proc.communicate(timeout=5)
|
||||
with game_lock.exclusive_game(self.path):
|
||||
pass
|
||||
|
||||
def test_task_refuses_converter_lock_before_bootstrap(self):
|
||||
with mock.patch.object(game_lock, 'default_lock_path', return_value=self.path), \
|
||||
mock.patch.object(aalc_task, 'bootstrap') as bootstrap, \
|
||||
mock.patch.object(aalc_task, 'log'):
|
||||
with game_lock.exclusive_game():
|
||||
self.assertEqual(aalc_task.run('daily', {}), aalc_task.PREFLIGHT_EXIT)
|
||||
bootstrap.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
+163
-104
@@ -7,14 +7,14 @@
|
||||
目标点。所以任务跑起来时鼠标是"拔河"状态, 用户没法用鼠标去点停止按钮。键盘不受
|
||||
影响, 所以急停必须走键盘。
|
||||
|
||||
AALC 自带的 pause_hotkey 帮不上忙: 那个配置项只在 GUI(app/farming_interface.py)
|
||||
里注册, lc_mcp 走命令行子进程, 那条路径上没有热键监听。这是本模块存在的原因。
|
||||
实现上踩过一个坑: 先用了 pynput 的 GlobalHotKeys, 静态注册成功、线程也活着, 但
|
||||
keybd_event 和 SendInput 两种注入都触发不了它 —— 钩子在当前会话下收不到键。
|
||||
改成 GetAsyncKeyState 轮询后实测可用。这里的测试守住轮询方案的几个关键性质,
|
||||
以及急停时"先放开鼠标、卡住也按时退出"的保证。
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import tempfile
|
||||
import time
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
@@ -22,134 +22,183 @@ from unittest import mock
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from lc_mcp import killswitch # noqa: E402
|
||||
|
||||
PRESSED = -32768 # SHORT 0x8000: GetAsyncKeyState 的"当前按下"位
|
||||
|
||||
class KeySpecTest(unittest.TestCase):
|
||||
|
||||
def test_wraps_plain_name(self):
|
||||
self.assertEqual(killswitch._key_spec('f12'), '<f12>')
|
||||
def key_state(value):
|
||||
return mock.patch.object(killswitch, '_key_state_api', return_value=lambda vk: value)
|
||||
|
||||
def test_keeps_already_wrapped(self):
|
||||
self.assertEqual(killswitch._key_spec('<f11>'), '<f11>')
|
||||
|
||||
def test_lowercases_and_trims(self):
|
||||
self.assertEqual(killswitch._key_spec(' F12 '), '<f12>')
|
||||
class ResolveVkTest(unittest.TestCase):
|
||||
"""键名解析必须严格: 认不出来要返回 None, 不能悄悄用默认值 ——
|
||||
否则用户以为设成了 F11, 实际还在监听别的键。"""
|
||||
|
||||
def test_empty_falls_back_to_default(self):
|
||||
self.assertEqual(killswitch._key_spec(''), '<f12>')
|
||||
self.assertEqual(killswitch._key_spec(None), '<f12>')
|
||||
self.assertEqual(killswitch._key_spec(' '), '<f12>')
|
||||
def test_common_keys(self):
|
||||
self.assertEqual(killswitch.resolve_vk('f12'), 0x7B)
|
||||
self.assertEqual(killswitch.resolve_vk('F11'), 0x7A)
|
||||
self.assertEqual(killswitch.resolve_vk('esc'), 0x1B)
|
||||
self.assertEqual(killswitch.resolve_vk('pause'), 0x13)
|
||||
|
||||
def test_default_is_end_not_steam_screenshot_key(self):
|
||||
self.assertEqual(killswitch.DEFAULT_KEY, 'end')
|
||||
self.assertEqual(killswitch.resolve_vk(None), 0x23)
|
||||
|
||||
def test_accepts_angle_brackets(self):
|
||||
self.assertEqual(killswitch.resolve_vk('<f12>'), 0x7B)
|
||||
|
||||
def test_trims_whitespace(self):
|
||||
self.assertEqual(killswitch.resolve_vk(' F12 '), 0x7B)
|
||||
|
||||
def test_empty_uses_default(self):
|
||||
for key in ('', None, ' '):
|
||||
self.assertEqual(killswitch.resolve_vk(key), killswitch.VK[killswitch.DEFAULT_KEY])
|
||||
|
||||
def test_unknown_returns_none(self):
|
||||
self.assertIsNone(killswitch.resolve_vk('nosuchkey'))
|
||||
|
||||
|
||||
class InstallTest(unittest.TestCase):
|
||||
"""装不上不能把任务带崩,但必须说清楚怎么应急。"""
|
||||
|
||||
def test_reports_when_pynput_is_missing(self):
|
||||
def test_reports_unknown_key_and_suggests_fallback(self):
|
||||
lines = []
|
||||
with mock.patch.dict(sys.modules, {'pynput': None}):
|
||||
got = killswitch.install(log=lines.append, key='f12')
|
||||
got = killswitch.install(log=lines.append, key='nosuchkey')
|
||||
self.assertIsNone(got)
|
||||
joined = '\n'.join(lines)
|
||||
self.assertIn('认不出键名', joined)
|
||||
self.assertIn('Ctrl+Alt+Del', joined, '必须给出应急手段')
|
||||
|
||||
def test_reports_when_keyboard_api_is_unavailable(self):
|
||||
lines = []
|
||||
with mock.patch.object(killswitch, '_key_state_api', side_effect=AttributeError('no user32')):
|
||||
got = killswitch.install(log=lines.append)
|
||||
self.assertIsNone(got)
|
||||
joined = '\n'.join(lines)
|
||||
self.assertIn('急停热键不可用', joined)
|
||||
self.assertIn('Ctrl+Alt+Del', joined, '必须给出应急手段')
|
||||
self.assertIn('Ctrl+Alt+Del', joined)
|
||||
|
||||
def test_registers_the_configured_key(self):
|
||||
listener = mock.Mock()
|
||||
listener.daemon = False
|
||||
fake_keyboard = mock.Mock()
|
||||
fake_keyboard.GlobalHotKeys.return_value = listener
|
||||
with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard),
|
||||
'pynput.keyboard': fake_keyboard}):
|
||||
got = killswitch.install(log=lambda m: None, key='f11')
|
||||
self.assertIs(got, listener)
|
||||
fake_keyboard.GlobalHotKeys.assert_called_once()
|
||||
self.assertIn('<f11>', fake_keyboard.GlobalHotKeys.call_args[0][0])
|
||||
listener.start.assert_called_once()
|
||||
self.assertTrue(listener.daemon)
|
||||
def test_installs_and_logs_the_key(self):
|
||||
lines = []
|
||||
with key_state(0), mock.patch.object(killswitch.KillSwitch, 'start', lambda self: self):
|
||||
switch = killswitch.install(log=lines.append, key='f11')
|
||||
self.assertIsInstance(switch, killswitch.KillSwitch)
|
||||
self.assertEqual(switch.vk, 0x7A)
|
||||
joined = '\n'.join(lines)
|
||||
self.assertIn('F11', joined)
|
||||
self.assertIn('游戏窗口保留', joined)
|
||||
|
||||
def test_env_var_overrides_default_key(self):
|
||||
listener = mock.Mock()
|
||||
fake_keyboard = mock.Mock()
|
||||
fake_keyboard.GlobalHotKeys.return_value = listener
|
||||
with mock.patch.dict(os.environ, {'LCP_KILL_KEY': 'pause'}), \
|
||||
mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard),
|
||||
'pynput.keyboard': fake_keyboard}):
|
||||
killswitch.install(log=lambda m: None)
|
||||
self.assertIn('<pause>', fake_keyboard.GlobalHotKeys.call_args[0][0])
|
||||
def test_env_var_overrides_default(self):
|
||||
with mock.patch.dict(killswitch.os.environ, {'LCP_KILL_KEY': 'esc'}), key_state(0), \
|
||||
mock.patch.object(killswitch.KillSwitch, 'start', lambda self: self):
|
||||
switch = killswitch.install(log=lambda m: None)
|
||||
self.assertEqual(switch.vk, 0x1B)
|
||||
|
||||
def test_start_failure_is_reported_not_raised(self):
|
||||
lines = []
|
||||
with key_state(0), mock.patch.object(killswitch.KillSwitch, 'start',
|
||||
side_effect=RuntimeError('boom')):
|
||||
got = killswitch.install(log=lines.append)
|
||||
self.assertIsNone(got)
|
||||
self.assertIn('启动失败', '\n'.join(lines))
|
||||
|
||||
|
||||
class ActivateTest(unittest.TestCase):
|
||||
def _grab_handler(self, log=lambda _: None, on_stop=None):
|
||||
listener = mock.Mock()
|
||||
keyboard = mock.Mock()
|
||||
keyboard.GlobalHotKeys.return_value = listener
|
||||
with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=keyboard)}):
|
||||
killswitch.install(log=log, on_stop=on_stop)
|
||||
return next(iter(keyboard.GlobalHotKeys.call_args.args[0].values())), listener
|
||||
class PollingTest(unittest.TestCase):
|
||||
"""轮询判断的核心:0x8000 位。测错位会导致"一直触发"或"永不触发"。"""
|
||||
|
||||
def fire(self, handler, listener):
|
||||
handler()
|
||||
listener._lc_state['worker'].join(2)
|
||||
self.assertFalse(listener._lc_state['worker'].is_alive())
|
||||
def test_high_bit_means_pressed(self):
|
||||
for value in (PRESSED, PRESSED | 1):
|
||||
with self.subTest(value=value), key_state(value):
|
||||
self.assertTrue(killswitch._pressed(0x7B))
|
||||
|
||||
def test_low_bits_are_not_pressed(self):
|
||||
# 0x0001 表示"上次调用后被按过", 不代表当前按住 —— 不能当成按下
|
||||
with key_state(0x0001):
|
||||
self.assertFalse(killswitch._pressed(0x7B))
|
||||
|
||||
def test_zero_is_not_pressed(self):
|
||||
with key_state(0):
|
||||
self.assertFalse(killswitch._pressed(0x7B))
|
||||
|
||||
def test_poll_thread_fires_on_press(self):
|
||||
sw = killswitch.KillSwitch(0x23, log=lambda m: None)
|
||||
exited = threading.Event()
|
||||
with key_state(PRESSED), mock.patch.object(killswitch, 'START_DELAY', 0), \
|
||||
mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: exited.set()):
|
||||
sw.start()
|
||||
self.assertTrue(exited.wait(2))
|
||||
sw._thread.join(2)
|
||||
self.assertTrue(sw.fired)
|
||||
|
||||
def test_broken_api_stops_polling_with_a_message(self):
|
||||
lines = []
|
||||
sw = killswitch.KillSwitch(0x23, log=lines.append)
|
||||
with mock.patch.object(killswitch, '_key_state_api', side_effect=OSError('gone')), \
|
||||
mock.patch.object(killswitch, 'START_DELAY', 0), \
|
||||
mock.patch.object(killswitch.os, '_exit') as fake_exit:
|
||||
sw.start()
|
||||
sw._thread.join(2)
|
||||
self.assertFalse(sw.is_alive())
|
||||
fake_exit.assert_not_called()
|
||||
self.assertIn('急停热键失效', '\n'.join(lines))
|
||||
|
||||
|
||||
class FireTest(unittest.TestCase):
|
||||
|
||||
def _switch(self, log=lambda m: None, on_stop=None):
|
||||
return killswitch.KillSwitch(0x23, log=log, key_name='end', on_stop=on_stop)
|
||||
|
||||
def test_exits_with_user_abort_code_and_only_fires_once(self):
|
||||
handler, listener = self._grab_handler()
|
||||
sw = self._switch()
|
||||
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
|
||||
self.fire(handler, listener)
|
||||
handler()
|
||||
sw._fire()
|
||||
sw._fire()
|
||||
sw._fire()
|
||||
fake_exit.assert_called_once_with(killswitch.EXIT_CODE)
|
||||
|
||||
def test_broken_log_cannot_disable_the_hotkey(self):
|
||||
log = mock.Mock()
|
||||
handler, listener = self._grab_handler(log=log)
|
||||
log.reset_mock()
|
||||
log.side_effect = OSError('closed log')
|
||||
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
|
||||
self.fire(handler, listener)
|
||||
fake_exit.assert_called_once_with(130)
|
||||
log.assert_not_called()
|
||||
def test_logs_that_game_is_kept(self):
|
||||
lines = []
|
||||
with mock.patch.object(killswitch.os, '_exit'):
|
||||
self._switch(log=lines.append)._fire()
|
||||
joined = '\n'.join(lines)
|
||||
self.assertIn('END', joined)
|
||||
self.assertIn('重新开始', joined)
|
||||
|
||||
def test_releases_input_before_exiting_even_when_cleanup_raises(self):
|
||||
def test_releases_input_before_logging_and_exiting(self):
|
||||
calls = []
|
||||
sw = self._switch(log=lambda m: calls.append('log'), on_stop=lambda: calls.append('release'))
|
||||
with mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: calls.append(code)):
|
||||
sw._fire()
|
||||
self.assertEqual(calls, ['release', 'log', 130])
|
||||
|
||||
def test_broken_cleanup_or_log_cannot_disable_the_hotkey(self):
|
||||
def cleanup():
|
||||
calls.append('release')
|
||||
raise OSError('driver disconnected')
|
||||
handler, listener = self._grab_handler(on_stop=cleanup)
|
||||
# 不让测试线程输出预期的异常 traceback。
|
||||
with mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: calls.append(code)), \
|
||||
mock.patch.object(threading, 'excepthook'):
|
||||
self.fire(handler, listener)
|
||||
self.assertEqual(calls, ['release', 130])
|
||||
log = mock.Mock(side_effect=OSError('closed log'))
|
||||
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
|
||||
self._switch(log=log, on_stop=cleanup)._fire()
|
||||
fake_exit.assert_called_once_with(130)
|
||||
|
||||
def test_hung_cleanup_cannot_block_exit_deadline(self):
|
||||
release, exited = threading.Event(), threading.Event()
|
||||
handler, listener = self._grab_handler(on_stop=release.wait)
|
||||
sw = self._switch(on_stop=release.wait)
|
||||
with mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: exited.set()):
|
||||
handler()
|
||||
worker = threading.Thread(target=sw._fire, daemon=True)
|
||||
worker.start()
|
||||
try:
|
||||
self.assertTrue(exited.wait(2), '清理卡住也必须触发强退')
|
||||
finally:
|
||||
release.set()
|
||||
listener._lc_state['worker'].join(2)
|
||||
|
||||
def test_startup_message_explains_game_is_kept(self):
|
||||
lines = []
|
||||
self._grab_handler(log=lines.append)
|
||||
self.assertIn('游戏窗口保留', '\n'.join(lines))
|
||||
worker.join(2)
|
||||
|
||||
def test_real_emergency_exit_is_reported_as_stopped(self):
|
||||
from lc_mcp.tasks import TaskRunner
|
||||
child = """
|
||||
import json, os, sys, time
|
||||
from types import SimpleNamespace
|
||||
import json, os, time
|
||||
from lc_mcp import killswitch
|
||||
from lc_mcp.aalc_task import RESTORE_ENV
|
||||
class Listener:
|
||||
def __init__(self, bindings): self.activate = next(iter(bindings.values()))
|
||||
def start(self): pass
|
||||
sys.modules['pynput'] = SimpleNamespace(keyboard=SimpleNamespace(GlobalHotKeys=Listener))
|
||||
listener = killswitch.install(log=lambda msg: None)
|
||||
with open(os.environ[RESTORE_ENV], 'w') as f: json.dump({'set_mirror_count': 1}, f)
|
||||
listener.activate()
|
||||
killswitch._key_state_api = lambda: (lambda vk: -32768)
|
||||
killswitch.install(log=lambda msg: None)
|
||||
time.sleep(10)
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
@@ -167,28 +216,38 @@ class StopTest(unittest.TestCase):
|
||||
def test_stop_is_safe_on_none(self):
|
||||
killswitch.stop(None) # 不该抛
|
||||
|
||||
def test_stop_calls_listener(self):
|
||||
listener = mock.Mock()
|
||||
killswitch.stop(listener)
|
||||
listener.stop.assert_called_once()
|
||||
def test_stop_calls_switch(self):
|
||||
sw = mock.Mock()
|
||||
killswitch.stop(sw)
|
||||
sw.stop.assert_called_once()
|
||||
|
||||
def test_listening_stops_on_return_and_exception(self):
|
||||
def test_stop_swallows_errors(self):
|
||||
sw = mock.Mock()
|
||||
sw.stop.side_effect = RuntimeError('boom')
|
||||
killswitch.stop(sw) # 不该抛
|
||||
|
||||
def test_stopped_switch_does_not_poll(self):
|
||||
sw = killswitch.KillSwitch(0x23, log=lambda m: None)
|
||||
with key_state(PRESSED), mock.patch.object(killswitch.os, '_exit') as fake_exit:
|
||||
sw.stop()
|
||||
sw.start()
|
||||
sw._thread.join(2)
|
||||
fake_exit.assert_not_called()
|
||||
|
||||
def test_listening_passes_cleanup_and_stops_on_return_and_exception(self):
|
||||
cleanup = object()
|
||||
for failure in (False, True):
|
||||
listener = mock.Mock()
|
||||
switch = mock.Mock()
|
||||
with self.subTest(failure=failure), \
|
||||
mock.patch.object(killswitch, 'install', return_value=listener):
|
||||
mock.patch.object(killswitch, 'install', return_value=switch) as install:
|
||||
try:
|
||||
with killswitch.listening():
|
||||
with killswitch.listening(on_stop=cleanup):
|
||||
if failure:
|
||||
raise RuntimeError('task failed')
|
||||
except RuntimeError:
|
||||
pass
|
||||
listener.stop.assert_called_once()
|
||||
|
||||
def test_stop_swallows_listener_errors(self):
|
||||
listener = mock.Mock()
|
||||
listener.stop.side_effect = RuntimeError('boom')
|
||||
killswitch.stop(listener) # 不该抛
|
||||
self.assertIs(install.call_args.kwargs['on_stop'], cleanup)
|
||||
switch.stop.assert_called_once()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
+21
-7
@@ -18,7 +18,7 @@ sys.path.insert(0, REPO)
|
||||
from lc_mcp import server as srv_mod # noqa: E402
|
||||
from lc_mcp.engine import find_hits # noqa: E402
|
||||
from lc_mcp.fake_engine import FakeEngine # noqa: E402
|
||||
from lc_mcp.protocol import Server, TOOLS # noqa: E402
|
||||
from lc_mcp.protocol import AUTOMATION_INSTRUCTIONS, Server, TOOLS # noqa: E402
|
||||
from lc_mcp.tasks import TaskRunner # noqa: E402
|
||||
|
||||
START = {'text': '开始', 'x': 100, 'y': 200, 'w': 40, 'h': 20}
|
||||
@@ -67,6 +67,7 @@ class ProtocolTest(unittest.TestCase):
|
||||
def test_initialize_and_list(self):
|
||||
r = self.s.handle({'jsonrpc': '2.0', 'id': 7, 'method': 'initialize', 'params': {}})
|
||||
self.assertEqual(r['id'], 7)
|
||||
self.assertEqual(r['result']['instructions'], AUTOMATION_INSTRUCTIONS)
|
||||
names = [t['name'] for t in self.s.handle({'jsonrpc': '2.0', 'id': 8, 'method': 'tools/list'})['result']['tools']]
|
||||
self.assertEqual(names, [t['name'] for t in TOOLS])
|
||||
self.assertIsNone(self.s.handle({'jsonrpc': '2.0', 'method': 'notifications/initialized'}))
|
||||
@@ -213,7 +214,7 @@ class AalcTaskArgsTest(unittest.TestCase):
|
||||
|
||||
class Cfg:
|
||||
def __init__(self):
|
||||
self.values, self.saved, self.flushes = {'set_mirror_count': 1}, {}, 0
|
||||
self.values, self.saved, self.flushes = {'set_mirror_count': 1, 'infinite_dungeons': True}, {}, 0
|
||||
|
||||
def get_value(self, key):
|
||||
return self.values[key]
|
||||
@@ -228,20 +229,33 @@ class AalcTaskArgsTest(unittest.TestCase):
|
||||
self.flushes += 1
|
||||
|
||||
cfg = Cfg()
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
before = {'set_mirror_count': 1, 'infinite_dungeons': True}
|
||||
lines = []
|
||||
with tempfile.TemporaryDirectory() as d, mock.patch.object(aalc_task, 'log', lines.append):
|
||||
path = os.path.join(d, 'x.restore.json')
|
||||
originals = aalc_task.apply_overrides(cfg, 'mirror', {'count': 5}, path)
|
||||
self.assertEqual(cfg.values['set_mirror_count'], 5)
|
||||
# 指定次数时无限刷牢必须关掉, 否则 AALC 把次数改成 9999
|
||||
self.assertEqual(cfg.values, {'set_mirror_count': 5, 'infinite_dungeons': False})
|
||||
self.assertIn('无限刷牢', '\n'.join(lines))
|
||||
with open(path, encoding='utf-8') as f:
|
||||
self.assertEqual(json.load(f), {'set_mirror_count': 1})
|
||||
self.assertEqual(originals, {'set_mirror_count': 1})
|
||||
self.assertEqual(json.load(f), before)
|
||||
self.assertEqual(originals, before)
|
||||
# 任务进程被强杀后, TaskRunner 用 --restore 读文件写回
|
||||
aalc_task.restore_file(path, cfg)
|
||||
self.assertEqual((cfg.saved, cfg.flushes), ({'set_mirror_count': 1}, 1))
|
||||
self.assertEqual((cfg.saved, cfg.flushes), (before, 1))
|
||||
self.assertFalse(os.path.exists(path))
|
||||
self.assertEqual(aalc_task.apply_overrides(cfg, 'reward', {}, path), {})
|
||||
self.assertFalse(os.path.exists(path)) # 没有覆盖就不留恢复文件
|
||||
|
||||
def test_mirror_without_count_keeps_configured_infinite_mode(self):
|
||||
from lc_mcp import aalc_task
|
||||
cfg = mock.Mock()
|
||||
cfg.get_value.side_effect = {'set_EXP_count': 3}.get
|
||||
self.assertEqual(aalc_task.apply_overrides(cfg, 'mirror', {}), {})
|
||||
cfg.unsaved_set_value.assert_not_called()
|
||||
self.assertEqual(aalc_task.apply_overrides(cfg, 'daily', {'exp': 1}), {'set_EXP_count': 3})
|
||||
cfg.unsaved_set_value.assert_called_once_with('set_EXP_count', 1)
|
||||
|
||||
|
||||
class TaskRestoreTest(unittest.TestCase):
|
||||
"""run_task 的临时次数会随 AALC 中途存盘写进 config.yaml; 强杀后必须写回原值。"""
|
||||
|
||||
@@ -80,6 +80,37 @@ class ProgressResultTest(unittest.TestCase):
|
||||
self.assertEqual(self.run_progress(level=30), (0, 1))
|
||||
|
||||
|
||||
class CardResultTest(unittest.TestCase):
|
||||
def run_command(self, command, upgrade=True, sync=True, uptie=True):
|
||||
argv = ['levelup.py'] + command + (['--uptie'] if uptie else [])
|
||||
with mock.patch.object(sys, 'argv', argv), \
|
||||
mock.patch.object(levelup, 'state', return_value={
|
||||
'items': [{'text': 'Level Up IDENTITIES Facades'}]}), \
|
||||
mock.patch.object(levelup, 'scan_grid', return_value=[
|
||||
(0, 0, 335, 260, 20, True, 'identity')]), \
|
||||
mock.patch.object(levelup, 'dismiss_modal'), \
|
||||
mock.patch.object(levelup, 'long_press'), \
|
||||
mock.patch.object(levelup, 'click'), \
|
||||
mock.patch.object(levelup, 'do_level_up', return_value=(upgrade, '升级结果')), \
|
||||
mock.patch.object(levelup, 'do_uptie', return_value=(sync, '同步结果')) as synchronize, \
|
||||
mock.patch.object(levelup.time, 'sleep'), \
|
||||
mock.patch('builtins.print'):
|
||||
code = levelup.main()
|
||||
return code, synchronize.call_count
|
||||
|
||||
def test_failed_uptie_fails_both_cli_commands(self):
|
||||
for command in (['card', '0', '0'], ['weakest']):
|
||||
with self.subTest(command=command):
|
||||
self.assertEqual(self.run_command(command, sync=False), (1, 1))
|
||||
|
||||
def test_both_operations_must_succeed(self):
|
||||
self.assertEqual(self.run_command(['card', '0', '0']), (0, 1))
|
||||
self.assertEqual(self.run_command(['card', '0', '0'], upgrade=False), (1, 1))
|
||||
|
||||
def test_upgrade_without_uptie_keeps_its_result(self):
|
||||
self.assertEqual(self.run_command(['card', '0', '0'], uptie=False), (0, 0))
|
||||
|
||||
|
||||
class Screens:
|
||||
"""按顺序返回预设画面的假 state(), 记录点击。"""
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import ast
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
@@ -34,6 +38,28 @@ class PreflightTest(unittest.TestCase):
|
||||
def test_missing_team_in_queue(self):
|
||||
problems = preflight.check(values(teams_active_queue=[2]), 'mirror', env={})
|
||||
self.assertIn('队伍 2', problems[0])
|
||||
self.assertIn('没有可用队伍', problems[-1])
|
||||
|
||||
def test_empty_queue_is_rejected_because_aalc_would_exit_zero(self):
|
||||
problems = preflight.check(values(teams_active_queue=[]), 'mirror', env={})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn('没有可用队伍', problems[0])
|
||||
self.assertEqual(preflight.check(values(teams_active_queue=[]), 'daily', env={}), [])
|
||||
self.assertEqual(preflight.check(values(teams_active_queue=[], mirror=False), 'all', env={}), [])
|
||||
|
||||
def test_fixed_team_use_must_match_current_difficulty(self):
|
||||
order = [1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0]
|
||||
hard_only = {'sinner_order': order, 'fixed_team_use': True, 'fixed_team_use_select': 0}
|
||||
normal_only = dict(hard_only, fixed_team_use_select=1)
|
||||
for team, hard, ok in [(hard_only, False, False), (hard_only, True, True),
|
||||
(normal_only, False, True), (normal_only, True, False),
|
||||
(dict(hard_only, fixed_team_use=False), False, True)]:
|
||||
with self.subTest(team=team, hard=hard):
|
||||
problems = preflight.check(values(teams={'1': team}, hard_mirror=hard), 'mirror', env={})
|
||||
self.assertEqual(problems == [], ok, problems)
|
||||
# 只要队列里有一支适用当前难度, AALC 就会轮转到它
|
||||
v = values(teams_active_queue=[1, 2], teams={'1': hard_only, '2': normal_only})
|
||||
self.assertEqual(preflight.check(v, 'mirror', env={}), [])
|
||||
|
||||
def test_lunacy_spending_is_rejected_unless_explicit(self):
|
||||
v = values(set_lunacy_to_enkephalin=2)
|
||||
@@ -56,15 +82,175 @@ class PreflightTest(unittest.TestCase):
|
||||
|
||||
class Cfg:
|
||||
data = {'simulator': False, 'mirror': True, 'set_win_size': 720,
|
||||
'set_lunacy_to_enkephalin': None, 'teams_active_queue': [1], 'teams': {1: Team()}}
|
||||
'set_windows': False, 'set_win_position': 'center',
|
||||
'set_lunacy_to_enkephalin': None, 'hard_mirror': 1,
|
||||
'teams_active_queue': [1], 'teams': {1: Team()}}
|
||||
|
||||
def get_value(self, key):
|
||||
return self.data[key]
|
||||
|
||||
v = preflight.collect(Cfg())
|
||||
self.assertEqual(v['teams'], {'1': {'sinner_order': [1]}})
|
||||
self.assertIs(v['hard_mirror'], True)
|
||||
self.assertEqual(v['set_lunacy_to_enkephalin'], 0)
|
||||
self.assertFalse(v['set_windows'])
|
||||
self.assertEqual(v['set_win_position'], 'center')
|
||||
|
||||
def test_user_managed_window_skips_configured_size_check(self):
|
||||
self.assertEqual(preflight.check(values(set_windows=False, set_win_size=2160),
|
||||
'daily', desktop=(1920, 1080), env={}), [])
|
||||
|
||||
def test_borderless_window_can_fill_the_desktop(self):
|
||||
for position in ('center', 'left_top', 'right_top', 'left_bottom', 'right_bottom'):
|
||||
with self.subTest(position=position):
|
||||
v = values(set_windows=True, set_win_size=1080, set_win_position=position)
|
||||
self.assertEqual(preflight.check(v, 'daily', desktop=(1920, 1080), env={}), [])
|
||||
self.assertTrue(preflight.check(v, 'daily', desktop=(1600, 900), env={}))
|
||||
|
||||
|
||||
class HeadlessHdrTest(unittest.TestCase):
|
||||
def test_upstream_prompt_is_acknowledged_without_an_event_loop(self):
|
||||
# Run the pinned upstream detector; Event.wait would block without a receiver.
|
||||
path = Path(__file__).resolve().parents[1] / 'vendor/aalc/tasks/base/script_task_scheme.py'
|
||||
tree = ast.parse(path.read_text(encoding='utf-8'))
|
||||
node = next(n for n in tree.body if isinstance(n, ast.FunctionDef)
|
||||
and n.name == '_warn_if_game_monitor_hdr_enabled')
|
||||
direct = object()
|
||||
|
||||
class Signal:
|
||||
callback = None
|
||||
|
||||
def connect(self, callback, mode):
|
||||
self.callback = callback if mode is direct else None
|
||||
|
||||
def disconnect(self, callback):
|
||||
self.callback = None
|
||||
|
||||
def emit(self, event):
|
||||
if self.callback:
|
||||
self.callback(event)
|
||||
|
||||
signal = Signal()
|
||||
events = []
|
||||
|
||||
def event_factory():
|
||||
event = threading.Event()
|
||||
events.append(event)
|
||||
return event
|
||||
|
||||
ns = dict(cfg=SimpleNamespace(simulator=False, get_value=lambda *a: True),
|
||||
screen=SimpleNamespace(handle=SimpleNamespace(hwnd=1)),
|
||||
win32api=SimpleNamespace(MonitorFromWindow=lambda *a: 1),
|
||||
win32con=SimpleNamespace(MONITOR_DEFAULTTONEAREST=2),
|
||||
get_monitor_hdr_info=lambda *a: SimpleNamespace(hdr_enabled=True),
|
||||
Event=event_factory, mediator=SimpleNamespace(hdr_warning=signal), log=mock.Mock())
|
||||
exec(compile(ast.Module(body=[node], type_ignores=[]), str(path), 'exec'), ns)
|
||||
qt = SimpleNamespace(Qt=SimpleNamespace(ConnectionType=SimpleNamespace(DirectConnection=direct)))
|
||||
messages = []
|
||||
with mock.patch.dict(sys.modules, {'PySide6.QtCore': qt}):
|
||||
with aalc_patches.headless_hdr_warning(SimpleNamespace(**ns), log=messages.append):
|
||||
worker = threading.Thread(target=ns[node.name], daemon=True)
|
||||
worker.start()
|
||||
worker.join(1)
|
||||
try:
|
||||
self.assertFalse(worker.is_alive(), 'HDR prompt blocked the task')
|
||||
self.assertTrue(events[0].is_set())
|
||||
self.assertIn('HDR', messages[0])
|
||||
finally:
|
||||
for event in events:
|
||||
event.set()
|
||||
worker.join(1)
|
||||
self.assertIsNone(signal.callback)
|
||||
|
||||
def test_exception_disconnects_the_receiver(self):
|
||||
signal = mock.Mock()
|
||||
scheme = SimpleNamespace(mediator=SimpleNamespace(hdr_warning=signal))
|
||||
qt = SimpleNamespace(Qt=SimpleNamespace(ConnectionType=SimpleNamespace(DirectConnection=1)))
|
||||
with mock.patch.dict(sys.modules, {'PySide6.QtCore': qt}):
|
||||
with self.assertRaisesRegex(RuntimeError, 'task failed'):
|
||||
with aalc_patches.headless_hdr_warning(scheme):
|
||||
raise RuntimeError('task failed')
|
||||
signal.disconnect.assert_called_once_with(signal.connect.call_args.args[0])
|
||||
|
||||
|
||||
|
||||
class MirrorCompletionTest(unittest.TestCase):
|
||||
"""AALC 退出码 0 不代表打完镜牢; 用上游真实 Mirror_task 核对完成局数。"""
|
||||
|
||||
class Signal:
|
||||
def __init__(self):
|
||||
self.callbacks = []
|
||||
|
||||
def connect(self, callback, mode):
|
||||
self.callbacks.append(callback)
|
||||
|
||||
def disconnect(self, callback):
|
||||
self.callbacks.remove(callback)
|
||||
|
||||
def emit(self, *args):
|
||||
for callback in list(self.callbacks):
|
||||
callback(*args)
|
||||
|
||||
def run_upstream_mirror(self, queue, team, count=1):
|
||||
path = Path(__file__).resolve().parents[1] / 'vendor/aalc/tasks/base/script_task_scheme.py'
|
||||
tree = ast.parse(path.read_text(encoding='utf-8'))
|
||||
node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'Mirror_task')
|
||||
signal = self.Signal()
|
||||
mediator = SimpleNamespace(mirror_signal=signal, mirror_bar_kill_signal=mock.Mock())
|
||||
state = {'teams_active_queue': list(queue),
|
||||
'teams_be_select': [num in queue for num in (1,)]}
|
||||
cfg = SimpleNamespace(
|
||||
set_mirror_count=count, infinite_dungeons=False, save_rewards=False, hard_mirror=False,
|
||||
auto_hard_mirror=False, re_claim_rewards=False, teams_active_queue=state['teams_active_queue'],
|
||||
config=SimpleNamespace(teams={'1': team}), get_value=state.get,
|
||||
normalize_and_sync_team_state=lambda persist=True: None, rotate_team_queue=mock.Mock())
|
||||
ns = dict(cfg=cfg, mediator=mediator, log=mock.Mock(), to_get_reward=mock.Mock(),
|
||||
onetime_mir_process=mock.Mock(return_value=True))
|
||||
exec(compile(ast.Module(body=[node], type_ignores=[]), str(path), 'exec'), ns)
|
||||
scheme = SimpleNamespace(mediator=mediator, Mirror_task=ns['Mirror_task'])
|
||||
qt = SimpleNamespace(Qt=SimpleNamespace(ConnectionType=SimpleNamespace(DirectConnection=1)))
|
||||
with mock.patch.dict(sys.modules, {'PySide6.QtCore': qt}), \
|
||||
aalc_patches.mirror_progress(scheme) as progress:
|
||||
scheme.Mirror_task()
|
||||
self.assertEqual(signal.callbacks, [], 'receiver must be disconnected')
|
||||
return progress, ns['onetime_mir_process']
|
||||
|
||||
def test_unusable_team_returns_normally_but_is_reported_incomplete(self):
|
||||
from lc_mcp import aalc_task
|
||||
hard_only = SimpleNamespace(fixed_team_use=True, fixed_team_use_select=0)
|
||||
progress, play = self.run_upstream_mirror([1], hard_only)
|
||||
play.assert_not_called()
|
||||
self.assertEqual((progress.finished, progress.total), (0, 1))
|
||||
lines = []
|
||||
with mock.patch.object(aalc_task, 'log', lines.append):
|
||||
self.assertEqual(aalc_task.mirror_result('mirror', progress), aalc_task.INCOMPLETE_EXIT)
|
||||
self.assertTrue(any(line.startswith('[ERROR]') and '0/1' in line for line in lines))
|
||||
|
||||
def test_completed_run_is_success(self):
|
||||
from lc_mcp import aalc_task
|
||||
progress, play = self.run_upstream_mirror([1], SimpleNamespace(fixed_team_use=False))
|
||||
play.assert_called_once()
|
||||
self.assertEqual((progress.finished, progress.total), (1, 1))
|
||||
with mock.patch.object(aalc_task, 'log'):
|
||||
self.assertEqual(aalc_task.mirror_result('mirror', progress), 0)
|
||||
|
||||
def test_missing_progress_only_fails_explicit_mirror_task(self):
|
||||
from lc_mcp import aalc_task
|
||||
with mock.patch.object(aalc_task, 'log'):
|
||||
self.assertEqual(aalc_task.mirror_result('all', aalc_patches.MirrorProgress()), 0)
|
||||
self.assertEqual(aalc_task.mirror_result('daily', aalc_patches.MirrorProgress()), 0)
|
||||
self.assertEqual(aalc_task.mirror_result('mirror', aalc_patches.MirrorProgress()),
|
||||
aalc_task.INCOMPLETE_EXIT)
|
||||
|
||||
def test_receiver_is_disconnected_on_exception(self):
|
||||
signal = mock.Mock()
|
||||
scheme = SimpleNamespace(mediator=SimpleNamespace(mirror_signal=signal))
|
||||
qt = SimpleNamespace(Qt=SimpleNamespace(ConnectionType=SimpleNamespace(DirectConnection=1)))
|
||||
with mock.patch.dict(sys.modules, {'PySide6.QtCore': qt}):
|
||||
with self.assertRaisesRegex(RuntimeError, 'task failed'):
|
||||
with aalc_patches.mirror_progress(scheme):
|
||||
raise RuntimeError('task failed')
|
||||
signal.disconnect.assert_called_once_with(signal.connect.call_args.args[0])
|
||||
|
||||
class ExactTeamMatchTest(unittest.TestCase):
|
||||
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from lc_mcp import aalc_patches # noqa: E402
|
||||
|
||||
|
||||
class SystemTeamNamesTest(unittest.TestCase):
|
||||
|
||||
def test_all_ten_systems_are_mapped(self):
|
||||
expected = {'burn', 'bleed', 'tremor', 'rupture', 'poise',
|
||||
'sinking', 'charge', 'slash', 'pierce', 'blunt'}
|
||||
self.assertEqual(set(aalc_patches.SYSTEM_TEAM_NAMES), expected)
|
||||
|
||||
def test_names_are_non_empty_strings(self):
|
||||
for system, names in aalc_patches.SYSTEM_TEAM_NAMES.items():
|
||||
self.assertIsInstance(names, tuple, system)
|
||||
self.assertTrue(names, system)
|
||||
for name in names:
|
||||
self.assertIsInstance(name, str)
|
||||
self.assertTrue(name.strip(), system)
|
||||
|
||||
def test_poise_accepts_both_spellings(self):
|
||||
# 游戏里叫「呼吸法」, system_cn_zh 里叫「呼吸」, 两个都要能命中
|
||||
self.assertIn('呼吸法', aalc_patches.SYSTEM_TEAM_NAMES['poise'])
|
||||
self.assertIn('呼吸', aalc_patches.SYSTEM_TEAM_NAMES['poise'])
|
||||
|
||||
|
||||
class RegionTest(unittest.TestCase):
|
||||
|
||||
def test_team_list_region(self):
|
||||
self.assertTrue(aalc_patches._in_list(130, 493)) # 实测「流血」的位置
|
||||
self.assertTrue(aalc_patches._in_list(255, 305))
|
||||
self.assertFalse(aalc_patches._in_list(130, 120)) # 顶栏不算列表
|
||||
self.assertFalse(aalc_patches._in_list(600, 493)) # 右侧面板
|
||||
self.assertFalse(aalc_patches._in_list(130, 700))
|
||||
|
||||
def test_header_region(self):
|
||||
self.assertTrue(aalc_patches._in_header(242, 125)) # 实测顶栏「流血」
|
||||
self.assertFalse(aalc_patches._in_header(130, 493))
|
||||
self.assertFalse(aalc_patches._in_header(900, 125))
|
||||
|
||||
def test_regions_do_not_overlap(self):
|
||||
for x, y in [(130, 493), (242, 125), (600, 300), (1200, 600)]:
|
||||
self.assertFalse(
|
||||
aalc_patches._in_list(x, y) and aalc_patches._in_header(x, y),
|
||||
(x, y),
|
||||
)
|
||||
|
||||
|
||||
class TeamOcrTest(unittest.TestCase):
|
||||
|
||||
def test_returns_list_and_strips_spaces(self):
|
||||
auto = mock.Mock()
|
||||
auto._run_ocr_for_text.return_value = {
|
||||
'编队#20': [132.0, 340.5],
|
||||
' 流血 ': [130.5, 493.0],
|
||||
'': [0, 0],
|
||||
}
|
||||
items = aalc_patches._team_ocr(auto)
|
||||
self.assertIn(('编队#20', 132.0, 340.5), items)
|
||||
self.assertIn(('流血', 130.5, 493.0), items)
|
||||
self.assertEqual(len(items), 2) # 空串被丢掉
|
||||
|
||||
def test_empty_ocr_gives_empty_list(self):
|
||||
auto = mock.Mock()
|
||||
auto._run_ocr_for_text.return_value = {}
|
||||
self.assertEqual(aalc_patches._team_ocr(auto), [])
|
||||
|
||||
def test_bad_position_is_skipped_not_fatal(self):
|
||||
auto = mock.Mock()
|
||||
auto._run_ocr_for_text.return_value = {'流血': [], '斩击': [1.0, 2.0]}
|
||||
self.assertEqual(aalc_patches._team_ocr(auto), [('斩击', 1.0, 2.0)])
|
||||
|
||||
|
||||
class _FakeMirror:
|
||||
def __init__(self, team_setting, team_num):
|
||||
self.system = team_setting['system']
|
||||
self.team_number = team_num
|
||||
|
||||
|
||||
class InstallSystemTeamSelectionTest(unittest.TestCase):
|
||||
"""用假模块验证挂载点与回退行为, 不依赖 AALC / Windows。"""
|
||||
|
||||
def setUp(self):
|
||||
self.calls = []
|
||||
|
||||
def original(num):
|
||||
self.calls.append(num)
|
||||
return 'fallback'
|
||||
|
||||
self.original = original
|
||||
self.mirror_mod = types.ModuleType('tasks.mirror.mirror')
|
||||
self.mirror_mod.Mirror = _FakeMirror
|
||||
self.mirror_mod.select_battle_team = original
|
||||
|
||||
self.auto = mock.Mock()
|
||||
auto_mod = types.ModuleType('module.automation')
|
||||
auto_mod.auto = self.auto
|
||||
|
||||
tasks_pkg = types.ModuleType('tasks')
|
||||
tasks_pkg.__path__ = []
|
||||
mirror_pkg = types.ModuleType('tasks.mirror')
|
||||
mirror_pkg.__path__ = []
|
||||
mirror_pkg.mirror = self.mirror_mod
|
||||
module_pkg = types.ModuleType('module')
|
||||
module_pkg.__path__ = []
|
||||
|
||||
self._patcher = mock.patch.dict(sys.modules, {
|
||||
'tasks': tasks_pkg,
|
||||
'tasks.mirror': mirror_pkg,
|
||||
'tasks.mirror.mirror': self.mirror_mod,
|
||||
'module': module_pkg,
|
||||
'module.automation': auto_mod,
|
||||
})
|
||||
self._patcher.start()
|
||||
self.addCleanup(self._patcher.stop)
|
||||
|
||||
def install(self):
|
||||
return aalc_patches.install_system_team_selection(log=lambda *_: None)
|
||||
|
||||
def test_returns_original_and_replaces_module_global(self):
|
||||
original = self.install()
|
||||
self.assertIs(original, self.original)
|
||||
self.assertIsNot(self.mirror_mod.select_battle_team, self.original)
|
||||
# __init__ 也被包装, 但仍然正常构造
|
||||
mirror = self.mirror_mod.Mirror({'system': 'bleed'}, 1)
|
||||
self.assertEqual(mirror.system, 'bleed')
|
||||
|
||||
def test_known_system_uses_name_search(self):
|
||||
self.install()
|
||||
self.mirror_mod.Mirror({'system': 'bleed'}, 1)
|
||||
with mock.patch.object(aalc_patches, '_select_team_by_name', return_value=True) as sel:
|
||||
self.assertIs(self.mirror_mod.select_battle_team(1), True)
|
||||
self.assertEqual(sel.call_args[0][1], ('流血',))
|
||||
self.assertEqual(self.calls, []) # 成功后不再走编号回退
|
||||
|
||||
def test_name_search_failure_does_not_fall_back_to_number(self):
|
||||
# 这号没有 编队#1, 静默回退到编号会选中错的队, 必须显式失败
|
||||
self.install()
|
||||
self.mirror_mod.Mirror({'system': 'bleed'}, 1)
|
||||
with mock.patch.object(aalc_patches, '_select_team_by_name', return_value=False):
|
||||
self.assertIs(self.mirror_mod.select_battle_team(1), False)
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_exception_in_name_search_is_contained(self):
|
||||
self.install()
|
||||
self.mirror_mod.Mirror({'system': 'bleed'}, 1)
|
||||
boom = mock.Mock(side_effect=RuntimeError('ocr down'))
|
||||
with mock.patch.object(aalc_patches, '_select_team_by_name', boom):
|
||||
self.assertIs(self.mirror_mod.select_battle_team(1), False)
|
||||
|
||||
def test_unknown_system_falls_back_to_original(self):
|
||||
self.install()
|
||||
self.mirror_mod.Mirror({'system': 'unknown_system'}, 3)
|
||||
self.assertEqual(self.mirror_mod.select_battle_team(3), 'fallback')
|
||||
self.assertEqual(self.calls, [3])
|
||||
|
||||
def test_missing_mirror_module_is_not_fatal(self):
|
||||
with mock.patch.dict(sys.modules, {'tasks.mirror': None, 'tasks.mirror.mirror': None}):
|
||||
self.assertIsNone(self.install())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user