AALC 升级到 V1.6.1 并按零协汉化核对镜牢补丁

Browse Source
- vendor/aalc: e1d1749 -> 2fcb1b4(V1.6.1)。上游 8196e72 修好了商店三个清单的
  路径, 删掉本地 install_shop_lists, test_shop_lists 改成守着上游 5/19/31。
- 上游 18deb77 把事件里找 "???" 改成 find_element 后自己点, 原事件表补丁挂在
  click_element 上会悄悄失效。改挂 find_element, 上游拿返回位置再点的那下吞掉;
  小指良单通模式再找 "???" 时返回没有, 不会改点别的选项。
- 事件表改成按同一屏其它选项的原文认事件(零协汉化的事件数据没有标题), 选项原文
  照抄 LLC_zh-CN/ActionEvents_*.json 并带事件 id; 去掉 index 规则。核对后保留
  6 条, 删掉汉化里对不上或说法矛盾的 4 条(两个睡袋、浸染棉花、终末日历); 失明巨人
  是判定, 标 check。选项比较前去标点。
- 饰品关键词按零协汉化体系名核对, 删掉汉化里从未出现的 出血。
- 事件表、饰品排序安装时检查上游源码里还有被拦截的调用, 没有就记 [ERROR] 跳过;
  包装函数带 __wrapped__, 叠装时也能查到上游源码。
