P2-6 镜牢商店必买先按中文名购买, 取消 P2-7
- 商店每一格下面写着饰品中文名(实机截图可见)。install_shop_by_name 在 buy_gifts 期间往 must_purchase 最前面临时插 3 个占位项, 上游逐个 click_element 点到占位项时: 以 shop_coins_assets 为锚点在商品格范围内 OCR, 名字完全一致 (允许 + 后缀)就点上方的图标, 之后购买/确认仍走上游循环; 图标模板在后面兜底。 - 名字表 lc_mcp/data/shop_gifts.json: AALC 5 张必买模板对应的饰品, 中文名按零协 汉化; 同一名字一次进店最多点 4 次; 没命中的截图不重复 OCR。 - 审计记 shop/name_match; 装在商店审计之后, 购买仍记 purchase_clicked。 - LCP_SHOP_NAMES=0 关闭; 表读不了或上游不再逐个点 must_purchase 时记 [ERROR]。 - 单测执行上游真实的 Shop.buy_gifts, 坐标按截图实测。 - P2-7 观测饰品自动勾选按用户意见不做。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,313 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""镜牢商店按中文名购买(BACKLOG P2-6)。
|
||||
|
||||
上游必买只认 5 张图标模板; 汉化后商店每一格下面写着饰品中文名。补丁在上游必买循环最前面临时插占位项,
|
||||
点到占位项时按名字表 OCR, 命中就点那一格的图标, 之后的购买/确认仍是上游原来那段循环。
|
||||
端到端用例执行上游真实的 Shop.buy_gifts。
|
||||
"""
|
||||
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
|
||||
|
||||
IN_SHOP = REPO / 'vendor' / 'aalc' / 'tasks' / 'mirror' / 'in_shop.py'
|
||||
MUST_PURCHASE = REPO / 'vendor' / 'aalc' / 'assets' / 'images' / 'default' / 'share' / 'mirror' / 'shop' / 'must_purchase'
|
||||
SCALE = 720 / 1440
|
||||
COINS = (551, 137) # 金币图标(1280x720)
|
||||
|
||||
|
||||
def icon_at(col, row):
|
||||
"""第 row 行第 col 列商品的图标中心; 列距 300、名字行在金币下方 +409/+716(1440 标定)。"""
|
||||
return (COINS[0] + (147 + 300 * col) * SCALE, COINS[1] + (409 + 307 * row - ap.SHOP_NAME_TO_ICON) * SCALE)
|
||||
|
||||
|
||||
class ShopNameHitsTest(unittest.TestCase):
|
||||
|
||||
def test_real_screenshot_layout(self):
|
||||
# docs/feedback/mirror_20261002_181322/special_shop_missed.png(1920x1080): 金币模板匹配在 (827, 206),
|
||||
# 名字行与图标中心是对着截图量的
|
||||
lines = [('人格技能观测', 937, 513), ('替换格里高尔的技能', 1162, 513), ('辉光变动仪', 1627, 513),
|
||||
('无头肖像', 937, 743), ('梦中的电子羊', 1162, 743), ('黏性淤浆', 1627, 743),
|
||||
('特殊商店', 383, 185), ('强化饰品', 265, 588), ('刷新', 1521, 183), ('离开', 1698, 970)]
|
||||
names = ('无头肖像', '辉光变动仪', '离开', '强化饰品')
|
||||
hits = ap.shop_name_hits(lines, names, (827, 206), 1080 / 1440)
|
||||
self.assertEqual([name for name, _ in hits], ['无头肖像', '辉光变动仪'])
|
||||
for (_, (x, y)), icon in zip(hits, [(937, 627), (1627, 397)]):
|
||||
self.assertAlmostEqual(x, icon[0], delta=3)
|
||||
self.assertAlmostEqual(y, icon[1], delta=3)
|
||||
|
||||
def test_only_whole_names_match(self):
|
||||
x, y = icon_at(0, 0)
|
||||
y += ap.SHOP_NAME_TO_ICON * SCALE
|
||||
names = ('缘分残片', '归途')
|
||||
hit = lambda text: [n for n, _ in ap.shop_name_hits([(text, x, y)], names, COINS, SCALE)]
|
||||
self.assertEqual(hit('缘分 残片'), ['缘分残片'])
|
||||
self.assertEqual(hit('缘分残片+'), ['缘分残片'])
|
||||
self.assertEqual(hit('缘分残片++'), ['缘分残片'])
|
||||
self.assertEqual(hit('归途。'), ['归途'])
|
||||
self.assertEqual(hit('残片'), [])
|
||||
self.assertEqual(hit('缘分残片的回忆'), [])
|
||||
|
||||
def test_table_order_wins_over_screen_order(self):
|
||||
lines = [('归途', *icon_at(0, 0)), ('缘分残片', *icon_at(3, 1))]
|
||||
lines = [(t, x, y + ap.SHOP_NAME_TO_ICON * SCALE) for t, x, y in lines]
|
||||
hits = ap.shop_name_hits(lines, ('缘分残片', '归途'), COINS, SCALE)
|
||||
self.assertEqual(hits, [('缘分残片', icon_at(3, 1)), ('归途', icon_at(0, 0))])
|
||||
|
||||
|
||||
class ShopGiftsTableTest(unittest.TestCase):
|
||||
|
||||
def test_shipped_table(self):
|
||||
names = ap.load_shop_gifts()
|
||||
self.assertEqual(names, ('缘分残片', '卡蜜拉', '采血包', '归途', '石版字符'))
|
||||
|
||||
@unittest.skipUnless(MUST_PURCHASE.is_dir(), 'vendor/aalc 子模块未检出')
|
||||
def test_shipped_table_covers_every_upstream_template(self):
|
||||
with open(ap.SHOP_NAMES_FILE, encoding='utf-8') as f:
|
||||
templates = {item['template'] for item in json.load(f)['gifts']}
|
||||
self.assertEqual(templates, set(os.listdir(MUST_PURCHASE)))
|
||||
|
||||
def test_bad_tables_raise_value_error(self):
|
||||
bad = ['[]', '{"gifts": []}', '{"gifts": {}}', '{"gifts": ["归途"]}', '{"gifts": [{"name": ""}]}',
|
||||
'{"gifts": [{"name": "。"}]}', '{"gifts": [{"name": "归途"}, {"name": "归 途"}]}']
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = os.path.join(tmp, 's.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_shop_gifts(path)
|
||||
|
||||
|
||||
class ShopScreen:
|
||||
"""商店界面: 一格格商品(图标 + 下面的名字), 点图标弹购买框, 点购买扣钱, 再点确认。"""
|
||||
|
||||
def __init__(self, items, money=1000, price=150):
|
||||
self.items = [dict(item) for item in items]
|
||||
self.money, self.price = money, price
|
||||
self.popup, self.confirm = None, False
|
||||
self.bought, self.icon_clicks = [], []
|
||||
self.screenshot = object()
|
||||
self.model = None
|
||||
|
||||
def icon(self, item):
|
||||
return icon_at(item['col'], item['row'])
|
||||
|
||||
def take_screenshot(self, *args, **kwargs):
|
||||
self.screenshot = object()
|
||||
return self.screenshot
|
||||
|
||||
def find_element(self, target, find_type='image', **kwargs):
|
||||
if target == ap.SHOP_COINS:
|
||||
return COINS
|
||||
if target.startswith('mirror/shop/must_purchase/'):
|
||||
template = target.rsplit('/', 1)[1]
|
||||
return next((self.icon(i) for i in self.items if i.get('template') == template), False)
|
||||
return [] if find_type == 'image_with_multiple_targets' else False
|
||||
|
||||
def click_element(self, target, *args, **kwargs):
|
||||
if target == ap.SHOP_PURCHASE:
|
||||
if self.popup is None or self.money < self.price:
|
||||
return False
|
||||
self.money -= self.price
|
||||
self.bought.append(self.popup['name'])
|
||||
self.items.remove(self.popup)
|
||||
self.popup, self.confirm = None, True
|
||||
return True
|
||||
if target == ap.SHOP_CONFIRM:
|
||||
done, self.confirm = self.confirm, False
|
||||
return done
|
||||
position = self.find_element(target)
|
||||
if position:
|
||||
self.mouse_click(*position)
|
||||
return True
|
||||
return False
|
||||
|
||||
def mouse_click(self, x, y, *args, **kwargs):
|
||||
for item in self.items:
|
||||
ix, iy = self.icon(item)
|
||||
if abs(ix - x) < 30 and abs(iy - y) < 30:
|
||||
self.popup = item
|
||||
self.icon_clicks.append(item['name'])
|
||||
return True
|
||||
|
||||
def mouse_click_blank(self, *args, **kwargs):
|
||||
self.popup = None
|
||||
|
||||
def mouse_action_with_pos(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def find_language_text(self, *args, **kwargs):
|
||||
return False
|
||||
|
||||
def run(self, image):
|
||||
lines = [('刷新', COINS[0] + 520 * SCALE, COINS[1] - 30 * SCALE),
|
||||
('强化饰品', COINS[0] - 750 * SCALE, COINS[1] + 500 * SCALE)]
|
||||
for item in self.items:
|
||||
x, y = self.icon(item)
|
||||
lines.append((item.get('label', item['name']), x, y + ap.SHOP_NAME_TO_ICON * SCALE))
|
||||
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(IN_SHOP.is_file(), 'vendor/aalc 子模块未检出')
|
||||
class UpstreamBuyGiftsTest(unittest.TestCase):
|
||||
"""执行上游真实的 Shop.buy_gifts: 买完必买项, 钱读成 0 不刷新, 一轮就结束。"""
|
||||
|
||||
def setUp(self):
|
||||
self.lines = []
|
||||
tree = ast.parse(IN_SHOP.read_text(encoding='utf-8'))
|
||||
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Shop')
|
||||
self.fn_node = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == 'buy_gifts')
|
||||
self.templates = ['mirror/shop/must_purchase/%s' % name for name in
|
||||
('carmilla.png', 'homeward.png', 'lithograph.png', 'phlebotomy_pack.png',
|
||||
'piece_of_relationship.png')]
|
||||
|
||||
def play(self, items, patched=True, audit=False, env=None, **screen_kwargs):
|
||||
screen = ShopScreen(items, **screen_kwargs)
|
||||
must = list(self.templates)
|
||||
ns = dict(auto=screen, must_purchase=must, sleep=lambda *a: None, retry=lambda: True, log=mock.Mock(),
|
||||
cfg=SimpleNamespace(set_win_size=720, not_skip_whitegossypium=False))
|
||||
exec(compile(ast.Module(body=[self.fn_node], type_ignores=[]), str(IN_SHOP), 'exec'), ns)
|
||||
shop_cls = type('Shop', (), {'buy_gifts': ns['buy_gifts'], 'RestartGame': RuntimeError})
|
||||
in_shop = types.ModuleType('tasks.mirror.in_shop')
|
||||
in_shop.Shop, in_shop.must_purchase = shop_cls, must
|
||||
package = types.ModuleType('tasks.mirror')
|
||||
package.in_shop = in_shop
|
||||
modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.in_shop': in_shop,
|
||||
'module': types.ModuleType('module'),
|
||||
'module.automation': SimpleNamespace(auto=screen),
|
||||
'module.config': SimpleNamespace(cfg=ns['cfg']),
|
||||
'module.ocr': SimpleNamespace(ocr=screen)}
|
||||
with mock.patch.dict(sys.modules, modules):
|
||||
if audit:
|
||||
ap.install_shop_audit(log=self.lines.append)
|
||||
if patched:
|
||||
self.assertIsNotNone(ap.install_shop_by_name(log=self.lines.append, env=env or {}))
|
||||
shop = shop_cls()
|
||||
shop.system, shop.shopping_strategy, shop.fuse_aggressive_switch = 'bleed', False, False
|
||||
shop.second_system, shop.max_keyword_refresh, shop.max_normal_refresh = False, 0, 0
|
||||
shop._get_cost = lambda: 0
|
||||
shop.buy_gifts()
|
||||
self.assertEqual(must, self.templates, '占位项必须拿掉')
|
||||
self.assertNotIn('click_element', vars(screen), 'click_element 必须还原')
|
||||
return screen
|
||||
|
||||
@property
|
||||
def log(self):
|
||||
return '\n'.join(self.lines)
|
||||
|
||||
def test_patch_hooks_into_the_current_upstream(self):
|
||||
self.play([])
|
||||
self.assertIn('patch: 商店必买先按中文名找(shop_gifts.json, 5 个名字)', self.log)
|
||||
self.assertNotIn('[ERROR]', self.log)
|
||||
|
||||
def test_name_on_the_grid_is_bought(self):
|
||||
items = [{'name': '缘分残片', 'col': 2, 'row': 1}, {'name': '黏性淤浆', 'col': 0, 'row': 0}]
|
||||
self.assertEqual(self.play(items, patched=False).bought, []) # 图标模板没认出来
|
||||
self.assertEqual(self.play(items).bought, ['缘分残片'])
|
||||
self.assertIn('商店: 按名字找到「缘分残片」, 点它的图标', self.log)
|
||||
|
||||
def test_table_order_decides_when_money_is_short(self):
|
||||
items = [{'name': '归途', 'col': 0, 'row': 0}, {'name': '缘分残片', 'col': 3, 'row': 1}]
|
||||
self.assertEqual(self.play(items, money=150).bought, ['缘分残片'])
|
||||
self.assertEqual(self.play(items, money=1000).bought, ['缘分残片', '归途'])
|
||||
|
||||
def test_templates_still_back_up_a_misread_name(self):
|
||||
items = [{'name': '卡蜜拉', 'label': '卡密拉', 'template': 'carmilla.png', 'col': 1, 'row': 0}]
|
||||
self.assertEqual(self.play(items).bought, ['卡蜜拉'])
|
||||
|
||||
def test_unaffordable_item_is_not_clicked_forever(self):
|
||||
screen = self.play([{'name': '采血包', 'col': 1, 'row': 1}], money=0)
|
||||
self.assertEqual(screen.bought, [])
|
||||
self.assertEqual(screen.icon_clicks, ['采血包'] * ap.SHOP_NAME_CLICKS)
|
||||
|
||||
def test_audit_sees_the_name_purchase(self):
|
||||
with mock.patch.object(ap.decisions, 'record') as record:
|
||||
self.play([{'name': '缘分残片', 'col': 2, 'row': 1}], audit=True)
|
||||
self.assertEqual(record.call_args_list, [
|
||||
mock.call('shop', '缘分残片', 'name_match', on_screen=['缘分残片']),
|
||||
mock.call('shop', 'shop_by_name', 'purchase_clicked', system='bleed')])
|
||||
|
||||
def test_env_zero_keeps_upstream(self):
|
||||
self.assertIsNone(ap.install_shop_by_name(log=self.lines.append, env={ap.SHOP_NAMES_ENV: '0'}))
|
||||
|
||||
|
||||
class InstallShopByNameTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.lines = []
|
||||
self.must = ['mirror/shop/must_purchase/a.png']
|
||||
self.auto = SimpleNamespace(click_element=mock.Mock(return_value=False), find_element=mock.Mock())
|
||||
self.shop_cls = type('Shop', (), {'buy_gifts': mock.Mock(side_effect=RuntimeError('boom'))})
|
||||
in_shop = types.ModuleType('tasks.mirror.in_shop')
|
||||
in_shop.Shop, in_shop.must_purchase = self.shop_cls, self.must
|
||||
package = types.ModuleType('tasks.mirror')
|
||||
package.in_shop = in_shop
|
||||
modules = {'tasks': types.ModuleType('tasks'), 'tasks.mirror': package, 'tasks.mirror.in_shop': in_shop,
|
||||
'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_placeholders_and_click_are_restored_after_an_exception(self):
|
||||
real = self.auto.click_element
|
||||
ap.install_shop_by_name(log=self.lines.append, env={})
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.shop_cls().buy_gifts()
|
||||
self.assertEqual(self.must, ['mirror/shop/must_purchase/a.png'])
|
||||
self.assertIs(self.auto.click_element, real)
|
||||
|
||||
def test_upstream_without_the_must_purchase_loop_is_an_error(self):
|
||||
def buy_gifts(shop):
|
||||
return shop # 不再逐个点 must_purchase
|
||||
|
||||
self.shop_cls.buy_gifts = buy_gifts
|
||||
self.assertIsNone(ap.install_shop_by_name(log=self.lines.append, env={}))
|
||||
self.assertIs(self.shop_cls.buy_gifts, buy_gifts)
|
||||
self.assertIn('[ERROR] [lc_mcp] 商店按名字购买跳过: 上游 Shop.buy_gifts 不再逐个', '\n'.join(self.lines))
|
||||
|
||||
def test_unreadable_table_is_an_error(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = os.path.join(tmp, 's.json')
|
||||
with open(path, 'w', encoding='utf-8') as f:
|
||||
f.write('{"gifts": []}')
|
||||
self.assertIsNone(ap.install_shop_by_name(log=self.lines.append, env={ap.SHOP_NAMES_ENV: path}))
|
||||
self.assertTrue(self.lines[0].startswith('[ERROR] [lc_mcp] 商店按名字购买跳过'))
|
||||
|
||||
def test_ocr_error_falls_back_to_templates(self):
|
||||
calls = []
|
||||
auto = self.auto
|
||||
|
||||
def buy_gifts(shop):
|
||||
for commodity in must_purchase():
|
||||
calls.append((commodity, auto.click_element(commodity, threshold=0.85)))
|
||||
auto.click_element('mirror/shop/purchase_assets.png')
|
||||
|
||||
must_purchase = lambda: list(self.must) # noqa: E731
|
||||
self.shop_cls.buy_gifts = buy_gifts
|
||||
self.auto.screenshot = object()
|
||||
self.auto.find_element = mock.Mock(side_effect=RuntimeError('ocr'))
|
||||
ap.install_shop_by_name(log=self.lines.append, env={})
|
||||
self.shop_cls().buy_gifts()
|
||||
self.assertEqual(calls, [(ap.SHOP_BY_NAME, False)] * ap.SHOP_BY_NAME_SLOTS
|
||||
+ [('mirror/shop/must_purchase/a.png', False)])
|
||||
self.assertIn('商店按名字购买出错(RuntimeError: ocr), 只用图标模板', '\n'.join(self.lines))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user