From a04b443b6acb988dd7c85ec6175e3086746db1b8 Mon Sep 17 00:00:00 2001 From: ywsabc2 Date: Sun, 15 Nov 2026 05:12:23 +0000 Subject: [PATCH] =?UTF-8?q?=E9=95=9C=E7=89=A2=E5=85=94=E5=AD=90=E6=B4=9E?= =?UTF-8?q?=E9=80=9F=E5=88=B7:=20=E6=AF=8F=E5=9C=BA=E7=AC=AC=E4=B8=80?= =?UTF-8?q?=E5=9B=9E=E5=90=88=E8=B6=85=E9=A2=91=E3=80=8C=E7=A9=BA=E6=B4=9E?= =?UTF-8?q?=E3=80=8D=E3=80=81=E6=94=BB=E7=95=A5=E8=B7=AF=E7=BA=BF=E5=8D=A1?= =?UTF-8?q?=E5=8C=85=E5=8A=A0=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit run_task(task="mirror", strategy="rabbit_hole") 时生效, 不带 strategy 时不装: - 选队按 rabbit_hole.json 的编队名(默认「兔子洞」); - 每回合 P → 长按浮士德打开 E.G.O 列表 → OCR 找「空洞」, 第一回合长按卡片超频 (侵蚀「空洞」直接打人; 普通「空洞」只叠弹孔), 其余回合单击 → Enter; 审计 battle/hollow 记 overclock/ego/ego_unavailable/no_option; - 路线卡包加分: 赌徒 → 地狱鸡 → 去·海·边 → 憎恶与绝望 → 2号线(OurPlay 全程困难路线), 按 AALC 默认权重模拟每层都选到路线卡包。 长按点 press_at 出厂未校准: 只记 [ERROR], 照常 P+Enter。 机制和超频操作按零协游戏文本/教程核实; 编队、路线按 codex 检索的 OurPlay/Reddit 攻略。 实机校准步骤见 docs/feedback/2026-11-15/RABBIT-HOLE.md, 台账 R-08。 Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- docs/ISSUES.md | 13 + docs/feedback/2026-11-15/RABBIT-HOLE.md | 93 +++++++ lc_mcp/aalc_patches.py | 201 +++++++++++++- lc_mcp/aalc_task.py | 40 ++- lc_mcp/data/rabbit_hole.json | 21 ++ lc_mcp/protocol.py | 18 +- tests/test_lc_mcp.py | 11 + tests/test_rabbit_hole.py | 342 ++++++++++++++++++++++++ tests/test_theme_pack_systems.py | 28 +- 10 files changed, 755 insertions(+), 19 deletions(-) create mode 100644 docs/feedback/2026-11-15/RABBIT-HOLE.md create mode 100644 lc_mcp/data/rabbit_hole.json create mode 100644 tests/test_rabbit_hole.py diff --git a/README.md b/README.md index 238dc8c..539c476 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,7 @@ MCP 初始化说明与工具描述均指导 AI 优先使用 AALC:常规日常 | `theme_pack` | `preferred` 达到优选阈值 / `highest_weight` 刷新后取最高权重 / `event_pack` 最左活动卡包;选中的卡包按体系加过分时带 `system_bonus`(`packs`/`system`/`from`/`to`) | | `gift` | `keyword` 命中体系关键词 / `no_keyword`(记的是交给 AALC 的第一顺位,白棉花、已持有仍由 AALC 处理) | | `event` | `text` 按表选 / `deferred` 认出了表里的事件但交给 AALC / `not_in_table`(带 `options`,可直接拿来补表) | +| `battle` | `hollow`:兔子洞模式每回合的结果,`overclock` 超频放上了「空洞」/ `ego` 单击放上了 / `ego_unavailable` 列表还开着(多半资源不够)/ `no_option` 没弹出列表或没认出 | | `gift_confirm` | `repeated` 「获得E.G.O饰品」确认连点不关,改点按钮中心 / `stuck` 还是不关,结束任务 | | `shop` | `name_match` 按中文名找到必买饰品(`choice` 是名字)/ `purchase_clicked` 点到了购买按钮(`choice` 是之前点的商品:`shop_by_name` 按名字、必买模板名、`level_IV_to_buy`、`by_position` 本体系饰品) | @@ -203,7 +204,11 @@ MCP 初始化说明与工具描述均指导 AI 优先使用 AALC:常规日常 当碎之物)所有体系 -3。AALC 原来的 -5 也能被压过,比如充能队会选 WARP快车谋杀案;嫌激进就调小表里的 `bonus`。 卡包数据来自 wiki.gg(`scripts/build_theme_pack_systems.py` 生成,换赛季重跑),社区推荐见 `docs/feedback/2026-11-15/theme-pack-research.md`。`LCP_THEME_PACK_SYSTEMS=0` 关闭。 -- **挂不上就报错**:事件表、饰品排序、商店按名字、前台按键、卡包加分这几个补丁靠拦截 AALC 的某个调用挂进去,安装时先查上游源码; +- **兔子洞速刷**(`run_task` 加 `strategy="rabbit_hole"`):按 `lc_mcp/data/rabbit_hole.json` 的编队名选队; + 每回合按 P → 长按浮士德打开 E.G.O 列表 → OCR 找「空洞」,每场第一回合长按卡片超频、其余回合单击 → Enter; + 攻略路线上的卡包(赌徒 → 地狱鸡 → 去·海·边 → 憎恶与绝望 → 2号线)加分。长按点 `press_at` 要在实机上量,没量时不点任何东西、 + 记 `[ERROR]`、照常 P+Enter。说明与校准步骤见 `docs/feedback/2026-11-15/RABBIT-HOLE.md`。 +- **挂不上就报错**:事件表、饰品排序、商店按名字、前台按键、卡包加分、兔子洞这几个补丁靠拦截 AALC 的某个调用挂进去,安装时先查上游源码; 上游改了写法时记 `[ERROR]` 并跳过该补丁,不会悄悄失效。 ## 无人值守 diff --git a/docs/ISSUES.md b/docs/ISSUES.md index 0edb6a0..ef409d6 100644 --- a/docs/ISSUES.md +++ b/docs/ISSUES.md @@ -210,6 +210,19 @@ `REGRESSION.md`(云端给的清单)、`REGRESSION-RESULTS.md`(本文件同目录,回归结果)、 `docs/BACKLOG.md`(排期)、本台账。 +### R-08 镜牢「兔子洞」速刷 【开发中,待实机校准】 + +- **来源**:用户 2026-11-15「开发一个兔子洞速刷的,你联合codex去搞」。 +- **是什么**:黑兽 - 卯 魁首 浮士德 + 浮士德的 E.G.O「空洞」(英文社区 Mao Hollow Faust)。普通「空洞」第一回合只叠弹孔不打人, + 每场第一回合**超频**(在 E.G.O 列表里长按卡片)用侵蚀「空洞」直接清场,之后放「填补空洞」。 + 机制和超频操作按零协游戏文本 / 教程核实;编队、路线、星光、商店按 codex 检索到的 OurPlay / Reddit 攻略(见 RABBIT-HOLE.md 1.2)。 +- **实现**:`run_task(task="mirror", strategy="rabbit_hole")`;配置在 `lc_mcp/data/rabbit_hole.json`(编队名、E.G.O 名、长按点、 + 第一回合超频、路线卡包加分)。长按点出厂未校准,未校准时只记 `[ERROR]`、照常 P+Enter;路线卡包加分照常生效。 + 后期 Boss 换打法、按战斗换人做不到(AALC 没有这一步)。 +- **下一步**:Windows 端按 [`feedback/2026-11-15/RABBIT-HOLE.md`](feedback/2026-11-15/RABBIT-HOLE.md) 建编队、调 AALC 设置、量长按点、 + 确认 5 件事、跑一局。 +- **验收**:一局里 `decisions.battle` 的 `overclock` + `ego` 占多数;每层选到路线卡包;单局用时接近攻略自报的 10~15 分钟。 + ### R-07 饰品三选一按体系关键词 【已实现,攒样本】 - 来源:BACKLOG P1-3,云端已实现并实机跑通 4 次(2 次命中)。 diff --git a/docs/feedback/2026-11-15/RABBIT-HOLE.md b/docs/feedback/2026-11-15/RABBIT-HOLE.md new file mode 100644 index 0000000..db179da --- /dev/null +++ b/docs/feedback/2026-11-15/RABBIT-HOLE.md @@ -0,0 +1,93 @@ +# 镜牢「兔子洞」速刷:开发与实机校准(2026-11-15) + +用户需求:「开发一个兔子洞速刷的」。台账 [`docs/ISSUES.md`](../../ISSUES.md) R-08。 + +## 1. 「兔子洞」是什么 + +### 1.1 机制(零协游戏文本,release 2026111301,已核实) + +| 项 | 内容 | 依据 | +|---|---|---| +| 叫法 | 中文社区「兔子洞」= 兔浮 + 空洞;英文社区「Mao Hollow Faust」 | codex 联网检索;YouTube 葡语视频标题「O novo método MAIS BARATO E MAIS RÁPIDO de farm Mirror Dungeon (Mao Hollow Faust)」 | +| 人格 | id 10212「黑兽 - 卯 魁首 浮士德」 | `Personalities.json` | +| E.G.O | id 20211「空洞」(浮士德专属;默尔索另有一个同名的 20510,攻略里也用) | `Egos.json` | +| 普通「空洞」 | **不打敌人**(不会命中敌方单位),给自己叠 5 发弹孔、呼吸、充能;本场首次使用打折。自身弹孔不低于 1 发时改用「填补空洞」:每发弹孔拼点威力 +2,硬币最多重复 4 次,只打一个目标时伤害 +100% | `Skills_Ego_Personality-02.json` 2021111 / 2021112 | +| 侵蚀「空洞」 | **随机指定目标直接打**;弹孔满 5 发时耗光弹孔,下回合全队加攻击 | 同上 2021121 | +| E.G.O 被动「排离空洞」 | 弹孔 5 发时「空洞」(觉醒、侵蚀)不耗 E.G.O 资源;回合开始 +1 发弹孔;友方击杀回 5 理智 | `Passive_Ego.json` 2021111 | +| 怎么放 E.G.O | 游戏教程「按住罪人的头像以打开其 E.G.O 列表」(wiki.gg 写的是按住技能格);资源不够的是灰的;再选一次是取消 | `TutorialRenewalDesc.json` tuto_01_09_01_02;[wiki.gg E.G.O/Gameplay](https://limbuscompany.wiki.gg/wiki/E.G.O/Gameplay) | +| 超频 | 「在战斗中选择 E.G.O 技能时,可以**长按 E.G.O** 来使用 E.G.O 超频」:强制用侵蚀技能,1.5 倍 E.G.O 资源和理智。资源够 1.5 倍是**稳定超频**(只打敌人),不够是**不稳定超频**(不分敌我,缺的资源扣成负数);普通状态的资源都不够时不能超频 | `TutorialMainUIText.json` tutorial_mainui_04_egoinfo_page_05_desc_01~03;`TutorialDesc0-4.json` tutorial_ego_overclock_1~6 | + +所以「第一回合超频」是关键:普通「空洞」第一回合只叠弹孔不打人,超频的侵蚀「空洞」第一回合就能清场。 + +### 1.2 攻略(codex 检索,玩家攻略,未实机验证) + +两份文字攻略,做法不完全一样: + +| 项 | OurPlay [777774](https://www.ourplay.net/planet/thread/777774)(中文,针对「新牢更新」) | Reddit [1x8zr65](https://www.reddit.com/r/LimbusCompanyHelp/comments/1x8zr65/help_me_with_most_time_efficient_md_run/) | +|---|---|---| +| 编队 | 兔浮 + 四破「空洞」、任意高等级默尔索 + 四破「空洞」、七协会李箱 + 四破「凶弹」,另备 2~3 个弱突刺人格;按战斗换人,不是全程单通 | 兔浮 + 一名高检定角色(作者用小指辛克莱) | +| 每场操作 | 前期每战**第一回合超频(侵蚀)「空洞」**,残血敌人靠弱突刺队友和「鸡线」补刀;后期部分 Boss:第一回合普通「空洞」,默尔索用「空洞」拦截打向浮士德的攻击,第二回合浮士德再放;三层起也可换李箱「凶弹」 | 战斗节点直接超频「空洞」 | +| 难度 / 路线 | 全程困难:1 层赌徒 → 2 层鸡包 → 3 层海边 → 4 层绝望 → 5 层二号线(变体:绝望提前;末层三号线 / 二十区奇迹复刻);避开加太多生命、减伤的苦难;鸡包别走经济最多的路线 | 前三层普通、四五层困难;优先事件,避开黄色警戒圈节点 | +| 星光 / 开局 | 尽量 120 星光开局,加护选 1、3,不勾星光换经济;初始饰品烟斗 / 石冢,观测「王座、鸡线」 | 加护 1、3 不升级;初始 Torn Bandolier,找 Grand Welcome、Sharp Needle & Thread | +| 商店 | 买呼吸或三级饰品,优先合呼吸石,再考虑沉沦石、水瓶、止水;后期给浮士德、默尔索回理智 | 买三级饰品、升满 Bandolier,给检定角色补满理智 | +| 单局用时 | 约 11 分钟(自报) | 混合难度约 10 分钟,全困难约 15 分钟 | + +- 「空洞」三破能起步,但 4 层起会变慢,推荐四破([Reddit 1x4hhd8](https://www.reddit.com/r/LimbusCompanyHelp/comments/1x4hhd8/who_do_i_shardshould_i_threadspin_hollow_faust_ego/))。 +- **未找到**:是否先按 P、资源不够时怎么补救、长按哪个键加速动画;本赛季(S8「西西弗之镜」)是否仍有效、有没有被削弱。 +- 读不到:Reddit 1x74sok、YouTube g9DPhija_LU 的正文。 + +## 2. 实现(默认不启用) + +```text +run_task(task="mirror", count=1, strategy="rabbit_hole") +``` + +配置都在 `lc_mcp/data/rabbit_hole.json`: + +| 字段 | 出厂值 | 作用 | +|---|---|---| +| `team_names` | `["兔子洞"]` | 选队不按体系名,按这个编队名选 | +| `ego_names` | `["空洞"]` | E.G.O 列表里要找的名字(归一后完全相等) | +| `press_at` | `null` | 长按打开 E.G.O 列表的点(客户区宽、高比例),**必须实机量** | +| `hold_seconds` | `1.0` | 长按时长(AALC 松开前还会多按 0.5 秒);长按头像、超频长按卡片都用它 | +| `overclock_first_turn` | `true` | 每场战斗第一回合长按卡片(超频),之后单击 | +| `theme_packs` | 赌徒 / 地狱鸡 / 去·海·边 +10,憎恶与绝望 +12,2号线 +10 | 攻略路线上的卡包加分,加在 AALC 原权重上,没有体系也加 | + +- **每回合**(替换 AALC 的 `Battle._battle_operation`):按 P(胜率)→ 长按 `press_at` → OCR 找列表里的「空洞」→ + 第一回合长按(超频)、其余回合单击 → 按 Enter。日志 `[lc_mcp] 兔子洞: …`,审计 `battle/hollow` 记 + `overclock`(超频放上了)/ `ego`(单击放上了)/ `ego_unavailable`(列表还开着,多半资源不够)/ `no_option`(没弹出列表或没认出「空洞」)。 + 按过 P 就一定按 Enter:交回 AALC 会再按一次 P,而 P 在胜率/伤害之间切换。 + 「第一回合」用 AALC 自己的 `first_turn`(看到战斗播片之前都算第一回合);上游去掉这个参数时记 `[ERROR]`,只放普通「空洞」。 +- **卡包**:路线卡包的加分和「卡包按体系加分」走同一个补丁,日志 `卡包按体系 (无)+兔子洞路线 加分: …`。按 AALC 默认权重 + (困难 + 中文)模拟,每层选到的依次是 赌徒 → 地狱鸡 → 去·海·边 → 憎恶与绝望 → 2号线(AALC 自己给 10 分的隐藏包凤·皇除外)。 + 憎恶与绝望多加 2 分,是因为它和 2号线都能在 4 层出现,AALC 原分都是 -5。`LCP_THEME_PACK_SYSTEMS=0` 时一起关掉。 +- **没校准时**:`press_at` 为 `null`(出厂就是),不点任何东西,记一条 `[ERROR]`,照 AALC 原来的 P+Enter 打;卡包加分照常。 +- **做不到的**(需要识别 Boss、按战斗换人,超出 AALC 现有流程):后期 Boss 第一回合改普通「空洞」、默尔索拦截、换李箱「凶弹」、 + 按战斗换上弱突刺补刀。星光、加护、初始饰品、难度在 AALC 自己的设置里调。 + +## 3. Windows 端要做的(按顺序) + +1. **准备编队和 AALC 设置**: + - 游戏里建一个叫「兔子洞」的编队:「黑兽 - 卯 魁首 浮士德」+「空洞」(最好四破),能上的话加默尔索 +「空洞」、七协会李箱 +「凶弹」。 + 记下账号有没有这些、各自的破数。 + - AALC:镜牢用的队伍指向这个编队;困难模式打开(攻略全程困难);加护 1、3;初始饰品按攻略(烟斗 / 石冢)能选就选。 +2. **量长按点**:开一场镜牢战斗,停在回合界面(不要点开始): + 1. `keypress p`,再 `get_state` 截图; + 2. 先试浮士德的**头像**(游戏教程的说法),不弹列表再试她那一列上面的技能格;记客户区坐标 `(x, y)` 和客户区大小 `(w, h)`; + 3. 用 `drag`(起点 = 终点 = `(x, y)`)长按,确认弹出 E.G.O 列表、里面有「空洞」; + 4. 把 `press_at` 写成 `[x/w, y/h]`(保留 3 位小数),提交推回。 +3. **确认这几件事**(截图 + 一句话结论): + - 先按 P 再选「空洞」,按 Enter 后浮士德确实放了「空洞」(没被 P 覆盖); + - 在列表里**长按**「空洞」卡片是不是超频(卡片或技能变成侵蚀样式),松手后列表是否关掉; + - 技能面板的列顺序每回合是否固定(浮士德是不是一直在同一列;队友阵亡后会不会挪位); + - 资源不够时「空洞」是不是灰的、点了是否没反应;点客户区左上角 `(1,1)` 能不能关掉列表; + - 第二回合起列表里显示的名字是「空洞」还是「填补空洞」(`ego_names` 要不要加「填补空洞」)。 +4. **跑一局**:`run_task(task="mirror", count=1, strategy="rabbit_hole")`。看: + - 日志里的 `兔子洞:` 行;`task_status` 的 `decisions.counts.battle`:`overclock` + `ego` 应占多数; + - `卡包按体系 (无)+兔子洞路线 加分` 行和 `decisions.theme_pack`:每层是否选到路线卡包; + - 单局用时(攻略自报 10~15 分钟)。 + +## 4. 回传 + +写回 `docs/feedback/<日期>/`:回合界面截图、长按后的 E.G.O 列表截图、超频长按后的截图、量出来的 `press_at`、 +第 3 步各项结论、一局的任务日志、`decisions.jsonl` 和单局用时。 diff --git a/lc_mcp/aalc_patches.py b/lc_mcp/aalc_patches.py index 0f7d96a..30056d1 100644 --- a/lc_mcp/aalc_patches.py +++ b/lc_mcp/aalc_patches.py @@ -716,10 +716,11 @@ def _select_team_by_name(auto, names, log=print, rounds=6): return False -def install_system_team_selection(log=print): +def install_system_team_selection(log=print, names=None): """镜牢选队改成"按队伍体系对应的中文名"在列表里点。 AALC 原生只认 编队#N; 本账号的编队是自定义名字(流血/斩击/...), 原生逻辑永远选不上。 + names 给了就不看体系, 直接按这些名字选(兔子洞这类固定编队的打法用)。 """ try: from tasks.mirror import mirror as mirror_mod @@ -737,8 +738,8 @@ def install_system_team_selection(log=print): def __init__(self, team_setting, team_num): original_init(self, team_setting, team_num) system = getattr(self, 'system', '') - wanted['names'] = (SYSTEM_TEAM_NAMES.get(system, ()) - + TEAM_PREFERENCES.get(system, ())) + wanted['names'] = tuple(names) if names else (SYSTEM_TEAM_NAMES.get(system, ()) + + TEAM_PREFERENCES.get(system, ())) wanted['enter_failed'] = False log('[lc_mcp] 镜牢体系 %s -> 目标编队 %s' % (system or '?', '/'.join(wanted['names']) or '(无配置)')) @@ -1642,6 +1643,7 @@ def theme_pack_bonus(pack, system, bonus): 体系包给 featured 档, 有这个体系的专属饰品按件数给 unique 档, 社区推荐给 recommend 档, 取最大; 社区说这个体系走它不划算(avoid 里有这个体系)就不加; 速刷要避开的(avoid 里有 '*')再减 avoid。 + 打法指定的路线卡包(pack['route'] 是它的加分, 如兔子洞)最后算, 至少给这么多, 不受体系和 avoid 影响。 """ score = bonus['featured'] if system in (pack.get('featured') or ()) else 0 count = (pack.get('unique') or {}).get(system, 0) @@ -1654,6 +1656,8 @@ def theme_pack_bonus(pack, system, bonus): score = min(score, 0) if '*' in avoid: score -= bonus.get('avoid', 0) + if pack.get('route'): + score = max(score, pack['route']) return score @@ -1719,8 +1723,12 @@ def boost_theme_pack_weights(weights, packs, system, bonus, language='zh_cn', ha return result, {k: info[k] for k in ordered} -def install_theme_pack_systems(log=print, env=None): - """镜牢选卡包时按当局体系给卡包加分。返回原 select_theme_pack, 未安装返回 None。""" +def install_theme_pack_systems(log=print, env=None, route=None, route_name='路线'): + """镜牢选卡包时按当局体系给卡包加分。返回原 select_theme_pack, 未安装返回 None。 + + route 是打法指定的路线卡包 {中文名: 加分}(如兔子洞的 rabbit_hole.json theme_packs), 每个至少加这么多, + 当局没有体系也照加。 + """ env = os.environ if env is None else env setting = env.get(THEME_PACK_SYSTEMS_ENV, '').strip() if setting == '0': @@ -1732,6 +1740,14 @@ def install_theme_pack_systems(log=print, env=None): except (OSError, ValueError) as e: log('[ERROR] [lc_mcp] 卡包体系表读不了(%s): %s, 卡包按 AALC 原权重选' % (path, e)) return None + route = dict(route or {}) + if route: + known = {pack['zh'] for pack in packs} + missing = [name for name in route if name not in known] + if missing: + log('[ERROR] [lc_mcp] %s卡包不在卡包表里, 不加分: %s' % (route_name, '/'.join(missing))) + route = {name: extra for name, extra in route.items() if name in known} + packs = [dict(pack, route=route[pack['zh']]) if pack['zh'] in route else pack for pack in packs] try: import inspect from tasks.mirror import mirror as mirror_mod @@ -1761,7 +1777,9 @@ def install_theme_pack_systems(log=print, env=None): THEME_PACK_BOOSTED.clear() system = state['system'] if system not in SYSTEM_TEAM_NAMES: - return original(*args, **kwargs) + if not route: + return original(*args, **kwargs) + system = None # 没有体系: 只加路线分(体系包、专属饰品、社区推荐都按 None 算 0) real = theme_list.get_effective_theme_pack_list def get_effective_theme_pack_list(hard_mode, language, *more, **kw): @@ -1773,8 +1791,9 @@ def install_theme_pack_systems(log=print, env=None): log('[lc_mcp] 卡包按体系加分出错(%s: %s), 用 AALC 原权重' % (type(e).__name__, e)) return weights if info: - log('[lc_mcp] 卡包按体系 %s 加分: %s' % (system, ', '.join( - '%s %d→%d' % (key, item['from'], item['to']) for key, item in info.items()))) + log('[lc_mcp] 卡包按体系 %s%s 加分: %s' % ( + system or '(无)', ('+' + route_name) if route else '', ', '.join( + '%s %d→%d' % (key, item['from'], item['to']) for key, item in info.items()))) THEME_PACK_BOOSTED.update(info) return result @@ -1784,7 +1803,9 @@ def install_theme_pack_systems(log=print, env=None): select_theme_pack.__wrapped__ = original mirror_mod.Mirror.__init__ = __init__ mirror_mod.select_theme_pack = select_theme_pack - log('[lc_mcp] patch: 镜牢卡包按体系加分(%s, %d 个卡包)' % (os.path.basename(path), len(packs))) + log('[lc_mcp] patch: 镜牢卡包按体系加分(%s, %d 个卡包%s)' % ( + os.path.basename(path), len(packs), + ', %s %s' % (route_name, ' '.join('%s+%d' % item for item in route.items())) if route else '')) return original @@ -1973,3 +1994,165 @@ def install_key_hold(log=print, env=None, user32=None): log('[lc_mcp] patch: 按键按住 %dms 再松开, 前台改发带扫描码的按键(%s)' % (KEY_HOLD * 1000, '/'.join(sorted(originals)))) return originals + + +# ---------------------------------------------------------------- 镜牢「兔子洞」速刷: 每回合给浮士德放「空洞」 + +# 「兔子洞」(英文社区 Mao Hollow Faust) = 黑兽 - 卯 魁首 浮士德 + 浮士德的 E.G.O「空洞」。游戏数据(零协 2026111301): +# 普通「空洞」不打敌人, 只给自己叠 5 发弹孔; 弹孔不低于 1 发时改用「填补空洞」(大伤害); 侵蚀「空洞」随机打人。 +# E.G.O 被动: 弹孔满 5 发时「空洞」(觉醒、侵蚀)不耗 E.G.O 资源, 每回合开始 +1 发。攻略(OurPlay 777774): 每场第一回合 +# 超频(强制用侵蚀技能)直接清场。AALC 战斗只会 P+Enter, 不会放 E.G.O。游戏教程: 按住罪人的头像打开 E.G.O 列表 +# (wiki.gg 写的是按住技能格), 单击 E.G.O 是普通放, 长按 E.G.O 是超频。完整依据见 docs/feedback/2026-11-15/RABBIT-HOLE.md。 +RABBIT_HOLE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'rabbit_hole.json') +RABBIT_HOLE_POPUP_WAIT = 0.6 # 长按松开后等 E.G.O 列表弹出 +RABBIT_HOLE_SETTLE = 0.4 # 点完 E.G.O 等界面刷新 + + +def load_rabbit_hole(path=RABBIT_HOLE_FILE): + """读兔子洞配置; 格式不对抛 ValueError。""" + with open(path, encoding='utf-8') as fh: + data = json.load(fh) + if not isinstance(data, dict): + raise ValueError('配置必须是 JSON 对象') + + def names(field): + value = data.get(field) + if not isinstance(value, list) or not value or \ + not all(isinstance(v, str) and normalize_team_name(v) for v in value): + raise ValueError('%s 必须是非空字符串列表' % field) + return tuple(normalize_team_name(v) for v in value) + + press_at = data.get('press_at') + if press_at is not None: + if not isinstance(press_at, list) or len(press_at) != 2 or \ + not all(isinstance(v, (int, float)) and 0 < v < 1 for v in press_at): + raise ValueError('press_at 必须是 null 或 [宽比例, 高比例], 都在 0~1 之间') + press_at = (float(press_at[0]), float(press_at[1])) + hold = data.get('hold_seconds', 1.0) + if isinstance(hold, bool) or not isinstance(hold, (int, float)) or not 0.2 <= hold <= 5: + raise ValueError('hold_seconds 必须在 0.2~5 秒之间') + overclock = data.get('overclock_first_turn', False) + if not isinstance(overclock, bool): + raise ValueError('overclock_first_turn 必须是 true/false') + packs = data.get('theme_packs', {}) + if not isinstance(packs, dict) or not all( + isinstance(k, str) and k.strip() and not isinstance(v, bool) and isinstance(v, int) and 0 < v <= 50 + for k, v in packs.items()): + raise ValueError('theme_packs 必须是 {卡包中文名: 加分(1~50 的整数)}') + return {'team_names': names('team_names'), 'ego_names': names('ego_names'), + 'press_at': press_at, 'hold_seconds': float(hold), 'overclock_first_turn': overclock, + 'theme_packs': {k.strip(): v for k, v in packs.items()}} + + +def find_ego_option(lines, ego_names, near=None): + """OCR 逐行结果里找 E.G.O 名字(归一后完全相等); 有几条取离长按点最近的。返回 (文本, x, y) 或 None。""" + hits = [(text, x, y) for text, x, y in lines if normalize_team_name(text) in ego_names] + if not hits: + return None + if near is None: + return hits[0] + return min(hits, key=lambda hit: (hit[1] - near[0]) ** 2 + (hit[2] - near[1]) ** 2) + + +def rabbit_hole_turn(auto, cfg, config, log=print, overclock=False): + """接管一回合: P → 长按浮士德(press_at)打开 E.G.O 列表 → 选「空洞」→ Enter。 + + overclock=True 时长按 E.G.O 卡片(超频: 1.5 倍资源和理智, 强制用侵蚀技能), 否则单击。 + 返回结果: ego / overclock / ego_unavailable / no_option。 + 按过 P 就一定按 Enter(中途出错也一样): 交回 AALC 会再按一次 P, 而 P 是在胜率/伤害之间切换。 + """ + width, height = cfg.set_win_size * 16 / 9, cfg.set_win_size + x, y = config['press_at'][0] * width, config['press_at'][1] * height + names = config['ego_names'] + result = 'no_option' + auto.key_press('p') + try: + time.sleep(0.5) + auto.mouse_drag(x, y, drag_time=config['hold_seconds'], dx=0, dy=0) + time.sleep(RABBIT_HOLE_POPUP_WAIT) + auto.take_screenshot() + lines = _ocr_lines(auto) + hit = find_ego_option(lines, names, near=(x, y)) + if hit is None: + log('[lc_mcp] 兔子洞: 长按 (%d,%d) 后没找到 E.G.O「%s」; 这一屏: %s' + % (x, y, '/'.join(names), '/'.join(str(t) for t, _, _ in lines[:20]) or '(空)')) + else: + if overclock: + auto.mouse_drag(hit[1], hit[2], drag_time=config['hold_seconds'], dx=0, dy=0) + else: + auto.mouse_click(hit[1], hit[2]) + time.sleep(RABBIT_HOLE_SETTLE) + auto.take_screenshot() + if find_ego_option(_ocr_lines(auto), names) is None: + result = 'overclock' if overclock else 'ego' + else: + result = 'ego_unavailable' # 列表还开着: 资源不够(灰的)或没点上 + log('[lc_mcp] 兔子洞: %s「%s」后列表还在(可能 E.G.O 资源不够), 这回合按胜率打' + % ('长按' if overclock else '点了', hit[0])) + if result not in ('ego', 'overclock'): + auto.mouse_click_blank() # 关掉弹出的列表 + time.sleep(RABBIT_HOLE_SETTLE) + finally: + auto.key_press('enter') + decisions.record('battle', 'hollow', result) + return result + + +def install_rabbit_hole(log=print, config=None): + """镜牢战斗每回合给浮士德放「空洞」。返回原 Battle._battle_operation, 未安装返回 None。""" + try: + config = config or load_rabbit_hole() + except (OSError, ValueError) as e: + log('[ERROR] [lc_mcp] 兔子洞配置读不了(%s): %s' % (RABBIT_HOLE_FILE, e)) + return None + try: + from tasks.battle.battle import Battle + from module.automation import auto + from module.config import cfg + except Exception as e: + log('[lc_mcp] 兔子洞补丁跳过: 无法导入 %s' % e) + return None + original = getattr(Battle, '_battle_operation', None) + if original is None or _source_mentions(original, 'auto.key_press("p")', 'auto.key_press("enter")') is False: + log('[ERROR] [lc_mcp] 上游 Battle._battle_operation 不再是 P+Enter 出手, 兔子洞补丁挂不上, 跳过') + return None + state = {'warned': False} + overclock = config.get('overclock_first_turn', False) + signature = None + if overclock: + import inspect + try: + signature = inspect.signature(original) + except (TypeError, ValueError): + signature = None + if signature is None or 'first_turn' not in signature.parameters: + log('[ERROR] [lc_mcp] 上游 Battle._battle_operation 没有 first_turn 参数, 兔子洞第一回合不超频, 只放普通「空洞」') + overclock = False + + def first_turn(self, args, kwargs): + try: + return bool(signature.bind(self, *args, **kwargs).arguments.get('first_turn')) + except TypeError: + return False + + def _battle_operation(self, *args, **kwargs): + if config['press_at'] is None: + if not state['warned']: + state['warned'] = True + log('[ERROR] [lc_mcp] 兔子洞: rabbit_hole.json 的 press_at 还没在实机上量, 本次按 AALC 原来的 P+Enter 打') + return original(self, *args, **kwargs) + try: + rabbit_hole_turn(auto, cfg, config, log=log, + overclock=overclock and first_turn(self, args, kwargs)) + except InterruptedError: + raise # AALC 的暂停/停止 + except Exception as e: # Enter 已经在 rabbit_hole_turn 的 finally 里按过, 这回合照常打 + log('[lc_mcp] 兔子洞: 这回合出错(%s: %s), 已按 Enter' % (type(e).__name__, e)) + return False # 上游的返回值是「小指良单通的连续防御是否执行」 + + _battle_operation.__wrapped__ = original + Battle._battle_operation = _battle_operation + log('[lc_mcp] patch: 镜牢兔子洞: 每回合给浮士德放 E.G.O「%s」%s(%s)' + % ('/'.join(config['ego_names']), ', 每场第一回合超频' if overclock else '', + '长按点未校准, 先按 P+Enter' if config['press_at'] is None else '长按 %.3f,%.3f' % config['press_at'])) + return original diff --git a/lc_mcp/aalc_task.py b/lc_mcp/aalc_task.py index 66b096a..e5dbe31 100644 --- a/lc_mcp/aalc_task.py +++ b/lc_mcp/aalc_task.py @@ -11,7 +11,8 @@ import sys from . import killswitch, preflight from .aalc_engine import bootstrap -from .aalc_patches import (TaskAbort, WindowGuard, driver_click_tasks, headless_hdr_warning, +from .aalc_patches import (TaskAbort, WindowGuard, driver_click_tasks, headless_hdr_warning, install_rabbit_hole, + load_rabbit_hole, install_default_battle_team, install_event_choices, install_exact_team_match, install_gift_confirm_guard, install_gift_preference, install_key_hold, install_robust_set_foreground, install_shop_audit, install_shop_by_name, @@ -29,6 +30,10 @@ TASKS = { 'enkephalin': {'times': 'set_lunacy_to_enkephalin'}, 'mirror': {'count': 'set_mirror_count'}, } +# 任务 -> {选项名: 允许的值}; 不对应 AALC 配置项, 只决定本次装哪些补丁 +TASK_OPTIONS = { + 'mirror': {'strategy': ('rabbit_hole',)}, # rabbit_hole: 兔子洞速刷, 见 lc_mcp/data/rabbit_hole.json +} # 用户给了镜牢次数时一并临时关闭的配置: 开着无限刷牢, AALC 会把次数改成 9999 EXPLICIT_COUNT_OVERRIDES = {'mirror': {'count': {'infinite_dungeons': False}}} RESTORE_ENV = 'LCP_RESTORE_FILE' @@ -104,7 +109,23 @@ def run(task, params): return PREFLIGHT_EXIT +def split_options(task, params): + """把任务选项(TASK_OPTIONS)从参数里拆出来, 返回 (次数类参数, 选项)。""" + allowed = TASK_OPTIONS.get(task, {}) + params = dict(params) + options = {k: params.pop(k) for k in list(params) if k in allowed} + return params, options + + def _run(task, params): + params, options = split_options(task, params) + rabbit = None + if options.get('strategy') == 'rabbit_hole': + try: + rabbit = load_rabbit_hole() + except (OSError, ValueError) as e: + log('[ERROR] [lc_mcp] 兔子洞配置读不了: %s' % e) + return PREFLIGHT_EXIT bootstrap() from module.automation import auto from module.config import cfg @@ -133,7 +154,7 @@ def _run(task, params): install_default_battle_team(scheme, log=log) # 镜牢: 编队是自定义名字(体系名), AALC 只会找 "编队#N"; 改成按体系名点选。 if task in ('mirror', 'all'): - install_system_team_selection(log=log) + install_system_team_selection(log=log, names=rabbit['team_names'] if rabbit else None) install_team_screen_guard(log=log) install_gift_confirm_guard(log=log) # 「获得E.G.O饰品」点不关时换落点/结束任务(ISSUES I-06) install_typed_keyboard_road(log=log) @@ -141,8 +162,13 @@ def _run(task, params): install_event_choices(log=log) install_shop_audit(log=log) install_shop_by_name(log=log) # 装在审计之后(包在外层), 审计才看得到按名字点的那一下 - install_theme_pack_systems(log=log) # 卡包按体系加分(BACKLOG R-01) + if rabbit: # 卡包按体系加分(BACKLOG R-01); 兔子洞再给攻略路线上的卡包加分 + install_theme_pack_systems(log=log, route=rabbit['theme_packs'], route_name='兔子洞路线') + else: + install_theme_pack_systems(log=log) install_theme_pack_audit(log=log) # 装在加分之后(包在外层), 审计记得到加分 + if rabbit: + install_rabbit_hole(log=log, config=rabbit) guard = WindowGuard(screen, cfg, log=log) guard.start() restore_path = os.environ.get(RESTORE_ENV) @@ -189,10 +215,16 @@ def main(argv): return 2 task = argv[1] params = json.loads(argv[2]) if len(argv) > 2 else {} - unknown = set(params) - set(TASKS[task]) + options = TASK_OPTIONS.get(task, {}) + unknown = set(params) - set(TASKS[task]) - set(options) if unknown: print('unknown params for %s: %s' % (task, ', '.join(sorted(unknown))), file=sys.stderr) return 2 + bad = {k: v for k, v in params.items() if k in options and v not in options[k]} + if bad: + print('bad option for %s: %s' % (task, ', '.join('%s=%r' % kv for kv in sorted(bad.items()))), + file=sys.stderr) + return 2 print('[lc_mcp] task %s start %s' % (task, json.dumps(params)), flush=True) code = run(task, params) if code: diff --git a/lc_mcp/data/rabbit_hole.json b/lc_mcp/data/rabbit_hole.json new file mode 100644 index 0000000..a67fcfb --- /dev/null +++ b/lc_mcp/data/rabbit_hole.json @@ -0,0 +1,21 @@ +{ + "_说明": [ + "镜牢「兔子洞」速刷(Mao Hollow Faust): 黑兽 - 卯 魁首 浮士德 + 浮士德的 E.G.O「空洞」。run_task(task=\"mirror\", strategy=\"rabbit_hole\") 时生效。", + "每回合: 按 P(胜率) → 长按浮士德(press_at)打开 E.G.O 列表 → OCR 找 ego_names 里的名字, 单击放 E.G.O(每场第一回合长按 = 超频) → 按 Enter。", + "游戏数据(零协 release 2026111301): 人格 id 10212; E.G.O id 20211「空洞」。普通「空洞」不打敌人, 只给自己叠 5 发弹孔; 弹孔不低于 1 发时改用「填补空洞」(大伤害);", + "超频(侵蚀)的「空洞」直接随机打人。E.G.O 被动「排离空洞」: 弹孔满 5 发时「空洞」(觉醒、侵蚀)不耗 E.G.O 资源, 每回合开始 +1 发弹孔。", + "超频: 游戏教程「在战斗中选择 E.G.O 技能时, 可以长按 E.G.O 来使用 E.G.O 超频」, 1.5 倍 E.G.O 资源和理智; 资源够 1.5 倍是稳定超频(只打敌人), 不够是不稳定超频(不分敌我, 缺的资源扣成负数)。", + "overclock_first_turn: 每场战斗第一回合超频(OurPlay 攻略「前期每战第一回合侵蚀空洞」), 之后的回合单击。后期 Boss 攻略改成第一回合普通「空洞」, 这里不区分。", + "press_at 是长按点在游戏客户区里的位置(宽、高的比例, 0~1), 必须在实机上量。游戏教程是「按住罪人的头像以打开其 E.G.O 列表」, wiki.gg 写的是按住技能格, 以实机为准。", + "press_at 为 null 时不点任何东西, 记一条 [ERROR] 后按 AALC 原来的 P+Enter 打。team_names 是这套打法用的编队名(游戏里自己建)。", + "hold_seconds 是 AALC mouse_drag 的停留时间, 它松开前还会再按住 0.5 秒, 实际按住约 hold_seconds+0.5 秒; 长按头像和超频长按卡片都用它。", + "theme_packs: 攻略路线上的卡包 {中文名: 加分}, 加在 AALC 原权重上(没有体系也加)。OurPlay 全程困难路线: 1 层身无分文的赌徒 → 2 层地狱鸡 → 3 层去·海·边 → 4 层憎恶与绝望 → 5 层 2号线。", + "AALC 默认权重(困难 + 中文): 赌徒 0、地狱鸡 1、海边 0、绝望 -5、号线 -5; 憎恶与绝望多加 2 分, 4 层和 2号线同时出现时先选它(2号线 4、5 层都会出)。LCP_THEME_PACK_SYSTEMS=0 时路线加分一起关掉。" + ], + "team_names": ["兔子洞"], + "ego_names": ["空洞"], + "press_at": null, + "hold_seconds": 1.0, + "overclock_first_turn": true, + "theme_packs": {"身无分文的赌徒": 10, "地狱鸡": 10, "去·海·边": 10, "憎恶与绝望": 12, "2号线": 10} +} diff --git a/lc_mcp/protocol.py b/lc_mcp/protocol.py index 16a5eae..50764b8 100644 --- a/lc_mcp/protocol.py +++ b/lc_mcp/protocol.py @@ -6,7 +6,7 @@ import threading import time from . import VERSION -from .aalc_task import TASKS +from .aalc_task import TASK_OPTIONS, TASKS from .engine import find_hits MAX_WAIT = 300.0 @@ -83,9 +83,14 @@ TOOLS = [ '传 count 时本次临时关闭 AALC 无限刷牢,结束后恢复;完成局数不足时任务报 failed。' '只刷一种日常时把另一种次数显式设为0,省略次数沿用配置。' 'all 需明确要求全部任务;enkephalin 需明确授权花狂气,免费合成模块不能用它。' - '任务运行期间禁止手动点击类工具;最终 succeeded 也要检查 errors,用户停止后不自动重跑。'), + '任务运行期间禁止手动点击类工具;最终 succeeded 也要检查 errors,用户停止后不自动重跑。' + 'mirror 可加 strategy="rabbit_hole":兔子洞速刷(黑兽-卯 浮士德每回合放 E.G.O「空洞」,每场第一回合超频),' + '编队、长按点、路线卡包见 lc_mcp/data/rabbit_hole.json。'), 'inputSchema': _obj({'task': {'type': 'string', 'enum': sorted(TASKS)}, - 'exp': _NUM, 'thread': _NUM, 'times': _NUM, 'count': _NUM}, ['task'])}, + 'exp': _NUM, 'thread': _NUM, 'times': _NUM, 'count': _NUM, + 'strategy': {'type': 'string', 'enum': sorted({v for o in TASK_OPTIONS.values() + for v in o['strategy']})}}, + ['task'])}, {'name': 'task_status', 'description': '启动 run_task 前检查占用,启动后轮询此工具监控,避免逐帧截图和重复启动。' '返回 idle/running/succeeded/failed/stopped、日志及异常;' 'decisions.counts 按阶段统计选队/寻路/卡包/饰品/事件/商店的决策理由。' @@ -158,6 +163,13 @@ class Server: if task not in TASKS: raise ValueError('unknown task %r' % task) params = {k: int(a[k]) for k in TASKS[task] if a.get(k) is not None} + options = TASK_OPTIONS.get(task, {}) + for key in ('strategy',): + if a.get(key) is None: + continue + if a[key] not in options.get(key, ()): + raise ValueError('%s 不支持 %s=%r' % (task, key, a[key])) + params[key] = a[key] # Starting must not race a click that has already checked running(). # Reject promptly when busy instead of waiting behind a long OCR poll. if not self.lock.acquire(blocking=False): diff --git a/tests/test_lc_mcp.py b/tests/test_lc_mcp.py index 7697a7b..3100f34 100644 --- a/tests/test_lc_mcp.py +++ b/tests/test_lc_mcp.py @@ -191,6 +191,17 @@ class ProtocolTest(unittest.TestCase): self.assertTrue(call(self.s, 'click', x=1, y=1)['ok']) self.assertFalse(call(self.s, 'run_task', task='bogus')['ok']) + def test_run_task_strategy_option(self): + self.assertIn('rabbit_hole', next(t for t in TOOLS if t['name'] == 'run_task') + ['inputSchema']['properties']['strategy']['enum']) + self.assertIn('不支持 strategy', call(self.s, 'run_task', task='mirror', strategy='fast')['error']) + self.assertIn('不支持 strategy', call(self.s, 'run_task', task='daily', strategy='rabbit_hole')['error']) + self.assertEqual(call(self.s, 'task_status')['state'], 'idle') + r = call(self.s, 'run_task', task='mirror', count=1, strategy='rabbit_hole') + self.assertTrue(r['ok'], r) + self.assertEqual(call(self.s, 'task_status')['params'], {'count': 1, 'strategy': 'rabbit_hole'}) + self.assertEqual(call(self.s, 'stop_task')['state'], 'stopped') + def test_task_exit_codes(self): self.tasks.argv_factory = lambda t, p: [sys.executable, '-c', 'import sys; sys.exit(3)'] call(self.s, 'run_task', task='reward') diff --git a/tests/test_rabbit_hole.py b/tests/test_rabbit_hole.py new file mode 100644 index 0000000..8858ab5 --- /dev/null +++ b/tests/test_rabbit_hole.py @@ -0,0 +1,342 @@ +# -*- coding: utf-8 -*- +"""镜牢「兔子洞」速刷: 黑兽 - 卯 魁首 浮士德每回合放 E.G.O「空洞」。 + +AALC 战斗只会 P+Enter; 补丁接管一回合: P → 长按浮士德打开 E.G.O 列表 → OCR 找「空洞」→ Enter。 +每场第一回合长按卡片(超频, 直接打人), 之后单击(弹孔不低于 1 发时游戏改用「填补空洞」)。 +长按点(press_at)要在实机上量, 没量时不点任何东西, 照 AALC 原来的 P+Enter 打。 +""" +import ast +import json +import os +import sys +import tempfile +import types +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO)) +from lc_mcp import aalc_patches as ap # noqa: E402 +from lc_mcp import aalc_task # noqa: E402 + +BATTLE = REPO / 'vendor' / 'aalc' / 'tasks' / 'battle' / 'battle.py' +CONFIG = {'team_names': ('兔子洞',), 'ego_names': ('空洞',), 'press_at': (0.25, 0.8), 'hold_seconds': 1.0} +PRESS = (0.25 * 1280, 0.8 * 720) + + +class BattleScreen: + """战斗面板: 长按到浮士德(±20 像素)才弹出 E.G.O 列表; 点到或长按可用的「空洞」列表就关。""" + + def __init__(self, usable=True, popup_text='空洞', press=PRESS): + self.usable = usable + self.popup_text = popup_text + self.press = press + self.popup = False + self.selected = False + self.overclocked = False + self.calls = [] + + @property + def screenshot(self): + return self + + def take_screenshot(self): + return self + + def read(self): + lines = [('回合 1', 640, 30), ('胜率', 1100, 600)] + if self.popup: + lines += [(self.popup_text, self.press[0] + 40, self.press[1] - 160), ('表象放射体', self.press[0] + 40, self.press[1] - 220)] + return SimpleNamespace(txts=tuple(t for t, _, _ in lines), + boxes=[[[x - 10, y - 5], [x + 10, y - 5], [x + 10, y + 5], [x - 10, y + 5]] + for _, x, y in lines]) + + def key_press(self, key): + self.calls.append(('key', key)) + + def on_card(self, x, y): + return abs(x - (self.press[0] + 40)) <= 10 and abs(y - (self.press[1] - 160)) <= 10 + + def mouse_drag(self, x, y, drag_time=0.1, dx=0, dy=0): + self.calls.append(('hold', round(x), round(y), drag_time, dx, dy)) + if self.popup and self.on_card(x, y): + if self.usable: + self.popup, self.selected, self.overclocked = False, True, True + elif abs(x - self.press[0]) <= 20 and abs(y - self.press[1]) <= 20: + self.popup = True + + def mouse_click(self, x, y, *args, **kwargs): + self.calls.append(('click', round(x), round(y))) + if self.popup and self.usable and self.on_card(x, y): + self.popup, self.selected = False, True + + def mouse_click_blank(self, *args, **kwargs): + self.calls.append(('blank',)) + self.popup = False + + +class RabbitHoleTurnTest(unittest.TestCase): + + def setUp(self): + self.lines = [] + engine = SimpleNamespace(ocr=SimpleNamespace(run=lambda screen: screen.read())) + for patcher in (mock.patch.dict(sys.modules, {'module': types.ModuleType('module'), 'module.ocr': engine}), + mock.patch.object(ap.time, 'sleep')): + patcher.start() + self.addCleanup(patcher.stop) + record = mock.patch.object(ap.decisions, 'record') + self.record = record.start() + self.addCleanup(record.stop) + self.cfg = SimpleNamespace(set_win_size=720) + + def turn(self, screen, config=CONFIG, overclock=False): + return ap.rabbit_hole_turn(screen, self.cfg, config, log=self.lines.append, overclock=overclock) + + def test_selects_hollow_between_p_and_enter(self): + screen = BattleScreen() + self.assertEqual(self.turn(screen), 'ego') + self.assertTrue(screen.selected) + self.assertEqual(screen.calls, [('key', 'p'), ('hold', 320, 576, 1.0, 0, 0), ('click', 360, 416), ('key', 'enter')]) + self.record.assert_called_once_with('battle', 'hollow', 'ego') + + def test_overclock_holds_the_card_instead_of_clicking(self): + # 游戏教程: 选择 E.G.O 技能时长按 E.G.O 卡片 = 超频 + screen = BattleScreen() + self.assertEqual(self.turn(screen, overclock=True), 'overclock') + self.assertTrue(screen.overclocked) + self.assertEqual(screen.calls, [('key', 'p'), ('hold', 320, 576, 1.0, 0, 0), ('hold', 360, 416, 1.0, 0, 0), + ('key', 'enter')]) + self.record.assert_called_once_with('battle', 'hollow', 'overclock') + + def test_overclock_on_a_greyed_out_card_closes_the_list(self): + screen = BattleScreen(usable=False) + self.assertEqual(self.turn(screen, overclock=True), 'ego_unavailable') + self.assertFalse(screen.overclocked) + self.assertEqual(screen.calls[-2:], [('blank',), ('key', 'enter')]) + self.assertIn('兔子洞: 长按「空洞」后列表还在', '\n'.join(self.lines)) + + def test_fill_in_name_is_matched_after_normalising(self): + screen = BattleScreen(popup_text='空 洞') + self.assertEqual(self.turn(screen), 'ego') + + def test_greyed_out_hollow_closes_the_list_and_still_fights(self): + screen = BattleScreen(usable=False) + self.assertEqual(self.turn(screen), 'ego_unavailable') + self.assertEqual(screen.calls[-2:], [('blank',), ('key', 'enter')]) + self.assertIn('兔子洞: 点了「空洞」后列表还在(可能 E.G.O 资源不够)', '\n'.join(self.lines)) + + def test_wrong_press_point_reports_what_was_on_screen(self): + screen = BattleScreen(press=(900, 500)) + self.assertEqual(self.turn(screen), 'no_option') + self.assertEqual(screen.calls[-2:], [('blank',), ('key', 'enter')]) + self.assertIn('长按 (320,576) 后没找到 E.G.O「空洞」; 这一屏: 回合 1/胜率', '\n'.join(self.lines)) + + def test_error_after_p_still_presses_enter(self): + # 交回 AALC 会再按一次 P, 而 P 在胜率/伤害之间切换 + screen = BattleScreen() + screen.mouse_drag = mock.Mock(side_effect=RuntimeError('input lost')) + with self.assertRaises(RuntimeError): + self.turn(screen) + self.assertEqual(screen.calls, [('key', 'p'), ('key', 'enter')]) + + +class LoadRabbitHoleTest(unittest.TestCase): + + def test_shipped_config_is_uncalibrated(self): + config = ap.load_rabbit_hole() + self.assertEqual(config['team_names'], ('兔子洞',)) + self.assertEqual(config['ego_names'], ('空洞',)) + self.assertIsNone(config['press_at']) + self.assertIs(config['overclock_first_turn'], True) + self.assertEqual(config['theme_packs'], {'身无分文的赌徒': 10, '地狱鸡': 10, '去·海·边': 10, + '憎恶与绝望': 12, '2号线': 10}) + + def test_shipped_route_packs_are_in_the_pack_table(self): + _, packs = ap.load_theme_pack_systems() + floors = {pack['zh']: pack['hard'].split(',') for pack in packs} + route = ap.load_rabbit_hole()['theme_packs'] + # OurPlay 全程困难路线: 1~5 层各一个 + for floor, name in enumerate(route, 1): + with self.subTest(name=name): + self.assertIn('%dF' % floor, floors[name]) + + def test_bad_configs(self): + base = {'team_names': ['兔子洞'], 'ego_names': ['空洞'], 'press_at': None, 'hold_seconds': 1} + for change in ({'team_names': []}, {'ego_names': ['']}, {'press_at': [0.5]}, {'press_at': [1.2, 0.5]}, + {'press_at': [0, 0.5]}, {'hold_seconds': 9}, {'hold_seconds': True}, + {'overclock_first_turn': 'yes'}, {'theme_packs': ['地狱鸡']}, {'theme_packs': {'地狱鸡': 0}}, + {'theme_packs': {'地狱鸡': True}}, {'theme_packs': {' ': 3}}): + with self.subTest(change=change), tempfile.TemporaryDirectory() as d: + path = os.path.join(d, 'r.json') + with open(path, 'w', encoding='utf-8') as fh: + json.dump(dict(base, **change), fh) + with self.assertRaises(ValueError): + ap.load_rabbit_hole(path) + + def test_calibrated_point(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, 'r.json') + with open(path, 'w', encoding='utf-8') as fh: + json.dump({'team_names': ['兔子洞'], 'ego_names': ['空洞'], 'press_at': [0.3, 0.85]}, fh) + config = ap.load_rabbit_hole(path) + self.assertEqual(config['press_at'], (0.3, 0.85)) + self.assertEqual((config['overclock_first_turn'], config['theme_packs']), (False, {})) + + +class FakeBattle: + def _battle_operation(self, first_turn, defense_first_round, avoid_skill_3, **kwargs): + if kwargs.get('never'): # 只给安装时的源码检查看, 测试里走不到 + auto.key_press("p") # noqa: F821 + auto.key_press("enter") # noqa: F821 + return 'upstream' + + +class InstallRabbitHoleTest(unittest.TestCase): + + def install(self, config, battle_cls=None): + self.lines = [] + self.battle_cls = battle_cls or type('Battle', (FakeBattle,), {}) + self.original = self.battle_cls._battle_operation + self.original_calls = [] + original = self.original + + def counted(this, *args, **kwargs): + self.original_calls.append(args) + return original(this, *args, **kwargs) + + counted.__wrapped__ = original + self.battle_cls._battle_operation = counted + battle_mod = types.ModuleType('tasks.battle.battle') + battle_mod.Battle = self.battle_cls + self.auto = SimpleNamespace() + modules = {'tasks': types.ModuleType('tasks'), 'tasks.battle': types.ModuleType('tasks.battle'), + 'tasks.battle.battle': battle_mod, 'module': types.ModuleType('module'), + 'module.automation': SimpleNamespace(auto=self.auto), + 'module.config': SimpleNamespace(cfg=SimpleNamespace(set_win_size=720))} + patcher = mock.patch.dict(sys.modules, modules) + patcher.start() + self.addCleanup(patcher.stop) + return ap.install_rabbit_hole(log=self.lines.append, config=config) + + def test_uncalibrated_keeps_upstream_and_says_so_once(self): + self.assertIsNotNone(self.install(dict(CONFIG, press_at=None))) + battle = self.battle_cls() + with mock.patch.object(ap, 'rabbit_hole_turn') as turn: + self.assertEqual(battle._battle_operation(True, False, False), 'upstream') + self.assertEqual(battle._battle_operation(False, False, False), 'upstream') + turn.assert_not_called() + log = '\n'.join(self.lines) + self.assertEqual(log.count('[ERROR] [lc_mcp] 兔子洞: rabbit_hole.json 的 press_at 还没在实机上量'), 1) + self.assertIn('patch: 镜牢兔子洞: 每回合给浮士德放 E.G.O「空洞」(长按点未校准, 先按 P+Enter)', log) + + def test_calibrated_turn_replaces_upstream(self): + self.install(CONFIG) + with mock.patch.object(ap, 'rabbit_hole_turn', return_value='ego') as turn: + self.assertIs(self.battle_cls()._battle_operation(True, False, False), False) + turn.assert_called_once() + self.assertEqual(self.original_calls, []) + + def test_overclock_only_on_the_first_turn(self): + self.install(dict(CONFIG, overclock_first_turn=True)) + battle = self.battle_cls() + with mock.patch.object(ap, 'rabbit_hole_turn', return_value='ego') as turn: + battle._battle_operation(True, False, False) # 上游 fight 按关键字传, 位置参数也要认 + battle._battle_operation(first_turn=False, defense_first_round=False, avoid_skill_3=False) + battle._battle_operation(first_turn=True, defense_first_round=False, avoid_skill_3=False, + prioritize_skill_3=False) + self.assertEqual([c.kwargs['overclock'] for c in turn.call_args_list], [True, False, True]) + self.assertIn('每回合给浮士德放 E.G.O「空洞」, 每场第一回合超频(长按 0.250,0.800)', '\n'.join(self.lines)) + + def test_overclock_off_never_holds_the_card(self): + self.install(dict(CONFIG, overclock_first_turn=False)) + with mock.patch.object(ap, 'rabbit_hole_turn', return_value='ego') as turn: + self.battle_cls()._battle_operation(True, False, False) + self.assertIs(turn.call_args.kwargs['overclock'], False) + + def test_upstream_without_first_turn_disables_overclock(self): + class NoFirstTurn: + def _battle_operation(self, *args, **kwargs): + if kwargs.get('never'): + auto.key_press("p") # noqa: F821 + auto.key_press("enter") # noqa: F821 + + self.install(dict(CONFIG, overclock_first_turn=True), battle_cls=NoFirstTurn) + with mock.patch.object(ap, 'rabbit_hole_turn', return_value='ego') as turn: + NoFirstTurn()._battle_operation(True, False, False) + self.assertIs(turn.call_args.kwargs['overclock'], False) + self.assertIn('[ERROR] [lc_mcp] 上游 Battle._battle_operation 没有 first_turn 参数', '\n'.join(self.lines)) + + def test_turn_error_is_contained(self): + self.install(CONFIG) + with mock.patch.object(ap, 'rabbit_hole_turn', side_effect=RuntimeError('ocr down')): + self.assertIs(self.battle_cls()._battle_operation(True, False, False), False) + self.assertIn('兔子洞: 这回合出错(RuntimeError: ocr down), 已按 Enter', '\n'.join(self.lines)) + + def test_interrupt_is_not_swallowed(self): + self.install(CONFIG) + with mock.patch.object(ap, 'rabbit_hole_turn', side_effect=InterruptedError): + with self.assertRaises(InterruptedError): + self.battle_cls()._battle_operation(True, False, False) + + def test_upstream_without_p_enter_is_an_error(self): + class Other: + def _battle_operation(self, *args): + return None + + self.assertIsNone(self.install(CONFIG, battle_cls=Other)) + self.assertIn('[ERROR] [lc_mcp] 上游 Battle._battle_operation 不再是 P+Enter 出手', '\n'.join(self.lines)) + + @unittest.skipUnless(BATTLE.is_file(), 'vendor/aalc 子模块未检出') + def test_current_upstream_turn_is_p_then_enter(self): + source = BATTLE.read_text(encoding='utf-8') + cls = next(n for n in ast.parse(source).body if isinstance(n, ast.ClassDef) and n.name == 'Battle') + node = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == '_battle_operation') + body = ast.get_source_segment(source, node) + self.assertIn('auto.key_press("p")', body) + self.assertIn('auto.key_press("enter")', body) + self.assertEqual(node.args.args[1].arg, 'first_turn') + fight = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == 'fight') + self.assertIn('first_turn=first_turn', ast.get_source_segment(source, fight)) + + +class StrategyOptionTest(unittest.TestCase): + + def test_options_are_split_from_counts(self): + self.assertEqual(aalc_task.split_options('mirror', {'count': 2, 'strategy': 'rabbit_hole'}), + ({'count': 2}, {'strategy': 'rabbit_hole'})) + self.assertEqual(aalc_task.split_options('daily', {'exp': 1}), ({'exp': 1}, {})) + + def test_cli_rejects_unknown_strategy_and_strategy_on_other_tasks(self): + for argv in (['x', 'mirror', '{"strategy": "fast"}'], ['x', 'daily', '{"strategy": "rabbit_hole"}']): + with self.subTest(argv=argv), mock.patch.object(aalc_task, 'run') as run, \ + mock.patch('sys.stderr'): + self.assertEqual(aalc_task.main(argv), 2) + run.assert_not_called() + + def test_cli_passes_the_strategy_through(self): + with mock.patch.object(aalc_task, 'run', return_value=0) as run, mock.patch('builtins.print'): + self.assertEqual(aalc_task.main(['x', 'mirror', '{"count": 1, "strategy": "rabbit_hole"}']), 0) + run.assert_called_once_with('mirror', {'count': 1, 'strategy': 'rabbit_hole'}) + + def test_team_names_override_the_system(self): + mirror_mod = types.ModuleType('tasks.mirror.mirror') + mirror_mod.Mirror = type('Mirror', (), {'__init__': lambda self, setting, num: setattr(self, 'system', 'bleed')}) + mirror_mod.select_battle_team = lambda num: False + package = types.ModuleType('tasks.mirror') + package.mirror = mirror_mod + modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.mirror': mirror_mod, + 'module': types.ModuleType('module'), 'module.automation': SimpleNamespace(auto=mock.Mock())} + lines = [] + with mock.patch.dict(sys.modules, modules): + ap.install_system_team_selection(log=lines.append, names=('兔子洞',)) + mirror_mod.Mirror({}, 1) + with mock.patch.object(ap, '_select_team_by_name', return_value=True) as select: + mirror_mod.select_battle_team(1) + self.assertEqual(select.call_args[0][1], ('兔子洞',)) + self.assertIn('镜牢体系 bleed -> 目标编队 兔子洞', '\n'.join(lines)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_theme_pack_systems.py b/tests/test_theme_pack_systems.py index 47fcc06..2a0b08f 100644 --- a/tests/test_theme_pack_systems.py +++ b/tests/test_theme_pack_systems.py @@ -83,6 +83,12 @@ class ThemePackTableTest(unittest.TestCase): self.assertEqual(ap.theme_pack_bonus(self.by_name['被遗忘者们'], 'charge', b), -3) self.assertEqual(ap.theme_pack_bonus(self.by_name['当碎之物'], 'blunt', b), 3) # 体系包 6, 拖时间 -3 + def test_route_bonus_ignores_system_and_avoid(self): + b = self.bonus + self.assertEqual(ap.theme_pack_bonus(dict(self.by_name['被遗忘者们'], route=5), None, b), 5) + self.assertEqual(ap.theme_pack_bonus(dict(self.by_name['憎恶与绝望'], route=2), 'charge', b), 6) # 取大的 + self.assertEqual(ap.theme_pack_bonus(self.by_name['憎恶与绝望'], None, b), 0) + def test_bonus_tiers(self): self.assertEqual(ap.theme_pack_bonus(self.by_name['电闪雷鸣'], 'charge', self.bonus), 6) self.assertEqual(ap.theme_pack_bonus(self.by_name['WARP快车谋杀案'], 'charge', self.bonus), 6) @@ -232,7 +238,7 @@ class UpstreamSelectThemePackTest(unittest.TestCase): self.node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'select_theme_pack') self.node.decorator_list = [] - def play(self, cards, system, patched=True, audit=False, env=None, hard=False): + def play(self, cards, system, patched=True, audit=False, env=None, hard=False, route=None): positions = [(300 + 300 * i, 300) for i in range(len(cards))] weights = example_weights('theme_pack_list_cn', *(('theme_pack_list_hard_cn',) if hard else ())) lookups = [] @@ -272,7 +278,8 @@ class UpstreamSelectThemePackTest(unittest.TestCase): mock.patch.object(logger, 'level', logging.DEBUG), mock.patch.object(logger, 'propagate', False), \ mock.patch.object(ap.decisions, 'record') as record: if patched: - self.assertIsNotNone(ap.install_theme_pack_systems(log=self.lines.append, env=env or {})) + self.assertIsNotNone(ap.install_theme_pack_systems(log=self.lines.append, env=env or {}, + route=route, route_name='兔子洞路线')) if audit: ap.install_theme_pack_audit(log=self.lines.append) mirror_mod.Mirror(system) @@ -333,6 +340,23 @@ class UpstreamSelectThemePackTest(unittest.TestCase): self.assertEqual(picked, '落泪者们') self.assertEqual(lookups[0], example_weights('theme_pack_list_cn')) + def test_rabbit_hole_route_without_a_system(self): + # 兔子洞编队没有体系; 困难模式 AALC 默认「绝望」「号线」都是 -5, 不加分拿 0 分的落泪者们 + route = ap.load_rabbit_hole()['theme_packs'] + floor4 = ['2号线', '憎恶与绝望', '落泪者们'] + self.assertEqual(self.play(floor4, None, hard=True)[0], '落泪者们') + self.assertEqual(self.play(floor4, None, hard=True, route=route)[0], '憎恶与绝望') # 2号线留给 5 层 + self.assertIn('卡包按体系 (无)+兔子洞路线 加分: ', self.log) + self.assertIn('兔子洞路线 身无分文的赌徒+10 地狱鸡+10 去·海·边+10 憎恶与绝望+12 2号线+10', self.log) + self.assertEqual(self.play(['电闪雷鸣', '2号线'], None, hard=True, route=route)[0], '2号线') + self.assertEqual(self.play(['地狱鸡', '去·海·边'], None, hard=True, route=route)[0], '地狱鸡') + self.assertEqual(self.play(['憎恶与绝望', '去·海·边'], None, hard=True, route=route)[0], '去·海·边') + + def test_route_beats_the_system_bonus_and_unknown_names_are_errors(self): + picked, _, _ = self.play(self.FLOOR4, 'charge', route={'落泪者们': 20, '不存在的包': 5}) + self.assertEqual(picked, '落泪者们') + self.assertIn('[ERROR] [lc_mcp] 兔子洞路线卡包不在卡包表里, 不加分: 不存在的包', self.log) + def test_env_zero_and_bad_table(self): self.assertIsNone(ap.install_theme_pack_systems(log=self.lines.append, env={ap.THEME_PACK_SYSTEMS_ENV: '0'})) with tempfile.TemporaryDirectory() as d: