- 饰品(P1-3): 三张及以上时上游把认出体系图标的卡逐张 insert(0), 后看的排到最前,
两张命中关键词的卡都带图标时补丁的顺序会被倒过来, 先拿命中少的。现在交给上游
"没命中的(原顺序) + 命中的(倒着)", 上游查体系图标时对命中的卡答"有", 拼出来是
命中多 -> 命中少 -> 只认出图标 -> 其余。测试的假界面加上体系图标, 先复现再修。
- 选队(P1-5): _team_ocr 经 _run_ocr_for_text 的 {文本: 坐标} 取结果, 选中某队后
顶栏和列表同名, 顶栏那条会被覆盖; 旧测试用成对结果模拟重复, 真实 dict 做不到。
改读 OCR 引擎逐行结果(同一引擎、同一截图), 引擎导入不了才退回 dict。
- 事件(P1-4): 同一张截图只判断一次, 单通模式再找 "???" 时不再整屏 OCR 第二遍。
- 文档: 修正 BACKLOG/README/交接文档对应描述, 去掉两处没核实的推断。
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
363 lines
17 KiB
Python
363 lines
17 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""镜牢饰品选择按体系关键词排序(BACKLOG P1-3)。
|
|
|
|
2026-11-14 核对: acquire_ego_gift() 两张卡时只排白棉花和已持有然后拿第一张, 不看 team_system。
|
|
补丁在上游挑选前按卡面 OCR 的体系关键词给卡排序; 端到端用例执行上游真实的 acquire_ego_gift。
|
|
"""
|
|
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
|
|
|
|
AALC = REPO / 'vendor' / 'aalc'
|
|
MIRROR = AALC / 'tasks' / 'mirror' / 'mirror.py'
|
|
SCALE = 720 / 1440
|
|
|
|
|
|
def line_at(card, row):
|
|
"""卡面第 row 行文字的位置(在上游判断范围内)。"""
|
|
return card[0] + 100 * SCALE * 2, card[1] + 40 * row
|
|
|
|
|
|
class GiftCardHitsTest(unittest.TestCase):
|
|
|
|
CARDS = [(300, 300), (600, 300), (900, 300)]
|
|
|
|
def hits(self, lines, keywords=('流血', '出血', 'bleed')):
|
|
return ap.gift_card_hits(self.CARDS, lines, keywords, SCALE)
|
|
|
|
def test_lines_are_assigned_to_the_card_they_sit_on(self):
|
|
lines = [('施加3层流血', *line_at(self.CARDS[1], 0)),
|
|
('出血时伤害提高', *line_at(self.CARDS[1], 1)),
|
|
('烧伤', *line_at(self.CARDS[0], 0)),
|
|
('选择EGO饰品', 600, 40)] # 标题不在任何卡上
|
|
self.assertEqual(self.hits(lines), [[], ['流血', '出血'], []])
|
|
|
|
def test_english_is_case_insensitive_and_spaces_are_ignored(self):
|
|
lines = [('Inflict BLEED', *line_at(self.CARDS[2], 0)), ('流 血', *line_at(self.CARDS[0], 0))]
|
|
self.assertEqual(self.hits(lines), [['流血'], [], ['bleed']])
|
|
|
|
def test_known_ocr_misreads_still_hit(self):
|
|
lines = [('施加震颐', *line_at(self.CARDS[0], 0)), ('沉论层数', *line_at(self.CARDS[1], 0))]
|
|
self.assertEqual(ap.gift_card_hits(self.CARDS, lines, ('震颤',), SCALE), [['震颤'], [], []])
|
|
self.assertEqual(ap.gift_card_hits(self.CARDS, lines, ('沉沦',), SCALE), [[], ['沉沦'], []])
|
|
|
|
def test_overlapping_ranges_go_to_the_nearest_card(self):
|
|
cards = [(300, 300), (450, 300)] # 两张卡的范围在 x=425..525 重叠
|
|
lines = [('流血', 440, 300), ('流血', 500, 300)]
|
|
self.assertEqual(ap.gift_card_hits(cards, lines, ('流血',), SCALE), [['流血'], ['流血']])
|
|
|
|
def test_upstream_order_undoes_the_icon_insertion(self):
|
|
# 两张卡上游按给的顺序挑; 三张时命中的卡被上游逐张 insert(0), 所以倒着给、放在最后
|
|
self.assertEqual(ap.gift_upstream_order([[], ['x']]), [1, 0])
|
|
self.assertEqual(ap.gift_upstream_order([['x'], [], ['x', 'y']]), [1, 0, 2])
|
|
self.assertEqual(ap.gift_upstream_order([[], [], []]), [0, 1, 2])
|
|
|
|
def test_rank_is_stable(self):
|
|
cards = ['a', 'b', 'c']
|
|
self.assertEqual(ap.rank_gift_cards(cards, [[], ['x'], []]), ['b', 'a', 'c'])
|
|
self.assertEqual(ap.rank_gift_cards(cards, [[], [], []]), cards)
|
|
self.assertEqual(ap.rank_gift_cards(cards, [['x'], ['x', 'y'], ['x']]), ['b', 'a', 'c'])
|
|
|
|
|
|
class KeywordTableTest(unittest.TestCase):
|
|
|
|
def test_shipped_table_covers_every_upstream_system(self):
|
|
table = ap.load_gift_keywords()
|
|
source = AALC / 'tasks' / '__init__.py'
|
|
if source.is_file():
|
|
tree = ast.parse(source.read_text(encoding='utf-8'))
|
|
node = next(n for n in tree.body if isinstance(n, ast.Assign)
|
|
and getattr(n.targets[0], 'id', None) == 'all_systems')
|
|
self.assertEqual(set(table), set(ast.literal_eval(node.value).values()))
|
|
for system, words in table.items():
|
|
self.assertTrue(words, system)
|
|
|
|
def test_bad_files_raise_value_error(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = os.path.join(tmp, 'k.json')
|
|
for content in ('[]', '{"bleed": "流血"}', '{"bleed": [1]}', '{'):
|
|
with self.subTest(content=content):
|
|
with open(path, 'w', encoding='utf-8') as f:
|
|
f.write(content)
|
|
with self.assertRaises(ValueError):
|
|
ap.load_gift_keywords(path)
|
|
|
|
def test_notes_are_ignored(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = os.path.join(tmp, 'k.json')
|
|
with open(path, 'w', encoding='utf-8') as f:
|
|
json.dump({'_说明': ['x'], 'bleed': ['流血', ' ']}, f, ensure_ascii=False)
|
|
self.assertEqual(ap.load_gift_keywords(path), {'bleed': ('流血',)})
|
|
|
|
|
|
class GiftScreen:
|
|
"""饰品选择界面: 每张卡 {'pos', 'lines', 'icon'}; icon 为 True 的卡体系图标模板能匹配上
|
|
(本机日志里没见它匹配上过, 默认 False)。"""
|
|
|
|
def __init__(self, cards, pick='0/1'):
|
|
self.cards = cards
|
|
self.pick = pick
|
|
self.clicks = []
|
|
self.ocr_runs = 0
|
|
self.model = None
|
|
self.screenshot = object()
|
|
|
|
def lines(self):
|
|
return [(text, *line_at(card['pos'], row))
|
|
for card in self.cards for row, text in enumerate(card['lines'])]
|
|
|
|
def take_screenshot(self):
|
|
return self.screenshot
|
|
|
|
def mouse_to_blank(self):
|
|
pass
|
|
|
|
def click_element(self, target, **kwargs):
|
|
return target.endswith('acquire_ego_gift_select_assets.png')
|
|
|
|
def find_element(self, target, find_type='image', threshold=0.8, my_crop=None, **kwargs):
|
|
if target == ap.GIFT_CARD and find_type == 'image_with_multiple_targets':
|
|
return [card['pos'] for card in self.cards]
|
|
if target.startswith('mirror/road_in_mir/acquire_ego_gift/') and my_crop:
|
|
x1, y1, x2, y2 = my_crop
|
|
for card in self.cards:
|
|
if card.get('icon') and x1 <= card['pos'][0] <= x2 and y1 <= card['pos'][1] <= y2:
|
|
return card['pos']
|
|
return False
|
|
|
|
def find_language_text(self, zh_text, en_text, my_crop=None, **kwargs):
|
|
words = [zh_text] if isinstance(zh_text, str) else zh_text
|
|
x1, y1, x2, y2 = my_crop
|
|
for text, x, y in self.lines():
|
|
if x1 <= x <= x2 and y1 <= y <= y2 and any(w in text for w in words):
|
|
return [x, y]
|
|
return False
|
|
|
|
def find_text_element(self, targets, my_crop=None, **kwargs):
|
|
return self.pick in targets
|
|
|
|
def mouse_click(self, x, y):
|
|
self.clicks.append((x, y))
|
|
|
|
def run(self, image):
|
|
self.ocr_runs += 1
|
|
lines = self.lines()
|
|
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 card(x, *lines, icon=False):
|
|
return {'pos': (x, 300), 'lines': list(lines), 'icon': icon}
|
|
|
|
|
|
@unittest.skipUnless(MIRROR.is_file(), 'vendor/aalc 子模块未检出')
|
|
class UpstreamAcquireEgoGiftTest(unittest.TestCase):
|
|
"""执行上游真实的 Mirror.acquire_ego_gift, 看最后点了哪张卡。"""
|
|
|
|
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 == 'acquire_ego_gift')
|
|
|
|
def choose(self, cards, system='bleed', patched=True, pick='0/1', env=None):
|
|
screen = GiftScreen(cards, pick=pick)
|
|
cfg = SimpleNamespace(set_win_size=720, not_skip_whitegossypium=False, mouse_action_interval=0)
|
|
ns = dict(cfg=cfg, auto=screen, sleep=lambda *a: None, time=SimpleNamespace(sleep=lambda *a: None),
|
|
retry=lambda: True, log=mock.Mock(),
|
|
ImageUtils=SimpleNamespace(get_bbox=lambda image: None, load_image=lambda path: None),
|
|
all_systems={0: 'burn', 1: 'bleed'})
|
|
exec(compile(ast.Module(body=[self.fn_node], type_ignores=[]), str(MIRROR), 'exec'), ns)
|
|
mirror_cls = type('Mirror', (), {'acquire_ego_gift': ns['acquire_ego_gift']})
|
|
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_gift_preference(log=self.lines.append, env=env or {}))
|
|
mirror = mirror_cls()
|
|
mirror.system, mirror.second_system = system, False
|
|
mirror.acquire_ego_gift()
|
|
self.assertNotIn('find_element', vars(screen), 'find_element 必须还原')
|
|
return [next(i for i, c in enumerate(cards) if c['pos'] == pos) for pos in screen.clicks], screen
|
|
|
|
@property
|
|
def log(self):
|
|
return '\n'.join(self.lines)
|
|
|
|
def test_two_cards_prefers_the_system_keyword(self):
|
|
cards = [card(300, '烧伤层数+1'), card(600, '施加2层流血')]
|
|
self.assertEqual(self.choose(cards, patched=False)[0], [0])
|
|
self.assertEqual(self.choose(cards)[0], [1])
|
|
self.assertIn('第1张=0 第2张=1(流血); 命中体系关键词, 先看第2张', self.log)
|
|
|
|
def test_owned_keyword_card_still_loses_to_an_unowned_one(self):
|
|
cards = [card(300, '烧伤层数+1'), card(600, '施加2层流血', '已持有')]
|
|
self.assertEqual(self.choose(cards)[0], [0])
|
|
|
|
def test_all_owned_falls_back_to_keyword_order(self):
|
|
cards = [card(300, '烧伤', '已持有'), card(600, '流血', '已持有')]
|
|
self.assertEqual(self.choose(cards)[0], [1])
|
|
|
|
def test_white_gossypium_is_still_skipped(self):
|
|
cards = [card(300, '烧伤层数+1'), card(600, '白棉花', '流血')]
|
|
self.assertEqual(self.choose(cards)[0], [0])
|
|
|
|
def test_all_white_gossypium_behaves_like_upstream(self):
|
|
cards = [card(300, '白棉花'), card(600, '白棉花', '流血')]
|
|
self.assertEqual(self.choose(cards)[0], self.choose(cards, patched=False)[0])
|
|
|
|
def test_three_cards_pick_one(self):
|
|
cards = [card(300, '烧伤'), card(600, '震颤'), card(900, '流血伤害提高', '施加流血')]
|
|
self.assertEqual(self.choose(cards, patched=False)[0], [0])
|
|
self.assertEqual(self.choose(cards)[0], [2])
|
|
|
|
def test_three_cards_pick_two(self):
|
|
cards = [card(300, '烧伤'), card(600, '流血'), card(900, '流血', '施加流血')]
|
|
self.assertEqual(self.choose(cards, pick='0/2')[0], [2, 1])
|
|
|
|
def test_icon_cards_keep_the_keyword_order(self):
|
|
# 上游把认出体系图标的卡逐张 insert(0), 后认出的反而排前面; 补丁要抵消这一步
|
|
cards = [card(300, '施加流血', icon=True), card(600, '流血', '施加流血', '流血层数', icon=True), card(900, '烧伤')]
|
|
self.assertEqual(self.choose(cards)[0], [1])
|
|
self.assertEqual(self.choose(cards, pick='0/2')[0], [1, 0])
|
|
|
|
def test_keyword_card_without_icon_still_beats_an_icon_card(self):
|
|
cards = [card(300, '流血', '施加流血', '流血层数'), card(600, '施加流血', icon=True), card(900, '烧伤')]
|
|
self.assertEqual(self.choose(cards)[0], [0])
|
|
|
|
def test_icon_only_card_comes_after_keyword_cards_but_before_the_rest(self):
|
|
cards = [card(300, '烧伤'), card(600, '没读出关键词', icon=True), card(900, '施加流血')]
|
|
self.assertEqual(self.choose(cards, patched=False)[0], [1])
|
|
self.assertEqual(self.choose(cards, pick='0/2')[0], [2, 1])
|
|
|
|
def test_without_keywords_icons_behave_like_upstream(self):
|
|
cards = [card(300, '烧伤', icon=True), card(600, '震颤', icon=True), card(900, '充能')]
|
|
self.assertEqual(self.choose(cards, pick='0/2')[0], self.choose(cards, pick='0/2', patched=False)[0])
|
|
|
|
def test_misread_keyword_for_tremor(self):
|
|
cards = [card(300, '流血'), card(600, '施加震颐')]
|
|
self.assertEqual(self.choose(cards, system='tremor')[0], [1])
|
|
|
|
def test_no_hits_keeps_upstream_choice(self):
|
|
cards = [card(300, '烧伤'), card(600, '充能')]
|
|
self.assertEqual(self.choose(cards)[0], [0])
|
|
self.assertIn('未命中体系关键词, 保持原顺序', self.log)
|
|
|
|
def test_duplicate_lines_on_two_cards_both_count(self):
|
|
# {文本: 坐标} 会把两张卡上的同一句合并成一条; 补丁直接读 OCR 引擎的逐行结果
|
|
cards = [card(300, '流血'), card(600, '流血', '施加流血')]
|
|
self.assertEqual(self.choose(cards)[0], [1])
|
|
self.assertIn('第1张=1(流血) 第2张=2(流血/流血)', self.log)
|
|
|
|
def test_decision_is_recorded_left_to_right(self):
|
|
cards = [card(300, '烧伤层数+1'), card(600, '施加2层流血')]
|
|
with mock.patch.object(ap.decisions, 'record') as record:
|
|
self.choose(cards)
|
|
record.assert_called_once_with('gift', 2, 'keyword', system='bleed', hits=[[], ['流血']])
|
|
|
|
def test_unknown_system_skips_ocr(self):
|
|
cards = [card(300, '烧伤'), card(600, '流血')]
|
|
chosen, screen = self.choose(cards, system='unknown')
|
|
self.assertEqual((chosen, screen.ocr_runs), ([0], 0))
|
|
|
|
|
|
class InstallGiftPreferenceTest(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
self.lines = []
|
|
self.original = mock.Mock(return_value='done')
|
|
self.mirror_cls = type('Mirror', (), {'acquire_ego_gift': 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=[(300, 300), (600, 300)]))
|
|
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 install(self, env=None):
|
|
return ap.install_gift_preference(log=self.lines.append, env=env or {})
|
|
|
|
def test_env_zero_leaves_upstream_untouched(self):
|
|
self.assertIsNone(self.install({ap.GIFT_KEYWORDS_ENV: '0'}))
|
|
self.assertIs(self.mirror_cls.acquire_ego_gift, self.original)
|
|
|
|
def test_unreadable_table_is_an_error_and_not_installed(self):
|
|
self.assertIsNone(self.install({ap.GIFT_KEYWORDS_ENV: '/nonexistent/k.json'}))
|
|
self.assertIs(self.mirror_cls.acquire_ego_gift, self.original)
|
|
self.assertTrue(self.lines[0].startswith('[ERROR] [lc_mcp] 饰品体系优先补丁跳过'))
|
|
|
|
def test_refuse_screen_passes_through(self):
|
|
self.install()
|
|
mirror = self.mirror_cls()
|
|
mirror.system = 'bleed'
|
|
self.assertEqual(mirror.acquire_ego_gift(type=2), 'done')
|
|
self.original.assert_called_once_with(mirror, type=2)
|
|
|
|
def test_find_element_is_restored_after_an_exception(self):
|
|
real = self.auto.find_element
|
|
self.original.side_effect = RuntimeError('boom')
|
|
self.install()
|
|
mirror = self.mirror_cls()
|
|
mirror.system = 'bleed'
|
|
with self.assertRaises(RuntimeError):
|
|
mirror.acquire_ego_gift()
|
|
self.assertIs(self.auto.find_element, real)
|
|
|
|
def test_ranking_error_keeps_upstream_order(self):
|
|
cards = [(300, 300), (600, 300)]
|
|
|
|
auto = self.auto
|
|
|
|
def original(mirror):
|
|
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.install()
|
|
mirror = self.mirror_cls()
|
|
mirror.system = 'bleed'
|
|
with mock.patch.object(ap, '_ocr_lines', side_effect=RuntimeError('ocr down')):
|
|
self.assertEqual(mirror.acquire_ego_gift(), cards)
|
|
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__':
|
|
unittest.main()
|