- BACKLOG 记录这次升级对各补丁的影响和核对结果。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-11-14 08:43:27 +00:00
co-authored by Claude Opus 5.5
parent 51525722cd
commit 72d2ca1a5b
10 changed files with 410 additions and 345 deletions
+162 -85
View File
@@ -1,10 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""镜牢事件按选项表选择(BACKLOG P1-4)。 """镜牢事件按选项表选择(BACKLOG P1-4)。
2026-11-14 核对: Mirror.event_handling() 不认事件, 最后总是点第一个选项。补丁在上游每轮挑选项前 2026-11-14 核对: Mirror.event_handling() 不认事件, 有 "???"/直接拿饰品/优势判定就选它, 否则点第一个选项。
认事件、按表点; 端到端用例执行上游真实的 event_handling。 补丁在上游每轮挑选项前按选项原文认事件、按表点; 端到端用例执行上游真实的 event_handling
(以及小指良单通模式用的 click_option_avoiding_unknown)。
""" """
import ast import ast
import functools
import json import json
import os import os
import sys import sys
@@ -21,17 +23,38 @@ sys.path.insert(0, str(REPO))
from lc_mcp import aalc_patches as ap # noqa: E402 from lc_mcp import aalc_patches as ap # noqa: E402
MIRROR = REPO / 'vendor' / 'aalc' / 'tasks' / 'mirror' / 'mirror.py' MIRROR = REPO / 'vendor' / 'aalc' / 'tasks' / 'mirror' / 'mirror.py'
EVENT = REPO / 'vendor' / 'aalc' / 'tasks' / 'event' / 'event_handling.py'
SCALE = 720 / 1440 SCALE = 720 / 1440
MARKER_X = 699 # 选项框左边缘(1280x720, 由 2560 模板换算) MARKER_X = 699 # 选项框左边缘(1280x720, 由 2560 模板换算)
ROW_GAP = 60 ROW_GAP = 60
SHEEP = ['你是特别的。', '你不是特别的。']
CHICKEN = ['鸡肉就是鸡肉喽。', '绝对是鸡腿,满满的汁液。', '鸡胸,肯定的,纯净无瑕。']
STATUE = ['侧耳倾听。', '摘下黄铜戒指。', '放上钱币。']
def markers(count): def markers(count):
return [(MARKER_X, 200 + ROW_GAP * i) for i in range(count)] return [(MARKER_X, 200 + ROW_GAP * i) for i in range(count)]
def rule(name='e', match=('事件名',), text=(), index=None): def rule(name='e', options=('别的选项',), text='要点的'):
return {'name': name, 'match': tuple(match), 'text': tuple(text), 'index': index} 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): class EventOptionsTest(unittest.TestCase):
@@ -43,49 +66,65 @@ class EventOptionsTest(unittest.TestCase):
('侧耳倾听', 300, 260), # 左边的叙述文字不算选项 ('侧耳倾听', 300, 260), # 左边的叙述文字不算选项
('梦中的电子羊', 200, 60)] # 标题 ('梦中的电子羊', 200, 60)] # 标题
options = ap.event_options(list(reversed(markers(3))), lines, SCALE) options = ap.event_options(list(reversed(markers(3))), lines, SCALE)
self.assertEqual([text for _, text in options], ['你是特别的', '你不是特别的。', '离开']) self.assertEqual([text for _, text in options], ['你是特别的', '你不是特别的', '离开'])
self.assertEqual([pos for pos, _ in options], markers(3)) self.assertEqual([pos for pos, _ in options], markers(3))
def test_text_far_below_the_last_option_is_ignored(self): def test_text_far_below_the_last_option_is_ignored(self):
options = ap.event_options(markers(1), [('继续', 900, 200 + 31)], SCALE) options = ap.event_options(markers(1), [('继续', 900, 200 + 31)], SCALE)
self.assertEqual(options[0][1], '') 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): class ChooseEventOptionTest(unittest.TestCase):
self.assertEqual(ap.choose_event_option(rule(text=('不是特别',), index=1), ('是特别', '不是特别的')),
(1, 'text', '选项文字含「不是特别」')) def test_event_is_recognised_by_its_other_options(self):
self.assertEqual(ap.choose_event_option(rule(text=('没有',), index=2), ('a', 'b'))[:2], (1, 'index')) rules = [rule('羊', ['你是特别的'], '你不是特别的')]
self.assertEqual(ap.choose_event_option(rule(index=4), ('a', 'b', 'c')), self.assertEqual(ap.choose_event_option(rules, ('你是特别的', '你不是特别的')), (rules[0], 1))
(None, None, '表里是第 4 项, 画面上只有 3 项')) self.assertEqual(ap.choose_event_option(rules, ('你不是特别的', '离开')), (None, None))
self.assertEqual(ap.choose_event_option(rule(text=('没有',)), ('a',))[:2], (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): class EventTableTest(unittest.TestCase):
def test_shipped_table_is_valid_and_has_at_least_five_events(self): def test_shipped_table_is_valid(self):
rules = ap.load_event_choices() rules = ap.load_event_choices()
self.assertGreaterEqual(len(rules), 5) self.assertGreaterEqual(len(rules), 5)
names = [r['name'] for r in rules] for r in rules:
self.assertLess(names.index('折射的往昔的睡袋'), names.index('往昔的睡袋')) with self.subTest(event=r['name']):
self.assertIsInstance(r['id'], int) # 零协汉化 ActionEvents 的事件 id, 方便回查
def test_shipped_events_come_from_the_event_reference(self): 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') reference = (REPO / 'docs/skills/limbus-mirror-speedrun/references/event-choices.md').read_text(encoding='utf-8')
for r in ap.load_event_choices(): for r in ap.load_event_choices():
with self.subTest(event=r['name']): with self.subTest(event=r['name']):
self.assertTrue(any(word in reference for word in r['match'])) 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): def test_bad_tables_raise_value_error(self):
bad = ['[]', '{"events": {}}', '{"events": [1]}', bad = ['[]', '{"events": {}}', '{"events": [1]}',
'{"events": [{"name": "a", "match": ["x"]}]}', '{"events": [{"name": "a", "options": ["x"]}]}',
'{"events": [{"name": "a", "match": [], "index": 1}]}', '{"events": [{"name": "a", "options": [], "text": "y"}]}',
'{"events": [{"name": "a", "match": ["x"], "index": 0}]}', '{"events": [{"name": "a", "options": "x", "text": "y"}]}',
'{"events": [{"name": "a", "match": ["x"], "index": true}]}', '{"events": [{"name": "a", "options": ["x"], "text": ["y"]}]}',
'{"events": [{"name": "a", "match": "x", "index": 1}]}'] '{"events": [{"name": "a", "options": ["。"], "text": "y"}]}',
'{"events": [{"name": "a", "options": ["离开"], "text": "离开。"}]}',
'{"events": [{"name": "a", "match": ["x"], "index": 2}]}']
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, 'e.json') path = os.path.join(tmp, 'e.json')
for content in bad: for content in bad:
@@ -97,11 +136,11 @@ class EventTableTest(unittest.TestCase):
class EventScreen: class EventScreen:
"""事件界面: 依次几屏选项, 点了一项就进下一屏, 最后回到地图。""" """事件界面: 依次几屏选项, 点了一项就进下一屏, 最后回到地图。unknown 是带 "???" 标签的那一项。"""
def __init__(self, title, screens, ignore_clicks=0): def __init__(self, screens, unknown=None, ignore_clicks=0):
self.title = title
self.screens = [list(s) for s in screens] self.screens = [list(s) for s in screens]
self.unknown = unknown
self.stage = 0 self.stage = 0
self.ignore_clicks = ignore_clicks self.ignore_clicks = ignore_clicks
self.chosen = [] self.chosen = []
@@ -112,7 +151,7 @@ class EventScreen:
def options(self): def options(self):
return self.screens[self.stage] if self.stage < len(self.screens) else None return self.screens[self.stage] if self.stage < len(self.screens) else None
def take_screenshot(self): def take_screenshot(self, *args, **kwargs):
return self.screenshot return self.screenshot
def mouse_to_blank(self, *args, **kwargs): def mouse_to_blank(self, *args, **kwargs):
@@ -124,6 +163,9 @@ class EventScreen:
return options is None return options is None
if target == ap.EVENT_OPTION and options: if target == ap.EVENT_OPTION and options:
return markers(len(options)) if find_type == 'image_with_multiple_targets' else markers(1)[0] 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': if target == 'event/choices_assets.png':
return bool(options) return bool(options)
return [] if find_type == 'image_with_multiple_targets' else False return [] if find_type == 'image_with_multiple_targets' else False
@@ -134,10 +176,12 @@ class EventScreen:
return True return True
return False return False
def mouse_click(self, x, y): def mouse_click(self, x, y, *args, **kwargs):
if not self.options: if not self.options:
return return
self.chosen.append(markers(len(self.options)).index((x, y))) 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: if self.ignore_clicks:
self.ignore_clicks -= 1 self.ignore_clicks -= 1
return return
@@ -150,7 +194,7 @@ class EventScreen:
return False return False
def run(self, image): def run(self, image):
lines = [(self.title, 200, 60)] lines = [('事件叙述文字', 200, 60)]
for (x, y), text in zip(markers(len(self.options or ())), self.options or ()): for (x, y), text in zip(markers(len(self.options or ())), self.options or ()):
lines.append((text, x + 200, y)) lines.append((text, x + 200, y))
return SimpleNamespace(txts=tuple(t for t, _, _ in lines), return SimpleNamespace(txts=tuple(t for t, _, _ in lines),
@@ -158,24 +202,27 @@ class EventScreen:
for _, x, y in lines]) for _, x, y in lines])
@unittest.skipUnless(MIRROR.is_file(), 'vendor/aalc 子模块未检出') @unittest.skipUnless(MIRROR.is_file() and EVENT.is_file(), 'vendor/aalc 子模块未检出')
class UpstreamEventHandlingTest(unittest.TestCase): class UpstreamEventHandlingTest(unittest.TestCase):
"""执行上游真实的 Mirror.event_handling, 看每屏点了第几项。""" """执行上游真实的 Mirror.event_handling, 看每屏点了第几项。"""
def setUp(self): def setUp(self):
self.lines = [] self.lines = []
tree = ast.parse(MIRROR.read_text(encoding='utf-8')) self.fn_node = upstream_function(MIRROR, 'event_handling', cls='Mirror')
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Mirror') self.avoid_node = upstream_function(EVENT, 'click_option_avoiding_unknown', cls='EventHandling')
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): def play(self, screens, patched=True, env=None, unknown=None, solo=False, ignore_clicks=0):
screen = EventScreen(title, screens, ignore_clicks=ignore_clicks) screen = EventScreen(screens, unknown=unknown, ignore_clicks=ignore_clicks)
cfg = SimpleNamespace(set_win_size=720) 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(), 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)) 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) exec(compile(ast.Module(body=[self.fn_node], type_ignores=[]), str(MIRROR), 'exec'), ns)
method = ns['event_handling'] method = ns['event_handling']
ns['event_handling'] = SimpleNamespace(decision_event_handling=lambda: False) # 上游模块同名 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_cls = type('Mirror', (), {'event_handling': method})
mirror_mod = types.ModuleType('tasks.mirror.mirror') mirror_mod = types.ModuleType('tasks.mirror.mirror')
mirror_mod.Mirror = mirror_cls mirror_mod.Mirror = mirror_cls
@@ -191,54 +238,65 @@ class UpstreamEventHandlingTest(unittest.TestCase):
self.assertIsNotNone(ap.install_event_choices(log=self.lines.append, env=env or {})) self.assertIsNotNone(ap.install_event_choices(log=self.lines.append, env=env or {}))
mirror = mirror_cls() mirror = mirror_cls()
mirror.event_total_time, mirror.event_times = 0, 0 mirror.event_total_time, mirror.event_times = 0, 0
mirror.defense_for_solo = solo
mirror.event_handling() mirror.event_handling()
self.assertEqual(mirror.event_times, 1) self.assertEqual(mirror.event_times, 1)
self.assertNotIn('click_element', vars(screen), 'click_element 必须还原') self.assertNotIn('find_element', vars(screen), 'find_element 必须还原')
self.assertNotIn('mouse_click', vars(screen), 'mouse_click 必须还原')
return screen.chosen return screen.chosen
@property @property
def log(self): def log(self):
return '\n'.join(self.lines) return '\n'.join(self.lines)
def test_option_text_overrides_the_first_option(self): def test_patch_hooks_into_the_current_upstream(self):
options = [['你是特别的', '你不是特别的。', '离开']] self.play([SHEEP])
self.assertEqual(self.play('梦中的电子羊', options, patched=False), [0]) self.assertIn('patch: 镜牢事件按选项表选择', self.log)
self.assertEqual(self.play('梦中的电子羊', options), [1]) self.assertNotIn('[ERROR]', self.log)
self.assertIn('事件 梦中的电子羊: 1=你是特别的 | 2=你不是特别的。 | 3=离开; 选第 2 项(选项文字含「你不是特别的」)',
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): def test_decisions_are_recorded_once_per_screen(self):
with mock.patch.object(ap.decisions, 'record') as record: with mock.patch.object(ap.decisions, 'record') as record:
self.play('梦中的电子羊', [['你是特别的', '你不是特别的。']]) self.play([SHEEP])
self.play('没见过的事件', [['战斗', '离开']]) self.play([['战斗', '离开']])
self.assertEqual(record.call_args_list, [ self.assertEqual(record.call_args_list, [
mock.call('event', 2, 'text', event='梦中的电子羊', options=['你是特别的', '你不是特别的。'], mock.call('event', 2, 'text', event='梦中的电子羊', event_id=901038, options=['你是特别的', '你不是特别的']),
why='选项文字含「你不是特别的」'),
mock.call('event', None, 'not_in_table', options=['战斗', '离开'])]) mock.call('event', None, 'not_in_table', options=['战斗', '离开'])])
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): def test_env_zero_keeps_upstream(self):
self.assertIsNone(ap.install_event_choices(log=self.lines.append, env={ap.EVENT_CHOICES_ENV: '0'})) self.assertIsNone(ap.install_event_choices(log=self.lines.append, env={ap.EVENT_CHOICES_ENV: '0'}))
@@ -253,7 +311,7 @@ class InstallEventChoicesTest(unittest.TestCase):
mirror_mod.Mirror = self.mirror_cls mirror_mod.Mirror = self.mirror_cls
package = types.ModuleType('tasks.mirror') package = types.ModuleType('tasks.mirror')
package.mirror = mirror_mod package.mirror = mirror_mod
self.auto = SimpleNamespace(click_element=mock.Mock(return_value=False)) 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, modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.mirror': mirror_mod,
'module': types.ModuleType('module'), 'module': types.ModuleType('module'),
'module.automation': SimpleNamespace(auto=self.auto), 'module.automation': SimpleNamespace(auto=self.auto),
@@ -262,34 +320,53 @@ class InstallEventChoicesTest(unittest.TestCase):
patcher.start() patcher.start()
self.addCleanup(patcher.stop) self.addCleanup(patcher.stop)
def test_click_element_is_restored_after_an_exception(self): def test_methods_are_restored_after_an_exception(self):
real = self.auto.click_element find, click = self.auto.find_element, self.auto.mouse_click
ap.install_event_choices(log=self.lines.append, env={}) ap.install_event_choices(log=self.lines.append, env={})
with self.assertRaises(RuntimeError): with self.assertRaises(RuntimeError):
self.mirror_cls().event_handling() self.mirror_cls().event_handling()
self.assertIs(self.auto.click_element, real) self.assertIs(self.auto.find_element, find)
self.assertIs(self.auto.mouse_click, click)
def test_unreadable_table_is_an_error(self): def test_unreadable_table_is_an_error(self):
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, 'e.json') path = os.path.join(tmp, 'e.json')
with open(path, 'w', encoding='utf-8') as f: with open(path, 'w', encoding='utf-8') as f:
json.dump({'events': [{'name': 'a', 'match': ['x']}]}, 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.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.assertIs(self.mirror_cls.event_handling, self.original)
self.assertTrue(self.lines[0].startswith('[ERROR] [lc_mcp] 事件选项表补丁跳过')) self.assertTrue(self.lines[0].startswith('[ERROR] [lc_mcp] 事件选项表补丁跳过'))
def test_decision_error_falls_back_to_upstream_click(self): 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 = [] calls = []
auto = self.auto
def original(mirror): def find(target, *args, **kwargs):
calls.append(self.auto.click_element(ap.EVENT_HOOK)) if target == ap.EVENT_OPTION:
raise RuntimeError('template')
return False
self.mirror_cls.event_handling = original def event_handling(mirror):
self.auto.find_element = mock.Mock(side_effect=RuntimeError('template')) 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={}) ap.install_event_choices(log=self.lines.append, env={})
self.mirror_cls().event_handling() self.mirror_cls().event_handling()
self.assertEqual(calls, [False]) self.assertEqual(calls, [False])
self.auto.click_element.assert_called_once_with(ap.EVENT_HOOK) self.assertEqual(self.auto.find_element.call_args_list[-1], mock.call(ap.EVENT_HOOK))
self.assertIn('事件选项表出错(RuntimeError: template)', '\n'.join(self.lines)) self.assertIn('事件选项表出错(RuntimeError: template)', '\n'.join(self.lines))
+20 -5
View File
@@ -214,12 +214,12 @@ class UpstreamAcquireEgoGiftTest(unittest.TestCase):
self.assertEqual(self.choose(cards)[0], self.choose(cards, patched=False)[0]) self.assertEqual(self.choose(cards)[0], self.choose(cards, patched=False)[0])
def test_three_cards_pick_one(self): def test_three_cards_pick_one(self):
cards = [card(300, '烧伤'), card(600, '震颤'), card(900, '流血伤害提高', '出血')] cards = [card(300, '烧伤'), card(600, '震颤'), card(900, '流血伤害提高', '施加流血')]
self.assertEqual(self.choose(cards, patched=False)[0], [0]) self.assertEqual(self.choose(cards, patched=False)[0], [0])
self.assertEqual(self.choose(cards)[0], [2]) self.assertEqual(self.choose(cards)[0], [2])
def test_three_cards_pick_two(self): def test_three_cards_pick_two(self):
cards = [card(300, '烧伤'), card(600, '流血'), card(900, '流血', '出血')] cards = [card(300, '烧伤'), card(600, '流血'), card(900, '流血', '施加流血')]
self.assertEqual(self.choose(cards, pick='0/2')[0], [2, 1]) self.assertEqual(self.choose(cards, pick='0/2')[0], [2, 1])
def test_misread_keyword_for_tremor(self): def test_misread_keyword_for_tremor(self):
@@ -233,9 +233,9 @@ class UpstreamAcquireEgoGiftTest(unittest.TestCase):
def test_duplicate_lines_on_two_cards_both_count(self): def test_duplicate_lines_on_two_cards_both_count(self):
# {文本: 坐标} 会把两张卡上的同一句合并成一条; 补丁直接读 OCR 引擎的逐行结果 # {文本: 坐标} 会把两张卡上的同一句合并成一条; 补丁直接读 OCR 引擎的逐行结果
cards = [card(300, '流血'), card(600, '流血', '出血')] cards = [card(300, '流血'), card(600, '流血', '施加流血')]
self.assertEqual(self.choose(cards)[0], [1]) self.assertEqual(self.choose(cards)[0], [1])
self.assertIn('第1张=1(流血) 第2张=2(流血/出血)', self.log) self.assertIn('第1张=1(流血) 第2张=2(流血/流血)', self.log)
def test_decision_is_recorded_left_to_right(self): def test_decision_is_recorded_left_to_right(self):
cards = [card(300, '烧伤层数+1'), card(600, '施加2层流血')] cards = [card(300, '烧伤层数+1'), card(600, '施加2层流血')]
@@ -300,8 +300,11 @@ class InstallGiftPreferenceTest(unittest.TestCase):
def test_ranking_error_keeps_upstream_order(self): def test_ranking_error_keeps_upstream_order(self):
cards = [(300, 300), (600, 300)] cards = [(300, 300), (600, 300)]
auto = self.auto
def original(mirror): def original(mirror):
return self.auto.find_element(ap.GIFT_CARD, find_type='image_with_multiple_targets') return auto.find_element("mirror/road_in_mir/acquire_ego_gift_card.png",
find_type='image_with_multiple_targets')
self.mirror_cls.acquire_ego_gift = original self.mirror_cls.acquire_ego_gift = original
self.install() self.install()
@@ -311,6 +314,18 @@ class InstallGiftPreferenceTest(unittest.TestCase):
self.assertEqual(mirror.acquire_ego_gift(), cards) self.assertEqual(mirror.acquire_ego_gift(), cards)
self.assertIn('关键词排序出错(RuntimeError: ocr down)', '\n'.join(self.lines)) self.assertIn('关键词排序出错(RuntimeError: ocr down)', '\n'.join(self.lines))
def test_upstream_without_the_card_lookup_is_an_error(self):
auto = self.auto
def original(mirror):
return auto.find_element("mirror/road_in_mir/some_other_card.png")
self.mirror_cls.acquire_ego_gift = original
self.install()
self.assertIs(self.mirror_cls.acquire_ego_gift, original)
self.assertIn('[ERROR] [lc_mcp] 饰品体系优先补丁跳过: 上游 Mirror.acquire_ego_gift 不再调用 find_element',
'\n'.join(self.lines))
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
+20 -77
View File
@@ -1,24 +1,21 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""镜牢商店"必买 / 必卖 / 公式合成"清单。 """镜牢商店"必买 / 必卖 / 公式合成"清单(BACKLOG P0-1)。
2026-11-14 实测: 上游 tasks/mirror/__init__.py 仍按 ./assets/images/share/... 列目录, 2026-11-14 实测: 上游 tasks/mirror/__init__.py 按旧路径 ./assets/images/share/... 列目录, 三个清单恒为空,
图片早已挪到 assets/images/<主题>/<语言>/ 下, 三个清单恒为空, 进店 51 秒一件没买。 进店 51 秒一件没买。上游 8196e72(V1.6.1) 改成按 assets/images/default/share/... 列, 本地补丁随之删掉;
这里守着上游别再退回空清单。
""" """
import os import os
import sys
import tempfile
import types import types
import unittest import unittest
from contextlib import contextmanager from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from unittest import mock
REPO = Path(__file__).resolve().parents[1] REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO))
from lc_mcp import aalc_patches # noqa: E402
AALC = REPO / 'vendor' / 'aalc' AALC = REPO / 'vendor' / 'aalc'
IMAGES = AALC / 'assets' / 'images' INIT = AALC / 'tasks' / 'mirror' / '__init__.py'
SHOP_LISTS = ('must_purchase', 'must_be_abandoned', 'fusion_result')
IMAGE_ROOTS = ('dark/zh_cn', 'dark/en', 'dark/share', 'default/zh_cn', 'default/en', 'default/share')
@contextmanager @contextmanager
@@ -31,89 +28,35 @@ def chdir(path):
os.chdir(old) os.chdir(old)
def as_tasks_mirror(package):
"""让 import tasks.mirror 拿到给定模块(父包也要在 sys.modules 里)。"""
parent = types.ModuleType('tasks')
parent.mirror = package
return mock.patch.dict(sys.modules, {'tasks': parent, 'tasks.mirror': package})
def upstream_mirror_package(): def upstream_mirror_package():
"""在 AALC 目录下执行上游 tasks/mirror/__init__.py, 得到它真实生成的三个列表。""" """在 AALC 目录下执行上游 tasks/mirror/__init__.py(任务进程的工作目录也是这里)。"""
module = types.ModuleType('tasks.mirror') module = types.ModuleType('tasks.mirror')
source = (AALC / 'tasks' / 'mirror' / '__init__.py').read_text(encoding='utf-8')
with chdir(AALC): with chdir(AALC):
exec(compile(source, str(AALC / 'tasks' / 'mirror' / '__init__.py'), 'exec'), module.__dict__) exec(compile(INIT.read_text(encoding='utf-8'), str(INIT), 'exec'), module.__dict__)
return module return module
@unittest.skipUnless(IMAGES.is_dir(), 'vendor/aalc 子模块未检出') @unittest.skipUnless(INIT.is_file(), 'vendor/aalc 子模块未检出')
class UpstreamShopListTest(unittest.TestCase): class UpstreamShopListTest(unittest.TestCase):
def test_upstream_lists_are_empty_and_patch_fills_them(self): def test_upstream_lists_are_filled(self):
package = upstream_mirror_package() package = upstream_mirror_package()
self.assertEqual([len(getattr(package, k)) for k in aalc_patches.SHOP_LISTS], [0, 0, 0], self.assertEqual([len(getattr(package, k)) for k in SHOP_LISTS], [5, 19, 31])
'上游已修好时可以删掉这个补丁') self.assertIn('mirror/shop/must_purchase/carmilla.png', package.must_purchase)
# in_shop 在导入时绑定的就是这几个列表对象
in_shop = types.SimpleNamespace(**{k: getattr(package, k) for k in aalc_patches.SHOP_LISTS})
lines = []
with as_tasks_mirror(package), chdir(AALC):
filled = aalc_patches.install_shop_lists(log=lines.append)
self.assertEqual(filled, {'must_purchase': 5, 'must_be_abandoned': 19, 'fusion_result': 31})
self.assertEqual([len(getattr(in_shop, k)) for k in aalc_patches.SHOP_LISTS], [5, 19, 31])
self.assertIn('mirror/shop/must_purchase/carmilla.png', in_shop.must_purchase)
self.assertIn('must_purchase=5', '\n'.join(lines))
def test_every_listed_name_resolves_under_some_image_root(self): def test_every_listed_name_resolves_under_some_image_root(self):
for kind in aalc_patches.SHOP_LISTS: package = upstream_mirror_package()
for name in aalc_patches.shop_list_images(kind, str(IMAGES)): images = AALC / 'assets' / 'images'
for kind in SHOP_LISTS:
for name in getattr(package, kind):
with self.subTest(name=name): with self.subTest(name=name):
self.assertTrue(any((IMAGES / root / name).is_file() for root in aalc_patches.IMAGE_ROOTS)) self.assertTrue(any((images / root / name).is_file() for root in IMAGE_ROOTS))
def test_local_roots_match_aalc_path_manager(self): def test_roots_match_aalc_path_manager(self):
source = (AALC / 'utils' / 'path_manager.py').read_text(encoding='utf-8') source = (AALC / 'utils' / 'path_manager.py').read_text(encoding='utf-8')
for root in aalc_patches.IMAGE_ROOTS: for root in IMAGE_ROOTS:
self.assertIn('"%s"' % root, source) self.assertIn('"%s"' % root, source)
class ShopListImagesTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.images = tmp.name
def put(self, root, kind, name):
folder = os.path.join(self.images, *root.split('/'), 'mirror', 'shop', kind)
os.makedirs(folder, exist_ok=True)
open(os.path.join(folder, name), 'wb').close()
def test_merges_themes_and_languages_without_duplicates(self):
self.put('default/share', 'must_purchase', 'b.png')
self.put('dark/share', 'must_purchase', 'b.png')
self.put('default/zh_cn', 'must_purchase', 'a.png')
self.put('default/share', 'must_purchase', 'notes.txt')
os.makedirs(os.path.join(self.images, 'default', 'share', 'mirror', 'shop', 'must_purchase', 'x.png'))
self.assertEqual(aalc_patches.shop_list_images('must_purchase', self.images),
['mirror/shop/must_purchase/a.png', 'mirror/shop/must_purchase/b.png'])
def test_missing_folders_give_an_empty_list(self):
self.assertEqual(aalc_patches.shop_list_images('fusion_result', self.images), [])
def test_non_empty_upstream_list_is_left_alone(self):
self.put('default/share', 'must_purchase', 'a.png')
package = types.SimpleNamespace(must_purchase=['upstream.png'], must_be_abandoned=[], fusion_result=[])
with as_tasks_mirror(package):
filled = aalc_patches.install_shop_lists(log=lambda m: None, images_dir=self.images)
self.assertEqual(package.must_purchase, ['upstream.png'])
self.assertEqual(filled, {'must_be_abandoned': 0, 'fusion_result': 0})
def test_import_failure_is_reported_not_raised(self):
lines = []
with mock.patch.dict(sys.modules, {'tasks': types.ModuleType('tasks'), 'tasks.mirror': None}):
self.assertEqual(aalc_patches.install_shop_lists(log=lines.append), {})
self.assertIn('商店清单补丁跳过', '\n'.join(lines))
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()