# -*- coding: utf-8 -*- """镜牢事件按选项表选择(BACKLOG P1-4)。 2026-11-14 核对: Mirror.event_handling() 不认事件, 有 "???"/直接拿饰品/优势判定就选它, 否则点第一个选项。 补丁在上游每轮挑选项前按选项原文认事件、按表点; 端到端用例执行上游真实的 event_handling (以及小指良单通模式用的 click_option_avoiding_unknown)。 """ import ast import functools 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' EVENT = REPO / 'vendor' / 'aalc' / 'tasks' / 'event' / 'event_handling.py' SCALE = 720 / 1440 MARKER_X = 699 # 选项框左边缘(1280x720, 由 2560 模板换算) ROW_GAP = 60 SHEEP = ['你是特别的。', '你不是特别的。'] CHICKEN = ['鸡肉就是鸡肉喽。', '绝对是鸡腿,满满的汁液。', '鸡胸,肯定的,纯净无瑕。'] STATUE = ['侧耳倾听。', '摘下黄铜戒指。', '放上钱币。'] def markers(count): return [(MARKER_X, 200 + ROW_GAP * i) for i in range(count)] def rule(name='e', options=('别的选项',), text='要点的'): return {'name': name, 'id': None, 'options': tuple(options), 'text': text} def upstream_function(path, name, cls=None): tree = ast.parse(path.read_text(encoding='utf-8')) body = tree.body if cls: body = next(n for n in body if isinstance(n, ast.ClassDef) and n.name == cls).body return next(n for n in body if isinstance(n, ast.FunctionDef) and n.name == name) class NormalizeEventTextTest(unittest.TestCase): def test_punctuation_width_and_spaces_are_ignored(self): self.assertEqual(ap.normalize_event_text('鸡胸,肯定的, 纯净 无瑕。'), '鸡胸肯定的纯净无瑕') self.assertEqual(ap.normalize_event_text('“我不特别吗?”'), '我不特别吗') self.assertEqual(ap.normalize_event_text('施加震颐'), '施加震颤') 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], '') class ChooseEventOptionTest(unittest.TestCase): def test_event_is_recognised_by_its_other_options(self): rules = [rule('羊', ['你是特别的'], '你不是特别的')] self.assertEqual(ap.choose_event_option(rules, ('你是特别的', '你不是特别的')), (rules[0], 1)) self.assertEqual(ap.choose_event_option(rules, ('你不是特别的', '离开')), (None, None)) def test_all_listed_options_must_be_on_screen(self): rules = [rule('鸡', ['绝对是鸡腿', '鸡胸肯定的'], '鸡肉就是鸡肉喽')] self.assertEqual(ap.choose_event_option(rules, ('鸡肉就是鸡肉喽', '绝对是鸡腿满满的汁液')), (None, None)) def test_recognised_but_target_not_read(self): rules = [rule('鸡', ['绝对是鸡腿'], '鸡肉就是鸡肉喽')] self.assertEqual(ap.choose_event_option(rules, ('鸡肉就是鸡', '绝对是鸡腿')), (rules[0], None)) def test_first_matching_rule_wins(self): rules = [rule('a', ['离开'], '战斗'), rule('b', ['离开'], '交谈')] self.assertEqual(ap.choose_event_option(rules, ('交谈', '战斗', '离开')), (rules[0], 1)) class EventTableTest(unittest.TestCase): def test_shipped_table_is_valid(self): rules = ap.load_event_choices() self.assertGreaterEqual(len(rules), 5) for r in rules: with self.subTest(event=r['name']): self.assertIsInstance(r['id'], int) # 零协汉化 ActionEvents 的事件 id, 方便回查 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.assertIn(r['name'].split('(')[0], reference) def test_each_shipped_event_picks_its_own_option(self): rules = ap.load_event_choices() for r in rules: with self.subTest(event=r['name']): screen = (r['text'],) + r['options'] self.assertEqual(ap.choose_event_option(rules, screen), (r, 0)) def test_bad_tables_raise_value_error(self): bad = ['[]', '{"events": {}}', '{"events": [1]}', '{"events": [{"name": "a", "options": ["x"]}]}', '{"events": [{"name": "a", "options": [], "text": "y"}]}', '{"events": [{"name": "a", "options": "x", "text": "y"}]}', '{"events": [{"name": "a", "options": ["x"], "text": ["y"]}]}', '{"events": [{"name": "a", "options": ["。"], "text": "y"}]}', '{"events": [{"name": "a", "options": ["离开"], "text": "离开。"}]}', '{"events": [{"name": "a", "match": ["x"], "index": 2}]}'] 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: """事件界面: 依次几屏选项, 点了一项就进下一屏, 最后回到地图。unknown 是带 "???" 标签的那一项。""" def __init__(self, screens, unknown=None, ignore_clicks=0): self.screens = [list(s) for s in screens] self.unknown = unknown 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, *args, **kwargs): 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 == ap.EVENT_HOOK and options and self.stage == 0 and self.unknown is not None: x, y = markers(len(options))[self.unknown] return (x + 300, y + 20) # 标签画在所属选项框里面, 比左边缘靠下 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, *args, **kwargs): if not self.options: return rows = markers(len(self.options)) above = [i for i, (_, my) in enumerate(rows) if my <= y] self.chosen.append(max(above) if above else 0) 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 = [('事件叙述文字', 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() and EVENT.is_file(), 'vendor/aalc 子模块未检出') class UpstreamEventHandlingTest(unittest.TestCase): """执行上游真实的 Mirror.event_handling, 看每屏点了第几项。""" def setUp(self): self.lines = [] self.fn_node = upstream_function(MIRROR, 'event_handling', cls='Mirror') self.avoid_node = upstream_function(EVENT, 'click_option_avoiding_unknown', cls='EventHandling') def play(self, screens, patched=True, env=None, unknown=None, solo=False, ignore_clicks=0): screen = EventScreen(screens, unknown=unknown, ignore_clicks=ignore_clicks) cfg = SimpleNamespace(set_win_size=720) avoid_ns = dict(auto=screen, log=mock.Mock()) exec(compile(ast.Module(body=[self.avoid_node], type_ignores=[]), str(EVENT), 'exec'), avoid_ns) 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( # 上游模块 tasks.event.event_handling 的同名单例 decision_event_handling=lambda: False, click_option_avoiding_unknown=functools.partial(avoid_ns['click_option_avoiding_unknown'], None)) 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.defense_for_solo = solo mirror.event_handling() self.assertEqual(mirror.event_times, 1) self.assertNotIn('find_element', vars(screen), 'find_element 必须还原') self.assertNotIn('mouse_click', vars(screen), 'mouse_click 必须还原') return screen.chosen @property def log(self): return '\n'.join(self.lines) def test_patch_hooks_into_the_current_upstream(self): self.play([SHEEP]) self.assertIn('patch: 镜牢事件按选项表选择', self.log) self.assertNotIn('[ERROR]', self.log) def test_table_choice_is_clicked_exactly_once(self): self.assertEqual(self.play([SHEEP], patched=False), [0]) self.assertEqual(self.play([SHEEP]), [1]) # 上游拿返回的位置再点一次会被吞掉 self.assertIn('事件 梦中的电子羊: 1=你是特别的 | 2=你不是特别的; 按表选第 2 项「你不是特别的」', self.log) def test_table_beats_the_unknown_tag(self): # 上游有 "???" 就点 "???"; 表里的事件按表点 self.assertEqual(self.play([CHICKEN[::-1]], unknown=0, patched=False), [0]) self.assertEqual(self.play([CHICKEN[::-1]], unknown=0), [2]) def test_solo_mode_does_not_click_a_second_option(self): # 小指良单通模式会再找一次 "???" 并改点别的选项; 已按表点过时它必须什么也不做 self.assertEqual(self.play([STATUE], unknown=0, solo=True, patched=False), [1]) self.assertEqual(self.play([STATUE], unknown=0, solo=True), [0]) def test_unknown_event_behaves_like_upstream(self): for kwargs in ({}, {'unknown': 1}, {'unknown': 1, 'solo': True}): with self.subTest(**kwargs): options = [['战斗', '离开']] self.assertEqual(self.play(options, **kwargs), self.play(options, patched=False, **kwargs)) self.assertIn('事件选项: 1=战斗 | 2=离开; 表里没有这个事件, 交给 AALC', self.log) def test_misread_target_falls_back_to_upstream(self): options = [['鸡肉就是鸡', CHICKEN[1], CHICKEN[2]]] self.assertEqual(self.play(options), [0]) self.assertIn('表里要点的「鸡肉就是鸡肉喽」没读到, 交给 AALC', self.log) def test_later_screens_not_in_the_table_go_to_upstream(self): self.assertEqual(self.play([CHICKEN[::-1], ['好', '不好']]), [2, 0]) def test_unresponsive_clicks_are_capped(self): chosen = self.play([SHEEP], ignore_clicks=ap.EVENT_TEXT_CLICKS + 1) self.assertEqual(chosen[:ap.EVENT_TEXT_CLICKS + 1], [1] * ap.EVENT_TEXT_CLICKS + [0]) self.assertIn('这次事件已按表点了 %d 次, 交给 AALC' % ap.EVENT_TEXT_CLICKS, self.log) def test_decisions_are_recorded_once_per_screen(self): with mock.patch.object(ap.decisions, 'record') as record: self.play([SHEEP]) self.play([['战斗', '离开']]) self.assertEqual(record.call_args_list, [ mock.call('event', 2, 'text', event='梦中的电子羊', event_id=901038, options=['你是特别的', '你不是特别的']), mock.call('event', None, 'not_in_table', options=['战斗', '离开'])]) 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(find_element=mock.Mock(return_value=False), mouse_click=mock.Mock()) 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_methods_are_restored_after_an_exception(self): find, click = self.auto.find_element, self.auto.mouse_click ap.install_event_choices(log=self.lines.append, env={}) with self.assertRaises(RuntimeError): self.mirror_cls().event_handling() self.assertIs(self.auto.find_element, find) self.assertIs(self.auto.mouse_click, click) 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'], 'index': 1}]}, 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_upstream_without_the_hook_is_an_error(self): auto = self.auto def event_handling(mirror): return auto.click_element("event/unknown_event.png") # 旧写法: 补丁挂不上 self.mirror_cls.event_handling = event_handling self.assertIsNone(ap.install_event_choices(log=self.lines.append, env={})) self.assertIs(self.mirror_cls.event_handling, event_handling) self.assertIn('[ERROR] [lc_mcp] 事件选项表补丁跳过: 上游 Mirror.event_handling 不再调用 find_element', '\n'.join(self.lines)) def test_decision_error_falls_back_to_upstream_find(self): calls = [] auto = self.auto def find(target, *args, **kwargs): if target == ap.EVENT_OPTION: raise RuntimeError('template') return False def event_handling(mirror): calls.append(auto.find_element("event/unknown_event.png")) self.auto.find_element = mock.Mock(side_effect=find) self.mirror_cls.event_handling = event_handling ap.install_event_choices(log=self.lines.append, env={}) self.mirror_cls().event_handling() self.assertEqual(calls, [False]) self.assertEqual(self.auto.find_element.call_args_list[-1], mock.call(ap.EVENT_HOOK)) self.assertIn('事件选项表出错(RuntimeError: template)', '\n'.join(self.lines)) if __name__ == '__main__': unittest.main()