P1-4 镜牢事件按选项表选择

Browse Source
- 包住 Mirror.event_handling:上游每轮挑选项前(找 unknown_event 那一步),
  画面有选项框时整屏 OCR,按行把文字归到各选项;认出表里的事件就点对应选项,
  没收录/选项不在画面上照常交给上游,调用结束还原 click_element
- 表 lc_mcp/data/event_choices.json 10 条,取自事件速查里的直出/免费奖励;
  按选项文字优先,按编号只用于第一屏、画面没变时最多重试 3 次
- 每屏选项打一次日志(含未收录事件的选项文字,便于补表)
- LCP_EVENT_CHOICES=0 关闭,=<路径> 换表;表读不了记 [ERROR] 不装
- 单测执行上游真实 event_handling

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-11-14 07:04:59 +00:00
co-authored by Claude Opus 5.5
parent 2f8f15a886
commit 4376d9cfb2
6 changed files with 508 additions and 1 deletions
+3
View File
@@ -169,6 +169,8 @@ MCP 初始化说明与工具描述均指导 AI 优先使用 AALC:常规日常
按上游权重(事件 < 商店 < 战斗 < …)依次按方向键,进不去再退回 ↑;不拖地图。`LCP_TYPED_ROAD=0` 关闭。 按上游权重(事件 < 商店 < 战斗 < …)依次按方向键,进不去再退回 ↑;不拖地图。`LCP_TYPED_ROAD=0` 关闭。
- **饰品选择按体系关键词**:镜牢路上的饰品 N 选一,先整屏 OCR,按卡面上命中当前体系关键词的行数给卡排序, - **饰品选择按体系关键词**:镜牢路上的饰品 N 选一,先整屏 OCR,按卡面上命中当前体系关键词的行数给卡排序,
再交给 AALC 原逻辑(跳过白棉花、已持有排后)。关键词表在 `lc_mcp/data/gift_keywords.json`。 再交给 AALC 原逻辑(跳过白棉花、已持有排后)。关键词表在 `lc_mcp/data/gift_keywords.json`。
- **事件选项表**:事件出现选项时整屏 OCR,认出 `lc_mcp/data/event_choices.json` 里的事件就按选项文字(或第几项)点;
没收录的事件照旧交给 AALC,日志会打印这一屏的选项文字,便于补表。
## 无人值守 ## 无人值守
@@ -218,6 +220,7 @@ powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Every
| `LCP_KEEP_SHOTS` | 30 | 截图保留张数 | | `LCP_KEEP_SHOTS` | 30 | 截图保留张数 |
| `LCP_ALLOW_LUNACY` | 未设置 | 设为 `1` 时允许预检放行 `set_lunacy_to_enkephalin` 不为 0 的配置 | | `LCP_ALLOW_LUNACY` | 未设置 | 设为 `1` 时允许预检放行 `set_lunacy_to_enkephalin` 不为 0 的配置 |
| `LCP_TYPED_ROAD` | 未设置 | 设为 `0` 时镜牢简单键盘寻路保持上游的"只按 ↑",不按节点类型选方向 | | `LCP_TYPED_ROAD` | 未设置 | 设为 `0` 时镜牢简单键盘寻路保持上游的"只按 ↑",不按节点类型选方向 |
| `LCP_EVENT_CHOICES` | 未设置 | 设为 `0` 时事件不查选项表;设为 JSON 文件路径时用它代替 `lc_mcp/data/event_choices.json` |
| `LCP_GIFT_KEYWORDS` | 未设置 | 设为 `0` 时饰品选择不按体系关键词排序;设为 JSON 文件路径时用它代替 `lc_mcp/data/gift_keywords.json` | | `LCP_GIFT_KEYWORDS` | 未设置 | 设为 `0` 时饰品选择不按体系关键词排序;设为 JSON 文件路径时用它代替 `lc_mcp/data/gift_keywords.json` |
| `LCP_KILL_KEY` | `end` | 任务子进程的急停键,如 `pause` / `scrolllock`;认不出的键名会报错而不是换成默认键 | | `LCP_KILL_KEY` | `end` | 任务子进程的急停键,如 `pause` / `scrolllock`;认不出的键名会报错而不是换成默认键 |
| `LC_PY` | 当前解释器 | `levelup.py`/`auto_cycle.py` 调用 MCP 用的 Python | | `LC_PY` | 当前解释器 | `levelup.py`/`auto_cycle.py` 调用 MCP 用的 Python |
+21
View File
@@ -146,6 +146,27 @@ Dijkstra 那套(`search_road.py:735`,代价 event 1 / shop 2 / battle 4 / bo
**风险**:低-中。选项点错可能拿不到奖励,但不会卡死。 **风险**:低-中。选项点错可能拿不到奖励,但不会卡死。
**状态(2026-11-14 云端)**:已实现,待实机验收。
- 做法:`install_event_choices()` 包住 `Mirror.event_handling`,调用期间临时替换 `auto.click_element`。
上游每轮挑选项的第一步是 `click_element("event/unknown_event.png")`,补丁在这一步之前插一次判断:
`event/select_first_option_assets.png` 多目标匹配到选项框(每项的左边缘)时整屏 OCR,把右侧同一行的文字归到各项;
画面上的文字命中表里某个事件,就点对应选项的左边缘(与上游点第一项的位置一致),并告诉上游"已点"(`event_chance -= 1`)。
其余情况(不在选项画面、事件没收录、表里的选项不在画面上)照常交给上游。
- 表 `lc_mcp/data/event_choices.json`(JSON,不加依赖),10 条,全部取自
`docs/skills/limbus-mirror-speedrun/references/event-choices.md` 里无判定/无战斗的直出或免费奖励。
- `text`(按选项文字)优先:红色坐像「侧耳倾听」、炸鸡对决「鸡肉就是鸡肉」、梦中的电子羊「你不是特别的」、失明巨人「什么都没有写」。
- `index`(按第几项)只用于事件的第一屏选项;画面没变时最多重试 3 次,之后的分支交给上游。参考文档提醒过
Wiki 编号可能与当前顺序不同,所以编号规则一律以实机日志核对。
- 规则按顺序匹配,`折射的往昔的睡袋`(1)排在 `往昔的睡袋`(2)前面。
- 日志:每屏选项只打一次,`[lc_mcp] 事件 <名>: 1=… | 2=…; 选第 N 项(理由)`;没收录时
`事件选项: 1=… | 2=…; 表里没有这个事件, 交给 AALC`,可直接拿来补表。
- 回滚:`LCP_EVENT_CHOICES=0`;表读不了记 `[ERROR]` 并不装补丁。
- 单测执行上游真实的 `event_handling`(`tests/test_event_choices.py`),覆盖按文字、按编号、编号超出、规则顺序、
第二屏交回上游、点击没生效时重试、未收录与上游一致。
- **待实机确认**:事件名是否出现在选项画面上(不出现则规则永远不命中,只会退回上游,不会点错);
选项文字与左边缘同一行的假设(`EVENT_OPTION_ROW`)。
--- ---
## P1-5 选队补丁的鲁棒性 ## P1-5 选队补丁的鲁棒性
+171
View File
@@ -970,3 +970,174 @@ def install_gift_preference(log=print, env=None):
mirror_mod.Mirror.acquire_ego_gift = acquire_ego_gift mirror_mod.Mirror.acquire_ego_gift = acquire_ego_gift
log('[lc_mcp] patch: 镜牢饰品选择按体系关键词排序(%s)' % os.path.basename(path)) log('[lc_mcp] patch: 镜牢饰品选择按体系关键词排序(%s)' % os.path.basename(path))
return original return original
# ---------------------------------------------------------------- 事件选项表
# 2026-11-14 核对: Mirror.event_handling() 不认事件, 有 "???"/直接拿饰品/优势判定就选它, 否则点第一个选项。
# 这里在上游每轮挑选项之前(它先找 event/unknown_event.png)插一步: 画面上有选项时整屏 OCR,
# 认出表里的事件就按选项文字(或第几项)点; 没认出、或表里的选项不在画面上, 交给上游原逻辑。
EVENT_CHOICES_ENV = 'LCP_EVENT_CHOICES' # 0 = 关闭; 文件路径 = 用这张表代替默认表
EVENT_CHOICES_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'event_choices.json')
EVENT_OPTION = 'event/select_first_option_assets.png' # 每个选项框的左边缘, 多目标匹配得到每一项
EVENT_HOOK = 'event/unknown_event.png' # 上游每轮挑选项的第一步
EVENT_OPTION_ROW = 60 # 选项文字与选项框左边缘的最大纵向距离(1440 标定; 选项框高约 107)
EVENT_OPTION_LEFT = 20 # 选项文字至多比左边缘再靠左这么多
EVENT_TEXT_CLICKS = 5 # 一次事件里按文字最多点几次
EVENT_INDEX_TRIES = 3 # 按编号点: 只在第一屏选项, 画面没变时最多重试几次
def load_event_choices(path=EVENT_CHOICES_FILE):
"""读事件表, 返回 [{'name', 'match', 'text', 'index'}]; 格式不对抛 ValueError。"""
with open(path, encoding='utf-8') as f:
raw = json.load(f)
events = raw.get('events') if isinstance(raw, dict) else None
if not isinstance(events, list):
raise ValueError('顶层应是 {"events": [...]}')
def words(item, key):
value = item.get(key, [])
if not isinstance(value, list) or not all(isinstance(w, str) for w in value):
raise ValueError('%s 的 %s 应是字符串列表' % (item.get('name', '?'), key))
return tuple(normalize_team_name(w) for w in value if normalize_team_name(w))
rules = []
for item in events:
if not isinstance(item, dict):
raise ValueError('events 的每一项应是对象')
name = str(item.get('name') or '?')
index = item.get('index')
if index is not None and (isinstance(index, bool) or not isinstance(index, int) or index < 1):
raise ValueError('%s 的 index 应是 >= 1 的整数' % name)
rule = {'name': name, 'match': words(item, 'match'), 'text': words(item, 'text'), 'index': index}
if not rule['match']:
raise ValueError('%s 缺少 match' % name)
if not rule['text'] and index is None:
raise ValueError('%s 至少要有 text 或 index' % name)
rules.append(rule)
return rules
def event_options(markers, lines, scale):
"""选项框左边缘(从上到下)与各自的文字: [(位置, 归一后的文字), ...]。"""
markers = sorted(markers, key=lambda m: float(m[1]))
texts = [[] for _ in markers]
for text, x, y in lines:
rows = [i for i, m in enumerate(markers)
if x >= float(m[0]) - EVENT_OPTION_LEFT * scale and abs(y - float(m[1])) <= EVENT_OPTION_ROW * scale]
if rows:
texts[min(rows, key=lambda i: abs(y - float(markers[i][1])))].append(normalize_team_name(text))
return [(m, ''.join(t)) for m, t in zip(markers, texts)]
def match_event_rule(rules, lines):
"""画面上的文字命中的第一条规则; 没有返回 None。"""
screen = [normalize_team_name(text) for text, _, _ in lines]
for rule in rules:
if any(word in text for word in rule['match'] for text in screen):
return rule
return None
def choose_event_option(rule, texts):
"""返回 (第几项(0 起), 'text'|'index', 理由); 选不出返回 (None, None, 理由)。"""
for word in rule['text']:
for i, text in enumerate(texts):
if word in text:
return i, 'text', '选项文字含「%s」' % word
if rule['index'] is not None:
if rule['index'] <= len(texts):
return rule['index'] - 1, 'index', '按表选第 %d 项' % rule['index']
return None, None, '表里是第 %d 项, 画面上只有 %d 项' % (rule['index'], len(texts))
return None, None, '表里的选项文字不在画面上'
def install_event_choices(log=print, env=None):
"""镜牢事件按表选项。返回原 Mirror.event_handling, 未安装返回 None。"""
env = os.environ if env is None else env
setting = (env.get(EVENT_CHOICES_ENV) or '').strip()
if setting == '0':
log('[lc_mcp] 事件选项表已关闭(%s=0), 沿用 AALC 原逻辑' % EVENT_CHOICES_ENV)
return None
path = setting or EVENT_CHOICES_FILE
try:
rules = load_event_choices(path)
except (OSError, ValueError) as e:
log('[ERROR] [lc_mcp] 事件选项表补丁跳过: %s 读不了(%s: %s)' % (path, type(e).__name__, e))
return None
try:
from tasks.mirror import mirror as mirror_mod
from module.automation import auto
from module.config import cfg
except Exception as e:
log('[lc_mcp] 事件选项表补丁跳过: 无法导入 %s' % e)
return None
original = getattr(getattr(mirror_mod, 'Mirror', None), 'event_handling', None)
if original is None:
log('[lc_mcp] 事件选项表补丁跳过: 上游没有 Mirror.event_handling')
return None
def decide(state):
"""按表点了一个选项返回 True; 其余情况返回 False 交给上游。"""
markers = auto.find_element(EVENT_OPTION, find_type='image_with_multiple_targets', threshold=0.75)
if not markers:
return False
lines = _ocr_lines(auto)
options = event_options(markers, lines, cfg.set_win_size / 1440)
texts = tuple(text for _, text in options)
state['rule'] = state['rule'] or match_event_rule(rules, lines)
rule = state['rule']
shown = ' | '.join('%d=%s' % (i + 1, text or '?') for i, text in enumerate(texts))
def once(message):
if (texts, message) not in state['logged']:
state['logged'].add((texts, message))
log(message)
if rule is None:
once('[lc_mcp] 事件选项: %s; 表里没有这个事件, 交给 AALC' % shown)
return False
i, how, reason = choose_event_option(rule, texts)
if how == 'text' and state['text_clicks'] >= EVENT_TEXT_CLICKS:
how, reason = None, '按文字已点 %d 次' % EVENT_TEXT_CLICKS
if how == 'index' and (state['signature'] not in (None, texts) or state['index_tries'] >= EVENT_INDEX_TRIES):
how, reason = None, '编号只用于第一屏选项'
if how is None:
once('[lc_mcp] 事件 %s: %s; %s, 交给 AALC' % (rule['name'], shown, reason))
return False
if how == 'text':
state['text_clicks'] += 1
else:
state['index_tries'] += 1
state['signature'] = texts
log('[lc_mcp] 事件 %s: %s; 选第 %d 项(%s)' % (rule['name'], shown, i + 1, reason))
position = options[i][0]
auto.mouse_click(position[0], position[1])
return True
def event_handling(self, *args, **kwargs):
state = {'rule': None, 'signature': None, 'index_tries': 0, 'text_clicks': 0, 'logged': set()}
real = auto.click_element
own = vars(auto).get('click_element')
def click_element(target, *a, **kw):
if target == EVENT_HOOK:
try:
if decide(state):
return True # 上游当作点到了选项: event_chance -= 1, 重新截图
except Exception as e:
log('[lc_mcp] 事件选项表出错(%s: %s), 交给 AALC' % (type(e).__name__, e))
return real(target, *a, **kw)
auto.click_element = click_element
try:
return original(self, *args, **kwargs)
finally:
if own is None:
vars(auto).pop('click_element', None)
else:
auto.click_element = own
mirror_mod.Mirror.event_handling = event_handling
log('[lc_mcp] patch: 镜牢事件按选项表选择(%s, %d 条)' % (os.path.basename(path), len(rules)))
return original
+2 -1
View File
@@ -12,7 +12,7 @@ import sys
from . import killswitch, preflight from . import killswitch, preflight
from .aalc_engine import bootstrap from .aalc_engine import bootstrap
from .aalc_patches import (WindowGuard, driver_click_tasks, headless_hdr_warning, from .aalc_patches import (WindowGuard, driver_click_tasks, headless_hdr_warning,
install_default_battle_team, install_exact_team_match, install_default_battle_team, install_event_choices, install_exact_team_match,
install_gift_preference, install_robust_set_foreground, install_shop_lists, install_gift_preference, install_robust_set_foreground, install_shop_lists,
install_system_team_selection, install_typed_keyboard_road, install_system_team_selection, install_typed_keyboard_road,
mirror_progress, stop_driver_click) mirror_progress, stop_driver_click)
@@ -131,6 +131,7 @@ def _run(task, params):
install_shop_lists(log=log) install_shop_lists(log=log)
install_typed_keyboard_road(log=log) install_typed_keyboard_road(log=log)
install_gift_preference(log=log) install_gift_preference(log=log)
install_event_choices(log=log)
guard = WindowGuard(screen, cfg, log=log) guard = WindowGuard(screen, cfg, log=log)
guard.start() guard.start()
restore_path = os.environ.get(RESTORE_ENV) restore_path = os.environ.get(RESTORE_ENV)
+23
View File
@@ -0,0 +1,23 @@
{
"_说明": [
"镜牢事件选项表(BACKLOG P1-4)。只在事件出现选项时生效; 没收录的事件、或表里的选项不在画面上时, 交给 AALC 原逻辑。",
"match: 画面上任一行文字包含其中一个词就认定是这个事件(按表顺序, 先命中的规则生效, 所以 '折射的往昔的睡袋' 要排在 '往昔的睡袋' 前面)。",
"text: 按选项文字选, 优先于 index; 推荐用, 因为 Wiki 编号和当前游戏顺序可能不同。",
"index: 按从上往下第几项选(1 起), 只用于事件的第一屏选项; 后续分支交给 AALC。",
"文字都先做与选队相同的归一(去空白、全角转半角、改回常见误读)。整表关闭: 任务环境变量 LCP_EVENT_CHOICES=0。",
"来源: docs/skills/limbus-mirror-speedrun/references/event-choices.md(2026-10-01 按 Wiki 核对), 都是无判定/无战斗的直出或免费奖励。",
"事件结果依据边狱公司中文 Wiki 社区「探索事件」(https://limbuscompany.huijiwiki.com/wiki/探索事件), 改编内容按 CC BY-SA 4.0 署名及相同方式共享。"
],
"events": [
{"name": "红色坐像", "match": ["无我入定", "红色坐像"], "text": ["侧耳倾听"]},
{"name": "炸鸡对决", "match": ["炸鸡对决"], "text": ["鸡肉就是鸡肉"]},
{"name": "梦中的电子羊", "match": ["梦中的电子羊"], "text": ["你不是特别的"]},
{"name": "失明巨人递来患者记录", "match": ["失明巨人", "患者记录"], "text": ["什么都没有写"]},
{"name": "鸡群的激情探戈", "match": ["激情探戈"], "index": 2},
{"name": "折射的往昔的睡袋", "match": ["折射的往昔的睡袋"], "index": 1},
{"name": "往昔的睡袋", "match": ["往昔的睡袋"], "index": 2},
{"name": "浸染棉花", "match": ["浸染棉花"], "index": 3},
{"name": "破碎罗盘", "match": ["破碎罗盘"], "index": 4},
{"name": "终末日历", "match": ["终末日历"], "index": 2}
]
}
+288
View File
@@ -0,0 +1,288 @@
# -*- coding: utf-8 -*-
"""镜牢事件按选项表选择(BACKLOG P1-4)。
2026-11-14 核对: Mirror.event_handling() 不认事件, 最后总是点第一个选项。补丁在上游每轮挑选项前
认事件、按表点; 端到端用例执行上游真实的 event_handling。
"""
import ast
import json
import os
import sys
import tempfile
import time
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
MIRROR = REPO / 'vendor' / 'aalc' / 'tasks' / 'mirror' / 'mirror.py'
SCALE = 720 / 1440
MARKER_X = 699 # 选项框左边缘(1280x720, 由 2560 模板换算)
ROW_GAP = 60
def markers(count):
return [(MARKER_X, 200 + ROW_GAP * i) for i in range(count)]
def rule(name='e', match=('事件名',), text=(), index=None):
return {'name': name, 'match': tuple(match), 'text': tuple(text), 'index': index}
class EventOptionsTest(unittest.TestCase):
def test_lines_attach_to_the_nearest_option_on_the_right(self):
lines = [('你是特别的', 900, 200),
('你不是', 900, 255), ('特别的。', 1000, 265), # 一项换成两行
('离开', 900, 322),
('侧耳倾听', 300, 260), # 左边的叙述文字不算选项
('梦中的电子羊', 200, 60)] # 标题
options = ap.event_options(list(reversed(markers(3))), lines, SCALE)
self.assertEqual([text for _, text in options], ['你是特别的', '你不是特别的。', '离开'])
self.assertEqual([pos for pos, _ in options], markers(3))
def test_text_far_below_the_last_option_is_ignored(self):
options = ap.event_options(markers(1), [('继续', 900, 200 + 31)], SCALE)
self.assertEqual(options[0][1], '')
def test_first_matching_rule_wins(self):
rules = [rule('折射', ('折射的往昔的睡袋',), index=1), rule('睡袋', ('往昔的睡袋',), index=2)]
self.assertEqual(ap.match_event_rule(rules, [('折射的往昔的睡袋', 200, 60)])['name'], '折射')
self.assertEqual(ap.match_event_rule(rules, [('往昔的 睡袋', 200, 60)])['name'], '睡袋')
self.assertIsNone(ap.match_event_rule(rules, [('别的事件', 200, 60)]))
def test_text_beats_index(self):
self.assertEqual(ap.choose_event_option(rule(text=('不是特别',), index=1), ('是特别', '不是特别的')),
(1, 'text', '选项文字含「不是特别」'))
self.assertEqual(ap.choose_event_option(rule(text=('没有',), index=2), ('a', 'b'))[:2], (1, 'index'))
self.assertEqual(ap.choose_event_option(rule(index=4), ('a', 'b', 'c')),
(None, None, '表里是第 4 项, 画面上只有 3 项'))
self.assertEqual(ap.choose_event_option(rule(text=('没有',)), ('a',))[:2], (None, None))
class EventTableTest(unittest.TestCase):
def test_shipped_table_is_valid_and_has_at_least_five_events(self):
rules = ap.load_event_choices()
self.assertGreaterEqual(len(rules), 5)
names = [r['name'] for r in rules]
self.assertLess(names.index('折射的往昔的睡袋'), names.index('往昔的睡袋'))
def test_shipped_events_come_from_the_event_reference(self):
reference = (REPO / 'docs/skills/limbus-mirror-speedrun/references/event-choices.md').read_text(encoding='utf-8')
for r in ap.load_event_choices():
with self.subTest(event=r['name']):
self.assertTrue(any(word in reference for word in r['match']))
def test_bad_tables_raise_value_error(self):
bad = ['[]', '{"events": {}}', '{"events": [1]}',
'{"events": [{"name": "a", "match": ["x"]}]}',
'{"events": [{"name": "a", "match": [], "index": 1}]}',
'{"events": [{"name": "a", "match": ["x"], "index": 0}]}',
'{"events": [{"name": "a", "match": ["x"], "index": true}]}',
'{"events": [{"name": "a", "match": "x", "index": 1}]}']
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, 'e.json')
for content in bad:
with self.subTest(content=content):
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
with self.assertRaises(ValueError):
ap.load_event_choices(path)
class EventScreen:
"""事件界面: 依次几屏选项, 点了一项就进下一屏, 最后回到地图。"""
def __init__(self, title, screens, ignore_clicks=0):
self.title = title
self.screens = [list(s) for s in screens]
self.stage = 0
self.ignore_clicks = ignore_clicks
self.chosen = []
self.model = None
self.screenshot = object()
@property
def options(self):
return self.screens[self.stage] if self.stage < len(self.screens) else None
def take_screenshot(self):
return self.screenshot
def mouse_to_blank(self, *args, **kwargs):
pass
def find_element(self, target, find_type='image', threshold=0.8, **kwargs):
options = self.options
if target == 'mirror/road_in_mir/legend_assets.png':
return options is None
if target == ap.EVENT_OPTION and options:
return markers(len(options)) if find_type == 'image_with_multiple_targets' else markers(1)[0]
if target == 'event/choices_assets.png':
return bool(options)
return [] if find_type == 'image_with_multiple_targets' else False
def click_element(self, target, **kwargs):
if target == ap.EVENT_OPTION and self.options:
self.mouse_click(*markers(1)[0])
return True
return False
def mouse_click(self, x, y):
if not self.options:
return
self.chosen.append(markers(len(self.options)).index((x, y)))
if self.ignore_clicks:
self.ignore_clicks -= 1
return
self.stage += 1
def find_language_text(self, *args, **kwargs):
return False
def find_text_element(self, *args, **kwargs):
return False
def run(self, image):
lines = [(self.title, 200, 60)]
for (x, y), text in zip(markers(len(self.options or ())), self.options or ()):
lines.append((text, x + 200, y))
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])
@unittest.skipUnless(MIRROR.is_file(), 'vendor/aalc 子模块未检出')
class UpstreamEventHandlingTest(unittest.TestCase):
"""执行上游真实的 Mirror.event_handling, 看每屏点了第几项。"""
def setUp(self):
self.lines = []
tree = ast.parse(MIRROR.read_text(encoding='utf-8'))
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Mirror')
self.fn_node = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == 'event_handling')
def play(self, title, screens, patched=True, env=None, ignore_clicks=0):
screen = EventScreen(title, screens, ignore_clicks=ignore_clicks)
cfg = SimpleNamespace(set_win_size=720)
ns = dict(auto=screen, retry=lambda: True, log=mock.Mock(), time=time, back_init_menu=mock.Mock(),
ImageUtils=SimpleNamespace(get_bbox=lambda image: (0, 0, 10, 10), load_image=lambda path: None))
exec(compile(ast.Module(body=[self.fn_node], type_ignores=[]), str(MIRROR), 'exec'), ns)
method = ns['event_handling']
ns['event_handling'] = SimpleNamespace(decision_event_handling=lambda: False) # 上游模块同名
mirror_cls = type('Mirror', (), {'event_handling': method})
mirror_mod = types.ModuleType('tasks.mirror.mirror')
mirror_mod.Mirror = mirror_cls
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=screen),
'module.config': SimpleNamespace(cfg=cfg),
'module.ocr': SimpleNamespace(ocr=screen)}
with mock.patch.dict(sys.modules, modules):
if patched:
self.assertIsNotNone(ap.install_event_choices(log=self.lines.append, env=env or {}))
mirror = mirror_cls()
mirror.event_total_time, mirror.event_times = 0, 0
mirror.event_handling()
self.assertEqual(mirror.event_times, 1)
self.assertNotIn('click_element', vars(screen), 'click_element 必须还原')
return screen.chosen
@property
def log(self):
return '\n'.join(self.lines)
def test_option_text_overrides_the_first_option(self):
options = [['你是特别的', '你不是特别的。', '离开']]
self.assertEqual(self.play('梦中的电子羊', options, patched=False), [0])
self.assertEqual(self.play('梦中的电子羊', options), [1])
self.assertIn('事件 梦中的电子羊: 1=你是特别的 | 2=你不是特别的。 | 3=离开; 选第 2 项(选项文字含「你不是特别的」)',
self.log)
def test_unknown_event_behaves_like_upstream(self):
options = [['战斗', '离开']]
self.assertEqual(self.play('没见过的事件', options), self.play('没见过的事件', options, patched=False))
self.assertIn('事件选项: 1=战斗 | 2=离开; 表里没有这个事件, 交给 AALC', self.log)
def test_index_rule(self):
self.assertEqual(self.play('浸染棉花', [['判定', '战斗', '离开']]), [2])
def test_index_beyond_the_options_falls_back(self):
self.assertEqual(self.play('破碎罗盘', [['a', 'b', 'c']]), [0])
self.assertIn('表里是第 4 项, 画面上只有 3 项, 交给 AALC', self.log)
def test_refracted_variant_is_matched_first(self):
self.assertEqual(self.play('折射的往昔的睡袋', [['判定', '全体降理智']]), [0])
self.assertEqual(self.play('往昔的睡袋', [['判定', '恢复']]), [1])
def test_index_only_applies_to_the_first_screen(self):
self.assertEqual(self.play('鸡群的激情探戈', [['判定', '探戈蘸酱'], ['好', '不好']]), [1, 0])
self.assertIn('编号只用于第一屏选项', self.log)
def test_index_click_is_retried_while_the_screen_is_unchanged(self):
self.assertEqual(self.play('终末日历', [['判定', '离开']], ignore_clicks=1), [1, 1])
def test_env_zero_keeps_upstream(self):
self.assertIsNone(ap.install_event_choices(log=self.lines.append, env={ap.EVENT_CHOICES_ENV: '0'}))
class InstallEventChoicesTest(unittest.TestCase):
def setUp(self):
self.lines = []
self.original = mock.Mock(side_effect=RuntimeError('boom'))
self.mirror_cls = type('Mirror', (), {'event_handling': self.original})
mirror_mod = types.ModuleType('tasks.mirror.mirror')
mirror_mod.Mirror = self.mirror_cls
package = types.ModuleType('tasks.mirror')
package.mirror = mirror_mod
self.auto = SimpleNamespace(click_element=mock.Mock(return_value=False))
modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.mirror': mirror_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)
def test_click_element_is_restored_after_an_exception(self):
real = self.auto.click_element
ap.install_event_choices(log=self.lines.append, env={})
with self.assertRaises(RuntimeError):
self.mirror_cls().event_handling()
self.assertIs(self.auto.click_element, real)
def test_unreadable_table_is_an_error(self):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, 'e.json')
with open(path, 'w', encoding='utf-8') as f:
json.dump({'events': [{'name': 'a', 'match': ['x']}]}, f)
self.assertIsNone(ap.install_event_choices(log=self.lines.append, env={ap.EVENT_CHOICES_ENV: path}))
self.assertIs(self.mirror_cls.event_handling, self.original)
self.assertTrue(self.lines[0].startswith('[ERROR] [lc_mcp] 事件选项表补丁跳过'))
def test_decision_error_falls_back_to_upstream_click(self):
calls = []
def original(mirror):
calls.append(self.auto.click_element(ap.EVENT_HOOK))
self.mirror_cls.event_handling = original
self.auto.find_element = mock.Mock(side_effect=RuntimeError('template'))
ap.install_event_choices(log=self.lines.append, env={})
self.mirror_cls().event_handling()
self.assertEqual(calls, [False])
self.auto.click_element.assert_called_once_with(ap.EVENT_HOOK)
self.assertIn('事件选项表出错(RuntimeError: template)', '\n'.join(self.lines))
if __name__ == '__main__':
unittest.main()