实机回归发现: 镜牢入场时 AALC 直接点「进入」, 根本不走 select_battle_team, 用的是游戏记住的旧队伍; 「星之恩惠」页满屏星星又会让「选队星级」模板误命中。 - aalc_patches: 点「进入」前若在选队页且顶栏不是目标队, 先按体系名切队(充能优先, 没有就震颤); 新增选队页守卫(只有出现「恩惠」字样才忽略星级模板); 选队扫描从每轮 3 次拖动改为 1 次(3 次会整屏跳过, 实测漏掉「充能」) - tests: 44→45 个用例, 覆盖偏好顺序、星之恩惠判定、守卫行为 - docs: REGRESSION-RESULTS.md(勾选结果), ISSUES.md(问题/需求台账), BACKLOG 状态表, HANDOVER 补「拉取后必须重启服务」 单测: 641 passed。实机: 2026-11-15 01:51 入场精确选中「充能」。
1544 lines
69 KiB
Python
1544 lines
69 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""任务子进程里对 AALC 的运行时补丁。不改 vendor/aalc 的源码。
|
||
|
||
1. 队伍名精确匹配
|
||
AALC 的 find_str_in_text 用子串匹配, "TEAMS #1" 会命中 "TEAMS #10"(中文 "编队#1"
|
||
同理)。账号有 10 个以上预设时就会选中别的(常常是空)队伍, 然后在编队人数检查里
|
||
无限空转——2026-10-05 一次空转了 27 分钟。这里只接管队伍名这一种目标, 要求编号
|
||
完全相同, 其他文本仍走 AALC 原逻辑。
|
||
|
||
2. 窗口比例守护
|
||
RDP 重连改变桌面分辨率后, Unity 会把窗口拉伸成非 16:9。AALC 只在任务开始时校正
|
||
一次, 之后全部模板匹配分数掉到阈值以下, 表现为原地空转、不报错。这里在后台定期
|
||
检查客户区尺寸, 偏离 set_win_size 时调回去。
|
||
"""
|
||
import json
|
||
import logging
|
||
import os
|
||
import re
|
||
import threading
|
||
import time
|
||
import unicodedata
|
||
from contextlib import contextmanager
|
||
|
||
from .decisions import decisions
|
||
|
||
TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE)
|
||
|
||
|
||
@contextmanager
|
||
def headless_hdr_warning(scheme, log=print):
|
||
"""Acknowledge upstream's GUI-only HDR prompt without a Qt event loop."""
|
||
from PySide6.QtCore import Qt
|
||
|
||
def acknowledge(event):
|
||
try:
|
||
log('[lc_mcp] HDR 已开启,可能影响图像识别;命令行任务继续运行')
|
||
finally:
|
||
event.set()
|
||
|
||
signal = scheme.mediator.hdr_warning
|
||
signal.connect(acknowledge, Qt.ConnectionType.DirectConnection)
|
||
try:
|
||
yield
|
||
finally:
|
||
signal.disconnect(acknowledge)
|
||
|
||
|
||
class MirrorProgress:
|
||
"""AALC 镜牢的实际完成局数。total 为 None 表示本次没有进入镜牢循环。"""
|
||
|
||
def __init__(self):
|
||
self.total = None
|
||
self.finished = 0
|
||
|
||
def record(self, finished, remaining):
|
||
# Mirror_task 开始时发 (0, 总局数), 每完成一局发 (已完成, 剩余)
|
||
if self.total is None:
|
||
self.total = finished + remaining
|
||
self.finished = max(self.finished, finished)
|
||
|
||
|
||
@contextmanager
|
||
def mirror_progress(scheme):
|
||
"""监听 mirror_signal 统计完成局数。
|
||
|
||
AALC 没有可用队伍或队列为空时 Mirror_task 直接跳出循环, 进程仍以 0 退出;
|
||
只看退出码会把"一局没打"报成 succeeded。
|
||
"""
|
||
from PySide6.QtCore import Qt
|
||
|
||
progress = MirrorProgress()
|
||
signal = scheme.mediator.mirror_signal
|
||
signal.connect(progress.record, Qt.ConnectionType.DirectConnection)
|
||
try:
|
||
yield progress
|
||
finally:
|
||
signal.disconnect(progress.record)
|
||
|
||
|
||
def team_number(text):
|
||
"""'TEAMS #12' / 'TFAMS#3' / '编队#1' -> '12' / '3' / '1'; 不是队伍名返回 None。"""
|
||
m = TEAM_TARGET.fullmatch(text.replace(' ', '').strip())
|
||
return m.group(1) if m else None
|
||
|
||
|
||
def find_team_text(want, ocr_dict):
|
||
"""在 OCR 结果里找编号恰好为 want 的队伍名, 返回其坐标或 False。"""
|
||
for text, position in ocr_dict.items():
|
||
for hit in TEAM_TARGET.finditer(text.replace(' ', '')):
|
||
if hit.group(1) == want:
|
||
return position
|
||
return False
|
||
|
||
|
||
def install_exact_team_match(auto, log=print):
|
||
original = auto.find_str_in_text
|
||
|
||
def find_str_in_text(target, ocr_dict):
|
||
want = team_number(str(target))
|
||
if want is None:
|
||
return original(target, ocr_dict)
|
||
return find_team_text(want, ocr_dict)
|
||
|
||
auto.find_str_in_text = find_str_in_text
|
||
log('[lc_mcp] patch: 队伍名改为编号精确匹配')
|
||
|
||
|
||
class WindowGuard(threading.Thread):
|
||
"""后台检查游戏客户区, 不是 set_win_size 对应的 16:9 尺寸就调回去。"""
|
||
|
||
def __init__(self, screen, cfg, interval=15.0, log=print):
|
||
super().__init__(name='lc_mcp-window-guard', daemon=True)
|
||
self.screen, self.cfg, self.interval, self.log = screen, cfg, interval, log
|
||
self.stopped = threading.Event()
|
||
self.fixes = 0
|
||
self._failed = None # 同一尺寸调不回来只报一次, 免得每 15 秒刷一条 ERROR
|
||
|
||
def want(self):
|
||
size = int(self.cfg.set_win_size)
|
||
return int(size * 16 / 9), size
|
||
|
||
def check_position(self):
|
||
"""窗口有一截跑到屏幕外时挪回工作区。
|
||
|
||
背景(2026-10-22 实测): 游戏会恢复自己保存的窗口位置, 出现过 (-8, 39) 这种
|
||
—— 左边 8 像素在屏幕外。前台模式(background_click=false)下 AALC 从**屏幕**
|
||
抓图, 窗口一出界抓到的画面就整体错位, 模板匹配相似度掉到 0.2~0.5, 表现是
|
||
"日志一直在动但几乎不点击"(实测 30 秒只点 1 次, 挪回来立刻恢复)。
|
||
set_win_position=free 时 AALC 不碰位置, 所以这里补上。
|
||
|
||
返回 'ok' / 'fixed' / None(没法判断)。
|
||
"""
|
||
try:
|
||
import win32con
|
||
import win32gui
|
||
except ImportError:
|
||
return None
|
||
handle = self.screen.handle
|
||
hwnd = handle._hwnd
|
||
try:
|
||
left, top, right, bottom = handle.monitor_info["Work"]
|
||
except Exception:
|
||
return None
|
||
try:
|
||
x, y, r, b = win32gui.GetWindowRect(hwnd)
|
||
except Exception:
|
||
return None
|
||
width, height = r - x, b - y
|
||
if width <= 0 or height <= 0:
|
||
return None
|
||
# 已经完整落在工作区内就不动
|
||
if x >= left and y >= top and r <= right and b <= bottom:
|
||
return 'ok'
|
||
new_x = max(left, min(x, right - width))
|
||
new_y = max(top, min(y, bottom - height))
|
||
try:
|
||
win32gui.SetWindowPos(hwnd, 0, new_x, new_y, 0, 0,
|
||
win32con.SWP_NOSIZE | win32con.SWP_NOZORDER |
|
||
win32con.SWP_NOACTIVATE)
|
||
except Exception as e:
|
||
self.log('[lc_mcp] window guard: 挪窗口失败 %s: %s' % (type(e).__name__, e))
|
||
return None
|
||
self.fixes += 1
|
||
self.log('[lc_mcp] window guard: 窗口 (%d,%d) 有部分在屏幕外, 已挪到 (%d,%d)'
|
||
% (x, y, new_x, new_y))
|
||
return 'fixed'
|
||
|
||
def check_once(self):
|
||
"""返回 'ok' / 'fixed' / 'failed' / None(没有可检查的窗口)。"""
|
||
handle = self.screen.handle
|
||
# set_windows 关闭表示用户自己管窗口, AALC 也不调, 这里同样不插手
|
||
if self.cfg.simulator or not self.cfg.set_windows or not handle._hwnd or handle.isMinimized:
|
||
return None
|
||
# 位置先修: 出界会让抓图错位, 那种情况下尺寸检查也没意义
|
||
if self.check_position() == 'fixed':
|
||
time.sleep(0.5)
|
||
current = (handle.width(True), handle.height(True))
|
||
want = self.want()
|
||
if current == want or 0 in current:
|
||
return 'ok' if current == want else None
|
||
self.screen.adjust_win_size(want)
|
||
time.sleep(1)
|
||
after = (handle.width(True), handle.height(True))
|
||
if after == want:
|
||
self.fixes += 1
|
||
self._failed = None
|
||
self.log('[lc_mcp] window guard: 客户区 %sx%s 已调回 %sx%s' % (current + want))
|
||
return 'fixed'
|
||
if after != self._failed:
|
||
self._failed = after
|
||
self.log('[ERROR] [lc_mcp] window guard: 客户区 %sx%s 调整后仍为 %sx%s(目标 %sx%s),'
|
||
' 桌面可能放不下窗口' % (current + after + want))
|
||
return 'failed'
|
||
|
||
def run(self):
|
||
while not self.stopped.wait(self.interval):
|
||
try:
|
||
self.check_once()
|
||
except Exception as e: # 守护线程不能把任务带崩
|
||
self.log('[lc_mcp] window guard: 检查出错 %s: %s' % (type(e).__name__, e))
|
||
|
||
def stop(self):
|
||
self.stopped.set()
|
||
|
||
# ---------------------------------------------------------------- 驱动级点击接管
|
||
|
||
# 新版 AALC 的输入入口带交互门和锁, 重绑时必须保留这些包装。
|
||
REBIND_NAMES = ('mouse_click', 'mouse_click_blank', 'mouse_down', 'mouse_up')
|
||
|
||
|
||
class DriverClickProxy:
|
||
"""把鼠标点击转发到罗技驱动, 其余一律透传给原 handler。
|
||
|
||
⛔ 只接管**点击类**操作。拖拽/滑动/滚轮仍走 AALC 原逻辑 —— 那些在镜牢和日常
|
||
里用得少, 而各自的行为差异(惯性、多点)不好用相对位移复现, 接了反而更容易出错。
|
||
"""
|
||
|
||
def __init__(self, handler, driver, screen, log=print):
|
||
self._handler = handler
|
||
self._driver = driver
|
||
self._screen = screen
|
||
self.log = log
|
||
self.clicks = 0
|
||
self.refused = 0
|
||
|
||
# --- 透传 -------------------------------------------------------------
|
||
def __getattr__(self, name):
|
||
return getattr(self._handler, name)
|
||
|
||
# --- 接管 -------------------------------------------------------------
|
||
def _screen_pos(self, x, y):
|
||
from .driver_input import client_to_screen, foreground_window, is_console_session
|
||
handle = self._screen.handle
|
||
hwnd = handle.hwnd
|
||
if not hwnd or handle.isMinimized or not is_console_session():
|
||
raise OSError('驱动点击需要 console 会话中可见的游戏窗口')
|
||
if foreground_window() != hwnd:
|
||
handle.setForeground()
|
||
if foreground_window() != hwnd:
|
||
raise OSError('无法激活游戏窗口, 未发送驱动输入')
|
||
# 游戏重启后句柄会变; 每次按当前句柄重新绑定, 免得前台校验拿旧句柄拒绝所有点击。
|
||
bind = getattr(self._driver, 'bind_window', None)
|
||
if bind is not None:
|
||
bind(hwnd)
|
||
return client_to_screen(hwnd, x, y)
|
||
|
||
def _trace(self, msg):
|
||
"""排障用的文件追踪: 日志被 AALC 的 logger 吞掉时靠它看真实调用。"""
|
||
path = os.environ.get('LCP_DRIVER_TRACE')
|
||
if not path:
|
||
return
|
||
try:
|
||
with open(path, 'a', encoding='utf-8') as fh:
|
||
fh.write('%s %s\n' % (time.strftime('%H:%M:%S'), msg))
|
||
except OSError:
|
||
pass
|
||
|
||
def mouse_click(self, x, y, times=1, move_back=False):
|
||
from .driver_input import get_cursor
|
||
self._handler.wait_pause()
|
||
self._trace('mouse_click(%s,%s,times=%s)' % (x, y, times))
|
||
original_pos = None
|
||
try:
|
||
sx, sy = self._screen_pos(x, y)
|
||
if move_back:
|
||
original_pos = get_cursor()
|
||
if self._driver.click(sx, sy, times=times):
|
||
self.clicks += 1
|
||
self.log('[driver] 点击客户区(%d,%d) -> 屏幕(%d,%d)' % (x, y, sx, sy))
|
||
return True
|
||
except InterruptedError:
|
||
raise
|
||
except OSError as e:
|
||
self._trace('点击失败: %s' % e)
|
||
self.log('[driver] 点击失败: %s' % e)
|
||
finally:
|
||
if original_pos is not None:
|
||
self._driver.move_to(*original_pos)
|
||
self.refused += 1
|
||
self.log('[driver] 放弃点击客户区(%d,%d): 无法激活或精确定位' % (x, y))
|
||
return False
|
||
|
||
def mouse_click_blank(self, coordinate=(1, 1), times=1, move_back=False):
|
||
return self.mouse_click(*coordinate, times=times, move_back=move_back)
|
||
|
||
def mouse_down(self, x, y):
|
||
self._handler.wait_pause()
|
||
sx, sy = self._screen_pos(x, y)
|
||
if not self._driver.move_to(sx, sy):
|
||
return False
|
||
return self._driver.down(1) is not False
|
||
|
||
def mouse_up(self, x, y):
|
||
try:
|
||
sx, sy = self._screen_pos(x, y)
|
||
self._driver.move_to(sx, sy)
|
||
finally:
|
||
self._driver.up(1)
|
||
return True
|
||
|
||
|
||
def install_driver_click(auto, screen, driver=None, log=print):
|
||
"""如果环境满足, 把 AALC 的鼠标点击切到罗技驱动级输入。
|
||
|
||
返回驱动实例(成功) 或 None(条件不满足, AALC 保持原样)。
|
||
条件不满足时**不改任何东西** —— 宁可继续用原来的注入方式, 也不要半吊子接管。
|
||
"""
|
||
from .driver_input import DriverInput
|
||
|
||
if isinstance(auto.input_handler, DriverClickProxy):
|
||
return auto.input_handler._driver
|
||
drv = driver if driver is not None else DriverInput(log=log)
|
||
ok, why = drv.preflight()
|
||
if not ok:
|
||
log('[lc_mcp] 驱动级输入未启用: %s' % why)
|
||
return None
|
||
# 绑定目标窗口: click() 靠它做句柄级前台校验。
|
||
# 只比矩形是不够的 —— 窗口互相重叠时, 同一个屏幕坐标会同时落在两边,
|
||
# 实测把浏览器切到前台后, 几何校验照样通过(2026-10-23)。
|
||
try:
|
||
drv.bind_window(screen.handle.hwnd)
|
||
except Exception:
|
||
pass
|
||
|
||
proxy = DriverClickProxy(auto.input_handler, drv, screen, log=log)
|
||
trace = os.environ.get('LCP_DRIVER_TRACE')
|
||
if trace:
|
||
try:
|
||
with open(trace, 'a', encoding='utf-8') as fh:
|
||
fh.write('%s install: 原 handler=%s -> proxy\n'
|
||
% (time.strftime('%H:%M:%S'), type(auto.input_handler).__name__))
|
||
fh.write('%s install: auto.mouse_click 原绑定=%r\n'
|
||
% (time.strftime('%H:%M:%S'), getattr(auto, 'mouse_click', None)))
|
||
except OSError:
|
||
pass
|
||
auto.input_handler = proxy
|
||
for name in REBIND_NAMES:
|
||
gate = getattr(auto, '_run_business_interaction', None)
|
||
setattr(auto, name, gate(name) if callable(gate) else getattr(proxy, name))
|
||
log('[lc_mcp] patch: 鼠标点击已切到罗技驱动级输入')
|
||
return drv
|
||
|
||
|
||
def stop_driver_click(auto):
|
||
handler = auto.input_handler
|
||
if isinstance(handler, DriverClickProxy):
|
||
handler._driver.emergency_stop()
|
||
|
||
|
||
@contextmanager
|
||
def driver_click_tasks(scheme, auto, screen, cfg, log=print):
|
||
"""每次游戏初始化完成后接管, 包括 all 任务和故障重启。"""
|
||
if cfg.simulator or os.environ.get('LCP_DRIVER_INPUT', '').strip() != '1':
|
||
yield
|
||
return
|
||
original = scheme.init_game
|
||
|
||
def init_game(*args, **kwargs):
|
||
result = original(*args, **kwargs)
|
||
install_driver_click(auto, screen, log=log)
|
||
return result
|
||
|
||
scheme.init_game = init_game
|
||
try:
|
||
yield
|
||
finally:
|
||
scheme.init_game = original
|
||
|
||
# ---------------------------------------------------------------- 前台窗口健壮化
|
||
|
||
def install_robust_set_foreground(screen, log=print):
|
||
"""把 SetForegroundWindow 换成带 AttachThreadInput 兜底的版本。
|
||
|
||
背景(2026-10-22): cfg.background_click=False 时 screen.py:342 会调
|
||
self.handle.setForeground(), 而原生实现只有一句裸调用
|
||
win32gui.SetForegroundWindow(hwnd)。Windows 不允许非前台进程抢占前台,
|
||
失败时抛 pywintypes.error(0, 'SetForegroundWindow', ...) —— 这个异常在
|
||
set_win() 里没有捕获, 直接把任务带崩(观测: exit code 3 之前的 traceback)。
|
||
|
||
兜底尝试关联当前线程和前台线程的输入队列, 完成后解挂。
|
||
Windows 仍可能拒绝激活; 驱动输入在发送前另行检查游戏是否在前台。
|
||
"""
|
||
handle = getattr(screen, 'handle', None)
|
||
if handle is None or not hasattr(handle, 'setForeground'):
|
||
log('[lc_mcp] 前台窗口补丁跳过: screen.handle 没有 setForeground')
|
||
return None
|
||
|
||
original = handle.setForeground
|
||
|
||
def setForeground():
|
||
hwnd = getattr(handle, 'hwnd', 0)
|
||
if not hwnd:
|
||
return
|
||
try:
|
||
original()
|
||
return
|
||
except Exception:
|
||
pass # 落到下面的 AttachThreadInput 兜底
|
||
try:
|
||
import win32api
|
||
import win32gui
|
||
import win32process
|
||
|
||
foreground = win32gui.GetForegroundWindow()
|
||
thread_fg = win32process.GetWindowThreadProcessId(foreground)[0] if foreground else 0
|
||
thread_me = win32api.GetCurrentThreadId()
|
||
attached = False
|
||
if thread_fg and thread_fg != thread_me:
|
||
# pywin32 成功时返回 None, 失败抛异常, 不能按真假判断。
|
||
win32process.AttachThreadInput(thread_me, thread_fg, True)
|
||
attached = True
|
||
try:
|
||
win32gui.BringWindowToTop(hwnd)
|
||
win32gui.SetForegroundWindow(hwnd)
|
||
finally:
|
||
if attached:
|
||
win32process.AttachThreadInput(thread_me, thread_fg, False)
|
||
except Exception as e:
|
||
log('[lc_mcp] setForeground 兜底也失败: %s: %s' % (type(e).__name__, e))
|
||
|
||
handle.setForeground = setForeground
|
||
log('[lc_mcp] patch: SetForegroundWindow 加 AttachThreadInput 兜底')
|
||
return handle
|
||
|
||
# ---------------------------------------------------------------- 日常本用默认队伍
|
||
|
||
|
||
def install_default_battle_team(scheme, log=print):
|
||
"""日常本不再翻队伍列表, 直接用界面上已经选中的默认队伍。
|
||
|
||
背景(2026-11-06): 这账号的队伍是自定义名字(不是 "编队#N"), 而
|
||
select_battle_team 按名字找队伍, 找不到就来回滑动 10 次(实测 61 秒), 滑完还把
|
||
队伍页留在滚动后的位置; 紧接着 battle.to_battle() 在 15 次循环里都找不到
|
||
"进入战斗" 按钮, 报 "超出最大尝试次数, 未能进入战斗", 整个日常就这样空转。
|
||
|
||
经验本/纽本本来就是用界面默认队伍打的, 跳过选队伍这一步即可。
|
||
"""
|
||
try:
|
||
from tasks.teams import team_formation as tf
|
||
except Exception as e:
|
||
log('[lc_mcp] 默认队伍补丁跳过: 无法导入 team_formation: %s' % e)
|
||
return None
|
||
original = getattr(tf, 'select_battle_team', None)
|
||
if original is None:
|
||
log('[lc_mcp] 默认队伍补丁跳过: 找不到 select_battle_team')
|
||
return None
|
||
|
||
def select_battle_team(*args, **kwargs):
|
||
log('[lc_mcp] patch: 日常本跳过选队伍, 直接用默认队伍')
|
||
return True
|
||
|
||
tf.select_battle_team = select_battle_team
|
||
scheme.select_battle_team = select_battle_team
|
||
log('[lc_mcp] patch: 日常本使用默认队伍')
|
||
return original
|
||
|
||
|
||
# ---------------------------------------------------------------- 镜牢按体系名选队
|
||
|
||
# 这账号把编队按体系命名(流血的队就叫 "流血"), AALC 却只会找 "编队#N" / "TEAMS #N"。
|
||
# 2026-11-14 实测: 列表里是 剧情关卡/斩击/突刺/打击/烧伤/流血/震颤/破裂/沉沦/呼吸法/充能
|
||
# 再接 编队#13..#38, 根本没有 "编队#1" —— AALC 翻满 10 页也找不到, 报 "无法寻得队伍"。
|
||
SYSTEM_TEAM_NAMES = {
|
||
'burn': ('烧伤',),
|
||
'bleed': ('流血',),
|
||
'tremor': ('震颤',),
|
||
'rupture': ('破裂',),
|
||
'poise': ('呼吸法', '呼吸'),
|
||
'sinking': ('沉沦',),
|
||
'charge': ('充能',),
|
||
'slash': ('斩击',),
|
||
'pierce': ('突刺',),
|
||
'blunt': ('打击',),
|
||
}
|
||
|
||
# 体系名之外还想按顺序再试的队名(2026-11-14 用户指定: 充能优先, 没有就退到震颤)。
|
||
# 注意: 体系本身仍按 team_system 算, 商店/饰品的体系判断不会跟着换。
|
||
TEAM_PREFERENCES = {
|
||
'charge': ('震颤',),
|
||
}
|
||
|
||
# 左侧编队列表的 OCR 命中范围(客户区像素, 1280x720 实测)
|
||
TEAM_LIST_X_MAX = 260
|
||
TEAM_LIST_Y_MIN = 300
|
||
TEAM_LIST_Y_MAX = 640
|
||
# 顶栏 "编队名" 的位置, 用来确认真的选中了
|
||
TEAM_HEADER = (170, 520, 90, 150)
|
||
|
||
|
||
def _team_ocr(auto):
|
||
"""整屏 OCR, 返回 [(去空白的文本, x, y), ...], 空串丢掉。
|
||
|
||
读 OCR 引擎的逐行结果(_ocr_lines): 选中某队后顶栏和左侧列表里是同一个名字, AALC 的
|
||
_run_ocr_for_text 返回 {文本: 坐标}, 同名只留一条, 顶栏那条可能被列表那条盖掉。
|
||
不用 my_crop: 裁剪区的坐标系不可靠。
|
||
"""
|
||
result = []
|
||
for text, x, y in _ocr_lines(auto):
|
||
clean = str(text).replace(' ', '').strip()
|
||
if clean:
|
||
result.append((clean, x, y))
|
||
return result
|
||
|
||
|
||
def _in_list(x, y):
|
||
return x < TEAM_LIST_X_MAX and TEAM_LIST_Y_MIN < y < TEAM_LIST_Y_MAX
|
||
|
||
|
||
def _in_header(x, y):
|
||
x1, x2, y1, y2 = TEAM_HEADER
|
||
return x1 < x < x2 and y1 < y < y2
|
||
|
||
|
||
def _scroll_team_list(auto, direction, times=6, distance=250):
|
||
"""direction=+1 向下拖(回到列表顶部), -1 向上拖(往下翻)。"""
|
||
for _ in range(times):
|
||
auto.mouse_swipe_for_team_scroll(130, 430, dy=direction * distance, duration=0.3)
|
||
time.sleep(0.35)
|
||
|
||
|
||
# 「星之恩惠」页满屏星星, 会命中「选队星级」模板(2026-11-14 实测: 连喊 6 次"不在编队界面",
|
||
# AALC 以为在选队页, 实际在星之恩惠页)。只有编队图标在、或者左侧列表真的是队名, 才算选队页。
|
||
TEAM_SCREEN_STARS = 'mirror/road_to_mir/select_team_stars_assets.png'
|
||
ENTER_ASSET = 'mirror/road_to_mir/enter_assets.png'
|
||
TEAM_SCREEN_ICON = 'teams/identify_assets.png'
|
||
TEAM_SCREEN_KNOWN = frozenset(
|
||
{'剧情关卡'}
|
||
| {name for names in SYSTEM_TEAM_NAMES.values() for name in names}
|
||
| {name for names in TEAM_PREFERENCES.values() for name in names}
|
||
)
|
||
|
||
|
||
def _looks_like_team_screen(auto):
|
||
"""左侧列表里至少 3 条像队名(已知队名或 编队#N)才算选队页。"""
|
||
try:
|
||
names = _list_names([item for item in _team_ocr(auto) if _in_list(item[1], item[2])])
|
||
except Exception:
|
||
return False
|
||
hits = sum(1 for name in names if name in TEAM_SCREEN_KNOWN or name.startswith('编队#'))
|
||
return hits >= 3
|
||
|
||
|
||
STARLIGHT_MARKERS = ('恩惠',)
|
||
|
||
|
||
def _is_starlight_screen(auto):
|
||
"""「星之恩惠」页: 有「恩惠」字样, 满屏星星; 选队页没有。
|
||
|
||
守卫只用它做否定条件, 比「必须有编队图标/队名列表」宽松: 选队页刚加载时图标和列表
|
||
可能还没出来, 严格条件会把真的选队页一起跳过(2026-11-14 21:03 实测)。
|
||
"""
|
||
try:
|
||
return any(marker in text for text, x, y in _team_ocr(auto) for marker in STARLIGHT_MARKERS)
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def install_team_screen_guard(log=print):
|
||
"""选队页守卫: 星级模板在「星之恩惠」页上的命中不算数。"""
|
||
try:
|
||
from module.automation import auto
|
||
except Exception as e:
|
||
log('[lc_mcp] 选队页守卫补丁跳过: 无法导入 auto %s' % e)
|
||
return None
|
||
original = getattr(auto, 'find_element', None)
|
||
if original is None:
|
||
log('[lc_mcp] 选队页守卫补丁跳过: auto 没有 find_element')
|
||
return None
|
||
|
||
def find_element(target, *args, **kwargs):
|
||
result = original(target, *args, **kwargs)
|
||
if result and isinstance(target, str) and target == TEAM_SCREEN_STARS:
|
||
if _is_starlight_screen(auto):
|
||
log('[lc_mcp] 星级模板在星之恩惠页命中, 不是选队页, 忽略')
|
||
return False
|
||
return result
|
||
|
||
auto.find_element = find_element
|
||
log('[lc_mcp] patch: 选队页守卫(星之恩惠页忽略星级模板)')
|
||
return original
|
||
|
||
|
||
# OCR 实测误读(2026-11-14): 震颤→震颐, 沉沦→沉论, 编队#16→编#16。归一化时按子串改回来。
|
||
TEAM_OCR_FIXES = (('震颐', '震颤'), ('沉论', '沉沦'), ('编#', '编队#'))
|
||
TEAM_PREFIX_MIN = 2 # 前缀匹配的队名至少两个字, 免得单字名把一片都吃进来
|
||
|
||
|
||
def normalize_team_name(text):
|
||
"""去空白、全角转半角(NFKC: #→#、()→()、全角空格)、改回常见误读。"""
|
||
text = ''.join(unicodedata.normalize('NFKC', str(text)).split())
|
||
for wrong, right in TEAM_OCR_FIXES:
|
||
text = text.replace(wrong, right)
|
||
return text
|
||
|
||
|
||
def team_name_match(text, names):
|
||
"""'exact' = 归一后等于某个名字; 'prefix' = 某个名字后面带了后缀(流血队、流血(X)); 否则 None。"""
|
||
text = normalize_team_name(text)
|
||
wanted = [normalize_team_name(name) for name in names]
|
||
if text in wanted:
|
||
return 'exact'
|
||
if any(len(name) >= TEAM_PREFIX_MIN and text.startswith(name) for name in wanted):
|
||
return 'prefix'
|
||
return None
|
||
|
||
|
||
def pick_team_item(items, names):
|
||
"""从列表条目 [(文本, x, y)] 里挑要点的那条, 返回 (条目, 理由) 或 (None, 理由)。
|
||
|
||
精确匹配优先, 多个名字时按 names 的顺序; 没有精确匹配才看前缀, 且这一屏只能有一条,
|
||
两条以上宁可不点(点错队比没选上更糟: 后面整局都用错的队)。
|
||
"""
|
||
for name in names:
|
||
for item in items:
|
||
if team_name_match(item[0], (name,)) == 'exact':
|
||
return item, '精确匹配 %s' % name
|
||
prefixed = {}
|
||
for item in items:
|
||
if team_name_match(item[0], names) == 'prefix':
|
||
prefixed.setdefault(normalize_team_name(item[0]), item)
|
||
if len(prefixed) == 1:
|
||
return next(iter(prefixed.values())), '前缀匹配 %s' % '/'.join(names)
|
||
if prefixed:
|
||
return None, '前缀匹配到多条(%s), 不点' % '/'.join(sorted(prefixed))
|
||
return None, ''
|
||
|
||
|
||
def _list_names(items):
|
||
"""这一屏列表里的名字, 从上到下(失败日志用)。"""
|
||
return [normalize_team_name(text) for text, x, y in sorted(items, key=lambda item: item[2])]
|
||
|
||
|
||
def _header_texts(auto):
|
||
"""顶栏区域读到的文字; 截图失败返回 None。"""
|
||
if auto.take_screenshot() is None:
|
||
return None
|
||
return [text for text, x, y in _team_ocr(auto) if _in_header(x, y)]
|
||
|
||
|
||
def _header_is(auto, names):
|
||
"""顶栏当前队伍名(归一后)恰好是 names 之一。只认精确: 顶栏是 "流血2" 时不能当成 "流血"。"""
|
||
return any(team_name_match(text, names) == 'exact' for text in _header_texts(auto) or ())
|
||
|
||
|
||
def _wait_header(auto, names, tries=3, delay=1.2):
|
||
"""点完之后顶栏要过一两帧才刷新, 多等几次。"""
|
||
for _ in range(tries):
|
||
time.sleep(delay)
|
||
if _header_is(auto, names):
|
||
return True
|
||
return False
|
||
|
||
|
||
def _select_team_by_name(auto, names, log=print, rounds=6):
|
||
"""在编队列表里按名字点选。成功返回 True, 没找到返回 False。
|
||
|
||
名字先归一化(空白/全半角/常见误读); 精确匹配优先, 否则接受唯一的"名字+后缀"。
|
||
没找到时把每一屏看到的名字打进日志。
|
||
|
||
每轮只往下拖 1 次: 实测一次拖动能滚 5~6 行、可见 7 行, 3 次一起拖会直接跳过
|
||
一整屏(2026-11-14 实测: 从「剧情关卡..震颤」一次跳到「编队#19..25」, 漏掉「充能」)。
|
||
"""
|
||
if auto.take_screenshot() is None:
|
||
return False
|
||
for _ in range(3):
|
||
if auto.find_element(TEAM_SCREEN_ICON) or _looks_like_team_screen(auto):
|
||
break
|
||
time.sleep(0.8)
|
||
else:
|
||
log('[lc_mcp] 不在编队界面, 跳过按名字选队')
|
||
return False
|
||
current = [normalize_team_name(t) for t in _header_texts(auto) or ()
|
||
if team_name_match(t, names) == 'exact']
|
||
if current: # 已经是这支队就不用动列表; 带后缀的队名要回列表里确认唯一后再点
|
||
log('[lc_mcp] patch: 当前已经是编队 %s, 无需切换' % current[0])
|
||
decisions.record('team', current[0], 'current', wanted=list(names))
|
||
return True
|
||
seen = []
|
||
auto.mouse_click(1, 1)
|
||
time.sleep(0.3)
|
||
# 逐个名字找: 每个名字都从列表顶部重新翻, 保证 names 的顺序就是优先级。
|
||
# (不能只用一屏的命中顺序——名字都可见时随屏幕位置, 靠后的优先项会被漏掉)
|
||
for name in names:
|
||
_scroll_team_list(auto, +1) # 回到顶部
|
||
for round_index in range(1, rounds + 1):
|
||
if auto.take_screenshot() is None:
|
||
log('[lc_mcp] 第 %d 屏截图失败' % round_index)
|
||
continue
|
||
items = [item for item in _team_ocr(auto) if _in_list(item[1], item[2])]
|
||
seen.append(_list_names(items))
|
||
hit, reason = pick_team_item(items, (name,))
|
||
if hit:
|
||
text, x, y = hit
|
||
label = normalize_team_name(text)
|
||
log('[lc_mcp] 编队列表里找到 %s @(%d,%d), %s' % (label, x, y, reason))
|
||
auto.mouse_action_with_pos([x, y], offset=False)
|
||
if _wait_header(auto, (label,)):
|
||
log('[lc_mcp] patch: 已按体系名选中编队 %s' % label)
|
||
decisions.record('team', label, team_name_match(label, names), wanted=list(names))
|
||
return True
|
||
header = [normalize_team_name(t) for t in _header_texts(auto) or ()]
|
||
log('[lc_mcp] 点了 %s 但顶栏没变(顶栏读到: %s), 继续往下翻' % (label, '/'.join(header) or '无'))
|
||
decisions.record('team', label, 'header_unchanged', wanted=list(names), header=header)
|
||
else:
|
||
log('[lc_mcp] 第 %d 屏没有 %s%s; 这一屏的名字: %s'
|
||
% (round_index, name, ', ' + reason if reason else '',
|
||
'/'.join(_list_names(items)) or '(空)'))
|
||
_scroll_team_list(auto, -1, times=1)
|
||
log('[lc_mcp] 编队列表里没找到 %s(共 %d 轮)' % ('/'.join(names), rounds * max(len(names), 1)))
|
||
decisions.record('team', None, 'not_found', wanted=list(names), seen=seen)
|
||
return False
|
||
|
||
|
||
def install_system_team_selection(log=print):
|
||
"""镜牢选队改成"按队伍体系对应的中文名"在列表里点。
|
||
|
||
AALC 原生只认 编队#N; 本账号的编队是自定义名字(流血/斩击/...), 原生逻辑永远选不上。
|
||
"""
|
||
try:
|
||
from tasks.mirror import mirror as mirror_mod
|
||
from module.automation import auto
|
||
except Exception as e:
|
||
log('[lc_mcp] 体系选队补丁跳过: 无法导入 %s' % e)
|
||
return None
|
||
original = getattr(mirror_mod, 'select_battle_team', None)
|
||
if original is None:
|
||
log('[lc_mcp] 体系选队补丁跳过: mirror 模块没有 select_battle_team')
|
||
return None
|
||
wanted = {'names': ()}
|
||
original_init = mirror_mod.Mirror.__init__
|
||
|
||
def __init__(self, team_setting, team_num):
|
||
original_init(self, team_setting, team_num)
|
||
system = getattr(self, 'system', '')
|
||
wanted['names'] = (SYSTEM_TEAM_NAMES.get(system, ())
|
||
+ TEAM_PREFERENCES.get(system, ()))
|
||
log('[lc_mcp] 镜牢体系 %s -> 目标编队 %s'
|
||
% (system or '?', '/'.join(wanted['names']) or '(无配置)'))
|
||
|
||
def select_battle_team(num):
|
||
names = wanted['names']
|
||
if names:
|
||
try:
|
||
if _select_team_by_name(auto, names, log=log):
|
||
return True
|
||
except Exception as e:
|
||
log('[lc_mcp] 按名字选队出错: %s: %s' % (type(e).__name__, e))
|
||
return False
|
||
return original(num)
|
||
|
||
# 2026-11-14 实测: 镜牢入场时 AALC 直接点「进入」, 根本不经过 select_battle_team
|
||
# (只有它先看到星级模板才会走选队)。所以在点「进入」之前补一次切队。
|
||
original_click = getattr(auto, 'click_element', None)
|
||
if original_click is not None:
|
||
def click_element(target, *args, **kwargs):
|
||
if isinstance(target, str) and target == ENTER_ASSET:
|
||
names = wanted['names']
|
||
try:
|
||
if names and _looks_like_team_screen(auto) and not _header_is(auto, names):
|
||
log('[lc_mcp] 入场前切队伍: %s' % '/'.join(names))
|
||
_select_team_by_name(auto, names, log=log)
|
||
except Exception as e:
|
||
log('[lc_mcp] 入场前切队伍出错: %s: %s' % (type(e).__name__, e))
|
||
return original_click(target, *args, **kwargs)
|
||
|
||
auto.click_element = click_element
|
||
log('[lc_mcp] patch: 入场前按体系切队伍')
|
||
|
||
mirror_mod.Mirror.__init__ = __init__
|
||
mirror_mod.select_battle_team = select_battle_team
|
||
log('[lc_mcp] patch: 镜牢按体系名选队')
|
||
return original
|
||
|
||
|
||
# ---------------------------------------------------------------- 镜牢键盘寻路按节点类型
|
||
|
||
# config.yaml 开着 mirror_keyboard_simple_pathfinding 时, AALC 每一步只按 ↑ 进最上面的节点,
|
||
# 完全不看节点类型(2026-11-14: 3 层只进过 1 次商店)。关掉它会走常规寻路, 那条路先用
|
||
# mouse_drag 把地图拖到固定位置(当初开简单模式就是为了躲拖地图卡死), 连线识别还依赖
|
||
# my_crop(交接文档实测在这台机器上坐标对不上)。
|
||
# 这里保持"只按键、不拖地图": 用 AALC 自带的 ONNX 模型整屏识别巴士右侧下一列节点的类型,
|
||
# 按上游 all_node_weight 从低到高依次按方向键, 每次都确认进得去; 都不行再退回原来的 ↑。
|
||
ROAD_KEYS = {'U': 'up', 'M': 'right', 'D': 'down'} # 与上游 MirrorMap.enter_next_node 一致
|
||
ROAD_TIE_ORDER = ('U', 'M', 'D') # 同类型时先试 ↑, 尽量贴近原简单模式
|
||
UPSTREAM_ROAD_COLUMN_GAP = 520 # 上游 search_road 的网格参数(2560x1440 标定)
|
||
UPSTREAM_ROAD_ROW_GAP = 437
|
||
UPSTREAM_NODE_WEIGHT = {
|
||
'battle': 4, 'boss_battle': 6, 'event': 1, 'focused_encounter': 6,
|
||
'risky_encounter': 7, 'shop': 2, 'abnormality_focused_encounter': 6,
|
||
}
|
||
TYPED_ROAD_ENV = 'LCP_TYPED_ROAD' # 设为 0 时不装这个补丁, 完全回到原简单键盘寻路
|
||
|
||
|
||
def rank_next_nodes(bus, nodes, scale, weights=UPSTREAM_NODE_WEIGHT,
|
||
column_gap=UPSTREAM_ROAD_COLUMN_GAP, row_gap=UPSTREAM_ROAD_ROW_GAP):
|
||
"""巴士右侧下一列的节点 -> [(方向, 类型, 权重), ...], 权重小的在前。
|
||
|
||
nodes 是 identify_nodes() 的输出 [[类型, (x, y)], ...]; 只取与巴士相隔一列的节点,
|
||
按相对巴士的行差映射成 U/M/D。同一方向识别出多个时保留权重最小的那个。
|
||
"""
|
||
if not bus or not nodes:
|
||
return []
|
||
gap_x, gap_y = column_gap * scale, row_gap * scale
|
||
best = {}
|
||
for kind, (x, y) in nodes:
|
||
if abs((x - bus[0]) - gap_x) > gap_x / 4:
|
||
continue
|
||
direction = {1: 'U', 0: 'M', -1: 'D'}.get(round((bus[1] - y) / gap_y))
|
||
if direction is None:
|
||
continue
|
||
weight = weights.get(kind)
|
||
if weight is None:
|
||
continue
|
||
if direction not in best or weight < best[direction][1]:
|
||
best[direction] = (kind, weight)
|
||
return sorted(((d, kind, w) for d, (kind, w) in best.items()),
|
||
key=lambda item: (item[2], ROAD_TIE_ORDER.index(item[0])))
|
||
|
||
|
||
def install_typed_keyboard_road(log=print, env=None):
|
||
"""替换简单键盘寻路: 按节点类型挑方向, 失败时退回原 ↑ 逻辑。返回原函数, 未安装返回 None。"""
|
||
env = os.environ if env is None else env
|
||
if env.get(TYPED_ROAD_ENV) == '0':
|
||
log('[lc_mcp] 键盘寻路按类型补丁已关闭(%s=0), 沿用原简单键盘寻路' % TYPED_ROAD_ENV)
|
||
return None
|
||
try:
|
||
from tasks.mirror import mirror as mirror_mod
|
||
from tasks.mirror import search_road as road
|
||
from module.automation import auto
|
||
from module.config import cfg
|
||
except Exception as e:
|
||
log('[lc_mcp] 键盘寻路按类型补丁跳过: 无法导入 %s' % e)
|
||
return None
|
||
original = getattr(road, 'search_road_simple_keyboard', None)
|
||
if original is None or not hasattr(road, 'identify_nodes'):
|
||
log('[lc_mcp] 键盘寻路按类型补丁跳过: 上游没有简单键盘寻路或节点识别')
|
||
return None
|
||
weights = getattr(road, 'all_node_weight', UPSTREAM_NODE_WEIGHT)
|
||
column_gap = getattr(road, 'ROAD_COLUMN_GAP', UPSTREAM_ROAD_COLUMN_GAP)
|
||
row_gap = getattr(road, 'ROAD_ROW_GAP', UPSTREAM_ROAD_ROW_GAP)
|
||
|
||
def search_road_simple_keyboard():
|
||
if not cfg.mirror_keyboard_navigation:
|
||
return original() # 上游会说明需要开启键盘寻路
|
||
try:
|
||
auto.mouse_to_blank()
|
||
time.sleep(0.3)
|
||
bus = auto.find_element('mirror/mybus_default_distance.png', take_screenshot=True)
|
||
nodes = road.identify_nodes(bus[0]) if bus else None
|
||
ranked = rank_next_nodes(bus, nodes, cfg.set_win_size / 1440, weights, column_gap, row_gap)
|
||
except Exception as e:
|
||
log('[lc_mcp] 键盘寻路: 识别下一列节点出错(%s: %s), 退回按 ↑' % (type(e).__name__, e))
|
||
decisions.record('road', 'up', 'fallback', why='%s: %s' % (type(e).__name__, e))
|
||
return original()
|
||
if not ranked:
|
||
why = '没找到巴士' if not bus else '下一列没识别到节点'
|
||
log('[lc_mcp] 键盘寻路: %s, 退回按 ↑' % why)
|
||
decisions.record('road', 'up', 'fallback', why=why)
|
||
return original()
|
||
candidates = ['%s=%s(%d)' % item for item in ranked]
|
||
log('[lc_mcp] 键盘寻路: 下一列 %s, 按权重从低到高依次尝试' % ' '.join(candidates))
|
||
for direction, kind, weight in ranked:
|
||
auto.key_press(ROAD_KEYS[direction])
|
||
time.sleep(1)
|
||
if road._keyboard_enter_succeeded():
|
||
best = direction == ranked[0][0]
|
||
reason = '下一列中最低' if best else '更优的方向没能进入'
|
||
log('[lc_mcp] 键盘寻路: 进入 %s 方向的 %s(权重 %d, %s)' % (direction, kind, weight, reason))
|
||
decisions.record('road', '%s:%s' % (direction, kind), 'lowest' if best else 'next_best',
|
||
candidates=candidates)
|
||
return True
|
||
log('[lc_mcp] 键盘寻路: %s 方向的 %s 没能进入, 试下一个' % (direction, kind))
|
||
log('[lc_mcp] 键盘寻路: 按类型都没进入, 退回按 ↑')
|
||
decisions.record('road', 'up', 'fallback', why='按类型都没进入', candidates=candidates)
|
||
return original()
|
||
|
||
road.search_road_simple_keyboard = search_road_simple_keyboard
|
||
mirror_mod.search_road_simple_keyboard = search_road_simple_keyboard
|
||
log('[lc_mcp] patch: 镜牢键盘寻路按节点类型选方向(不拖地图)')
|
||
return original
|
||
|
||
|
||
# ---------------------------------------------------------------- 临时替换 auto 的方法
|
||
|
||
_MISSING = object()
|
||
|
||
|
||
@contextmanager
|
||
def _override(obj, name, value):
|
||
"""在 with 期间把 obj.name 换成 value(实例属性), 结束时还原成原来的实例属性或类方法。"""
|
||
own = vars(obj).get(name, _MISSING)
|
||
setattr(obj, name, value)
|
||
try:
|
||
yield
|
||
finally:
|
||
if own is _MISSING:
|
||
vars(obj).pop(name, None)
|
||
else:
|
||
setattr(obj, name, own)
|
||
|
||
|
||
# ---------------------------------------------------------------- 饰品选择按体系关键词
|
||
|
||
# 2026-11-14 核对: acquire_ego_gift() 两张卡时只看白棉花和已持有, 拿第一张; 三张卡时虽然用
|
||
# acquire_ego_gift/<体系>.png 做图标匹配(阈值 0.85), 但日志里从没见它起作用。这里在上游挑选之前,
|
||
# 按卡面 OCR 文本里的体系关键词把卡重新排序; 白棉花、已持有、体系图标仍由上游处理(排序稳定)。
|
||
GIFT_KEYWORDS_ENV = 'LCP_GIFT_KEYWORDS' # 0 = 关闭; 文件路径 = 用这张表代替默认表
|
||
GIFT_KEYWORDS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'gift_keywords.json')
|
||
GIFT_CARD = 'mirror/road_in_mir/acquire_ego_gift_card.png'
|
||
GIFT_ICON = 'mirror/road_in_mir/acquire_ego_gift/%s.png' # 上游三张卡时按体系图标挑卡用的模板
|
||
GIFT_CARD_BOX = (-50, -300, 450, 350) # 上游判断白棉花/已持有时每张卡的范围(相对卡片匹配点, 1440 标定)
|
||
|
||
|
||
def load_gift_keywords(path=GIFT_KEYWORDS_FILE):
|
||
"""读关键词表 {体系: (关键词, ...)}; 以 _ 开头的键是说明。格式不对抛 ValueError。"""
|
||
with open(path, encoding='utf-8') as f:
|
||
raw = json.load(f)
|
||
if not isinstance(raw, dict):
|
||
raise ValueError('顶层应是 {体系: [关键词]}')
|
||
table = {}
|
||
for system, words in raw.items():
|
||
if str(system).startswith('_'):
|
||
continue
|
||
if not isinstance(words, list) or not all(isinstance(w, str) for w in words):
|
||
raise ValueError('%s 的值应是字符串列表' % system)
|
||
table[str(system)] = tuple(w for w in words if normalize_team_name(w))
|
||
return table
|
||
|
||
|
||
def _dict_ocr_lines(auto):
|
||
"""经 AALC 的 _run_ocr_for_text 读整屏: {文本: 坐标}, 同名文本只剩一条。只在 OCR 引擎导入不了时用。"""
|
||
lines = []
|
||
for text, pos in (auto._run_ocr_for_text(my_crop=None) or {}).items():
|
||
try:
|
||
lines.append((str(text), float(pos[0]), float(pos[1])))
|
||
except (TypeError, IndexError, ValueError):
|
||
continue
|
||
return lines
|
||
|
||
|
||
def _ocr_lines(auto):
|
||
"""整屏 OCR 的每一行 [(文本, x, y)]。直接用 OCR 引擎(与 _run_ocr_for_text 同一个引擎、同一张截图、
|
||
同样取框的中心), 不经它的 {文本: 坐标}: 同一句出现在两处(两张卡、顶栏和列表)时 dict 只留一条。"""
|
||
try:
|
||
from module.ocr import ocr as engine
|
||
except Exception:
|
||
return _dict_ocr_lines(auto)
|
||
result = engine.run(auto.screenshot)
|
||
texts, boxes = getattr(result, 'txts', None), getattr(result, 'boxes', None)
|
||
if texts is None or boxes is None:
|
||
return []
|
||
lines = []
|
||
for text, box in zip(texts, boxes):
|
||
try:
|
||
lines.append((str(text), (float(box[0][0]) + float(box[2][0])) / 2,
|
||
(float(box[0][1]) + float(box[2][1])) / 2))
|
||
except (TypeError, IndexError, ValueError):
|
||
continue
|
||
return lines
|
||
|
||
|
||
def gift_card_hits(cards, lines, keywords, scale):
|
||
"""每张卡上命中关键词的行: [[关键词, ...], ...], 与 cards 一一对应。
|
||
|
||
行按坐标归到卡上(范围与上游一致); 落在两张卡的范围里时归给水平方向更近的那张。
|
||
"""
|
||
left, top, right, bottom = (v * scale for v in GIFT_CARD_BOX)
|
||
boxes = [(float(c[0]) + left, float(c[1]) + top, float(c[0]) + right, float(c[1]) + bottom) for c in cards]
|
||
words = [(w, normalize_team_name(w).lower()) for w in keywords]
|
||
hits = [[] for _ in cards]
|
||
for text, x, y in lines:
|
||
clean = normalize_team_name(text).lower()
|
||
found = [w for w, key in words if key and key in clean]
|
||
if not found:
|
||
continue
|
||
inside = [i for i, (x1, y1, x2, y2) in enumerate(boxes) if x1 <= x <= x2 and y1 <= y <= y2]
|
||
if inside:
|
||
i = min(inside, key=lambda i: abs(x - (boxes[i][0] + boxes[i][2]) / 2))
|
||
hits[i].append(found[0])
|
||
return hits
|
||
|
||
|
||
def gift_card_order(hits):
|
||
"""卡的下标, 命中行数多的排前面, 一样多保持原顺序。"""
|
||
return sorted(range(len(hits)), key=lambda i: -len(hits[i]))
|
||
|
||
|
||
def gift_upstream_order(hits):
|
||
"""交给上游的卡顺序(下标), 使上游拼出来的候选顺序等于 gift_card_order。
|
||
|
||
两张卡: 上游按给的顺序挑(只把白棉花/已持有排后), 直接给 gift_card_order。
|
||
三张及以上: 上游逐张看, 认出体系图标的卡 insert(0)(后看的排到最前), 其余 append。
|
||
所以先给没命中的卡(原顺序), 再把命中的卡倒着给, 并让上游的图标判断对命中的卡返回"有":
|
||
拼出来就是 命中多的 → 命中少的 → 只认出图标的 → 其余。
|
||
"""
|
||
order = gift_card_order(hits)
|
||
if len(hits) <= 2:
|
||
return order
|
||
keyed = [i for i in order if hits[i]]
|
||
return [i for i in range(len(hits)) if not hits[i]] + keyed[::-1]
|
||
|
||
|
||
def rank_gift_cards(cards, hits):
|
||
return [cards[i] for i in gift_card_order(hits)]
|
||
|
||
|
||
def install_gift_preference(log=print, env=None):
|
||
"""饰品选择(镜牢路上的 N 选一)先按体系关键词给卡排序。返回原方法, 未安装返回 None。"""
|
||
env = os.environ if env is None else env
|
||
setting = (env.get(GIFT_KEYWORDS_ENV) or '').strip()
|
||
if setting == '0':
|
||
log('[lc_mcp] 饰品体系优先补丁已关闭(%s=0), 沿用 AALC 原逻辑' % GIFT_KEYWORDS_ENV)
|
||
return None
|
||
path = setting or GIFT_KEYWORDS_FILE
|
||
try:
|
||
table = load_gift_keywords(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), 'acquire_ego_gift', None)
|
||
if original is None:
|
||
log('[lc_mcp] 饰品体系优先补丁跳过: 上游没有 Mirror.acquire_ego_gift')
|
||
return None
|
||
if _source_calls(original, 'find_element', GIFT_CARD) is False:
|
||
log('[ERROR] [lc_mcp] 饰品体系优先补丁跳过: 上游 Mirror.acquire_ego_gift 不再调用 find_element(%r), 挂不上'
|
||
% GIFT_CARD)
|
||
return None
|
||
|
||
def prefer(cards, system, keywords):
|
||
"""返回 (交给上游的卡顺序, 要当作认出体系图标的卡的范围左上角)。"""
|
||
scale = cfg.set_win_size / 1440
|
||
hits = gift_card_hits(cards, _ocr_lines(auto), keywords, scale)
|
||
order = gift_card_order(hits)
|
||
by_x = sorted(range(len(cards)), key=lambda i: float(cards[i][0])) # 日志按从左到右编号
|
||
detail = ' '.join('第%d张=%d%s' % (n + 1, len(hits[i]), '(%s)' % '/'.join(hits[i]) if hits[i] else '')
|
||
for n, i in enumerate(by_x))
|
||
first = by_x.index(order[0]) + 1
|
||
if any(hits):
|
||
log('[lc_mcp] 饰品选择(体系 %s): %s; 命中体系关键词, 先看第%d张' % (system, detail, first))
|
||
else:
|
||
log('[lc_mcp] 饰品选择(体系 %s): %s; 未命中体系关键词, 保持原顺序' % (system, detail))
|
||
# 上游随后还会跳过白棉花、把已持有排后, 这里记的是交给上游的第一顺位
|
||
decisions.record('gift', first, 'keyword' if any(hits) else 'no_keyword', system=system,
|
||
hits=[hits[i] for i in by_x])
|
||
keyed = []
|
||
if len(cards) > 2:
|
||
left, top = GIFT_CARD_BOX[0] * scale, GIFT_CARD_BOX[1] * scale
|
||
keyed = [(float(cards[i][0]) + left, float(cards[i][1]) + top) for i in order if hits[i]]
|
||
return [cards[i] for i in gift_upstream_order(hits)], keyed
|
||
|
||
def acquire_ego_gift(self, *args, **kwargs):
|
||
system = getattr(self, 'system', '')
|
||
keywords = table.get(system, ())
|
||
if kwargs.get('type', args[0] if args else 1) != 1 or not keywords: # type=2 是"拒绝饰品"界面
|
||
return original(self, *args, **kwargs)
|
||
real = auto.find_element
|
||
icon = GIFT_ICON % system
|
||
keyed = [] # 这一屏命中关键词的卡(上游 bbox 的左上角); 上游查体系图标时对它们答"有"
|
||
|
||
def is_keyed(crop):
|
||
try:
|
||
x, y = float(crop[0]), float(crop[1])
|
||
except (TypeError, IndexError, ValueError):
|
||
return False
|
||
return any(abs(x - kx) < 1 and abs(y - ky) < 1 for kx, ky in keyed)
|
||
|
||
def find_element(target, *a, **kw):
|
||
if target == icon and keyed and is_keyed(kw.get('my_crop')):
|
||
crop = kw['my_crop']
|
||
return ((float(crop[0]) + float(crop[2])) / 2, (float(crop[1]) + float(crop[3])) / 2)
|
||
found = real(target, *a, **kw)
|
||
find_type = kw.get('find_type', a[0] if a else 'image')
|
||
if target == GIFT_CARD and find_type == 'image_with_multiple_targets':
|
||
keyed.clear()
|
||
if found and len(found) > 1:
|
||
try:
|
||
ordered, keyed[:] = prefer(list(found), system, keywords)
|
||
return ordered
|
||
except Exception as e:
|
||
keyed.clear()
|
||
log('[lc_mcp] 饰品选择: 关键词排序出错(%s: %s), 沿用原顺序' % (type(e).__name__, e))
|
||
return found
|
||
|
||
with _override(auto, 'find_element', find_element):
|
||
return original(self, *args, **kwargs)
|
||
|
||
acquire_ego_gift.__wrapped__ = original # 让后装的补丁查得到上游源码
|
||
mirror_mod.Mirror.acquire_ego_gift = acquire_ego_gift
|
||
log('[lc_mcp] patch: 镜牢饰品选择按体系关键词排序(%s)' % os.path.basename(path))
|
||
return original
|
||
|
||
|
||
# ---------------------------------------------------------------- 事件选项表
|
||
|
||
# 2026-11-14 核对: Mirror.event_handling() 不认事件, 有 "???"/直接拿饰品/优势判定就选它, 否则点第一个选项。
|
||
# 这里在上游每轮挑选项之前(它先 find_element("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 # 一次事件里按表最多点几次(点了没反应时不死循环)
|
||
|
||
|
||
def normalize_event_text(text):
|
||
"""选项文字归一: 与队名相同的归一, 再去掉标点(OCR 常漏句号, 全角半角也不一)。"""
|
||
return ''.join(ch for ch in normalize_team_name(text) if not unicodedata.category(ch).startswith('P'))
|
||
|
||
|
||
def _upstream_source(func):
|
||
"""上游函数的源码; 先顺着 __wrapped__ 剥掉本模块包的几层。拿不到返回 None。"""
|
||
import inspect
|
||
try:
|
||
return inspect.getsource(inspect.unwrap(func))
|
||
except (OSError, TypeError, ValueError):
|
||
return None
|
||
|
||
|
||
def _source_calls(func, method, target):
|
||
"""上游函数源码里有没有 auto.<method>("<target>" 这样的调用; 拿不到源码返回 None。
|
||
|
||
补丁靠拦截这类调用挂进上游流程, 上游改了写法就挂不上; 安装时查一下, 免得悄悄失效。
|
||
"""
|
||
source = _upstream_source(func)
|
||
if source is None:
|
||
return None
|
||
return re.search(r'\.%s\(\s*["\']%s["\']' % (re.escape(method), re.escape(target)), source) is not None
|
||
|
||
|
||
def _source_mentions(func, *needles):
|
||
"""上游函数源码里是否都有这些片段; 拿不到源码返回 None。"""
|
||
source = _upstream_source(func)
|
||
return None if source is None else all(needle in source for needle in needles)
|
||
|
||
|
||
def load_event_choices(path=EVENT_CHOICES_FILE):
|
||
"""读事件表, 返回 [{'name', 'id', 'options', 'text'}]; 格式不对抛 ValueError。
|
||
|
||
options 是同一屏其它选项的原文, 全部出现在画面上才认定是这个事件; text 是要点的那一项。
|
||
"""
|
||
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": [...]}')
|
||
rules = []
|
||
for item in events:
|
||
if not isinstance(item, dict):
|
||
raise ValueError('events 的每一项应是对象')
|
||
name = str(item.get('name') or '?')
|
||
text, others = item.get('text'), item.get('options')
|
||
if not isinstance(text, str) or not normalize_event_text(text):
|
||
raise ValueError('%s 的 text 应是非空字符串(要点的选项原文)' % name)
|
||
if not isinstance(others, list) or not others or \
|
||
not all(isinstance(w, str) and normalize_event_text(w) for w in others):
|
||
raise ValueError('%s 的 options 应是非空字符串列表(同一屏其它选项的原文)' % name)
|
||
rule = {'name': name, 'id': item.get('id'), 'text': normalize_event_text(text),
|
||
'options': tuple(normalize_event_text(w) for w in others)}
|
||
if any(w in rule['text'] or rule['text'] in w for w in rule['options']):
|
||
raise ValueError('%s 的 options 与 text 互相包含, 认不出是哪一项' % 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_event_text(text))
|
||
return [(m, ''.join(t)) for m, t in zip(markers, texts)]
|
||
|
||
|
||
def choose_event_option(rules, texts):
|
||
"""按画面上的选项认事件: 返回 (规则, 要点第几项(0 起))。
|
||
|
||
没认出返回 (None, None); 认出了但要点的那项没读到返回 (规则, None)。
|
||
"""
|
||
for rule in rules:
|
||
if all(any(word in text for text in texts) for word in rule['options']):
|
||
return rule, next((i for i, text in enumerate(texts) if rule['text'] in text), None)
|
||
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
|
||
if _source_calls(original, 'find_element', EVENT_HOOK) is False:
|
||
log('[ERROR] [lc_mcp] 事件选项表补丁跳过: 上游 Mirror.event_handling 不再调用 find_element(%r), 挂不上'
|
||
% EVENT_HOOK)
|
||
return None
|
||
|
||
def decide(state):
|
||
"""按表点了一个选项返回点的位置; 其余情况返回 None 交给上游。"""
|
||
markers = auto.find_element(EVENT_OPTION, find_type='image_with_multiple_targets', threshold=0.75)
|
||
if not markers:
|
||
return None
|
||
options = event_options(markers, _ocr_lines(auto), cfg.set_win_size / 1440)
|
||
texts = tuple(text for _, text in options)
|
||
shown = ' | '.join('%d=%s' % (i + 1, text or '?') for i, text in enumerate(texts))
|
||
|
||
def once(message):
|
||
if (texts, message) in state['logged']:
|
||
return False
|
||
state['logged'].add((texts, message))
|
||
log(message)
|
||
return True
|
||
|
||
rule, i = choose_event_option(rules, texts)
|
||
if rule is None:
|
||
if once('[lc_mcp] 事件选项: %s; 表里没有这个事件, 交给 AALC' % shown):
|
||
decisions.record('event', None, 'not_in_table', options=list(texts))
|
||
return None
|
||
why = None
|
||
if i is None:
|
||
why = '表里要点的「%s」没读到' % rule['text']
|
||
elif state['clicks'] >= EVENT_TEXT_CLICKS:
|
||
why = '这次事件已按表点了 %d 次' % EVENT_TEXT_CLICKS
|
||
if why:
|
||
if once('[lc_mcp] 事件 %s: %s; %s, 交给 AALC' % (rule['name'], shown, why)):
|
||
decisions.record('event', None, 'deferred', event=rule['name'], event_id=rule['id'],
|
||
options=list(texts), why=why)
|
||
return None
|
||
state['clicks'] += 1
|
||
log('[lc_mcp] 事件 %s: %s; 按表选第 %d 项「%s」' % (rule['name'], shown, i + 1, rule['text']))
|
||
decisions.record('event', i + 1, 'text', event=rule['name'], event_id=rule['id'], options=list(texts))
|
||
position = (float(options[i][0][0]), float(options[i][0][1]))
|
||
auto.mouse_click(position[0], position[1])
|
||
return position
|
||
|
||
def event_handling(self, *args, **kwargs):
|
||
state = {'clicks': 0, 'logged': set(), 'clicked': None, 'passed': None}
|
||
real_find, real_click = auto.find_element, auto.mouse_click
|
||
|
||
def find_element(target, *a, **kw):
|
||
if target != EVENT_HOOK:
|
||
return real_find(target, *a, **kw)
|
||
if state['clicked'] is not None:
|
||
# 刚按表点过: 小指良单通模式的 click_option_avoiding_unknown 会再找一次 "???", 别让它再点
|
||
state['clicked'] = None
|
||
return None
|
||
shot = getattr(auto, 'screenshot', None)
|
||
clicked = None
|
||
if shot is None or shot is not state['passed']: # 同一张截图只判断一次(单通模式会再找一次 "???")
|
||
try:
|
||
clicked = decide(state)
|
||
except Exception as e:
|
||
log('[lc_mcp] 事件选项表出错(%s: %s), 交给 AALC' % (type(e).__name__, e))
|
||
state['passed'] = shot if clicked is None else None
|
||
if clicked is None:
|
||
return real_find(target, *a, **kw)
|
||
state['clicked'] = clicked
|
||
return clicked # 上游当作找到了 "???": event_chance -= 1, 重新截图
|
||
|
||
def mouse_click(x, y, *a, **kw):
|
||
if state['clicked'] is not None and (x, y) == state['clicked']:
|
||
state['clicked'] = None # 上游拿返回的位置再点一次; 已经点过了, 吞掉
|
||
return True
|
||
return real_click(x, y, *a, **kw)
|
||
|
||
with _override(auto, 'find_element', find_element), _override(auto, 'mouse_click', mouse_click):
|
||
return original(self, *args, **kwargs)
|
||
|
||
event_handling.__wrapped__ = original # 让后装的补丁查得到上游源码
|
||
mirror_mod.Mirror.event_handling = event_handling
|
||
log('[lc_mcp] patch: 镜牢事件按选项表选择(%s, %d 条)' % (os.path.basename(path), len(rules)))
|
||
return original
|
||
|
||
|
||
# ---------------------------------------------------------------- 决策审计: 商店购买、卡包选择
|
||
|
||
SHOP_PURCHASE = 'mirror/shop/purchase_assets.png'
|
||
SHOP_CONFIRM = 'mirror/road_in_mir/ego_gift_get_confirm_assets.png'
|
||
|
||
|
||
def install_shop_audit(log=print):
|
||
"""商店买东西时记一条审计。只观察, 不改上游的购买逻辑。"""
|
||
try:
|
||
from tasks.mirror.in_shop import Shop
|
||
from module.automation import auto
|
||
except Exception as e:
|
||
log('[lc_mcp] 商店审计跳过: 无法导入 %s' % e)
|
||
return None
|
||
original = getattr(Shop, 'buy_gifts', None)
|
||
if original is None:
|
||
log('[lc_mcp] 商店审计跳过: 上游没有 Shop.buy_gifts')
|
||
return None
|
||
|
||
def buy_gifts(self, *args, **kwargs):
|
||
last = {'item': None}
|
||
real_click, real_pos = auto.click_element, auto.mouse_action_with_pos
|
||
|
||
def click_element(target, *a, **kw):
|
||
result = real_click(target, *a, **kw)
|
||
if result and target == SHOP_PURCHASE:
|
||
# 点到"购买"按钮; 钱不够时按钮匹配不上, 不会走到这里
|
||
decisions.record('shop', last['item'] or 'unknown', 'purchase_clicked',
|
||
system=getattr(self, 'system', None))
|
||
last['item'] = None
|
||
elif result and target != SHOP_CONFIRM:
|
||
last['item'] = os.path.splitext(os.path.basename(str(target)))[0] # 必买项/四级/三级素材
|
||
return result
|
||
|
||
def mouse_action_with_pos(*a, **kw):
|
||
last['item'] = 'by_position' # 本体系饰品是按模板坐标点的
|
||
return real_pos(*a, **kw)
|
||
|
||
with _override(auto, 'click_element', click_element), \
|
||
_override(auto, 'mouse_action_with_pos', mouse_action_with_pos):
|
||
return original(self, *args, **kwargs)
|
||
|
||
buy_gifts.__wrapped__ = original # 让后装的补丁查得到上游源码
|
||
Shop.buy_gifts = buy_gifts
|
||
log('[lc_mcp] patch: 商店购买写入决策审计')
|
||
return original
|
||
|
||
|
||
# ---------------------------------------------------------------- 商店按中文名购买
|
||
|
||
# 上游必买只认 mirror/shop/must_purchase/ 下 5 张图标模板(阈值 0.85)。汉化后商店每一格下面写着饰品中文名
|
||
# (docs/feedback/mirror_20261002_181322/special_shop_missed.png), 这里按名字表 OCR, 命中就点那一格的图标;
|
||
# 之后的"购买 -> 确认"仍是上游同一段循环, 模板留在后面兜底。
|
||
# 挂法: buy_gifts 期间在 must_purchase 最前面临时插几个占位项; 上游 for commodity in must_purchase:
|
||
# auto.click_element(commodity, ...) 点到占位项时改成按名字找。
|
||
SHOP_NAMES_ENV = 'LCP_SHOP_NAMES' # 0 = 关闭; 文件路径 = 用这张表代替默认表
|
||
SHOP_NAMES_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'shop_gifts.json')
|
||
SHOP_BY_NAME = 'lc_mcp/shop_by_name' # 占位项; 不是图片, 只在补丁里认
|
||
SHOP_BY_NAME_SLOTS = 3 # 每轮必买最多按名字买几件
|
||
SHOP_NAME_CLICKS = 4 # 一次进店同一个名字最多点几次(钱不够时上游会重点)
|
||
SHOP_COINS = 'mirror/shop/shop_coins_assets.png' # 上游 re_sort_points 也拿它当商品格的锚点
|
||
SHOP_GRID_BOX = (0, 300, 1250, 900) # 名字行相对金币图标的范围(1440 标定; 实测两行名字在 +409/+716)
|
||
SHOP_NAME_TO_ICON = 155 # 名字行中心到图标中心的纵向距离(1440 标定, 1080 截图实测 116)
|
||
|
||
|
||
def load_shop_gifts(path=SHOP_NAMES_FILE):
|
||
"""读按名字购买的表, 返回归一后的名字元组(靠前的先买); 格式不对抛 ValueError。"""
|
||
with open(path, encoding='utf-8') as f:
|
||
raw = json.load(f)
|
||
gifts = raw.get('gifts') if isinstance(raw, dict) else None
|
||
if not isinstance(gifts, list) or not gifts:
|
||
raise ValueError('顶层应是 {"gifts": [{"name": ...}, ...]}')
|
||
names = []
|
||
for item in gifts:
|
||
name = item.get('name') if isinstance(item, dict) else None
|
||
if not isinstance(name, str) or not normalize_event_text(name):
|
||
raise ValueError('gifts 的每一项应有非空的 name')
|
||
if normalize_event_text(name) in names:
|
||
raise ValueError('%s 重复' % name)
|
||
names.append(normalize_event_text(name))
|
||
return tuple(names)
|
||
|
||
|
||
def shop_name_hits(lines, names, coins, scale):
|
||
"""商品格里名字对上表的行, 按表里的顺序: [(名字, 图标位置), ...]。
|
||
|
||
只认金币图标右下方商品格范围内、与名字完全一致的行(允许强化后缀 +); 子串不算, 免得半截名字误买。
|
||
"""
|
||
left, top, right, bottom = (v * scale for v in SHOP_GRID_BOX)
|
||
x0, y0 = float(coins[0]), float(coins[1])
|
||
found = {}
|
||
for text, x, y in lines:
|
||
if not (x0 + left <= x <= x0 + right and y0 + top <= y <= y0 + bottom):
|
||
continue
|
||
clean = normalize_event_text(text).rstrip('+')
|
||
if clean in names and clean not in found:
|
||
found[clean] = (x, y - SHOP_NAME_TO_ICON * scale)
|
||
return [(name, found[name]) for name in names if name in found]
|
||
|
||
|
||
def install_shop_by_name(log=print, env=None):
|
||
"""商店必买先按中文名找。返回原 Shop.buy_gifts, 未安装返回 None。"""
|
||
env = os.environ if env is None else env
|
||
setting = (env.get(SHOP_NAMES_ENV) or '').strip()
|
||
if setting == '0':
|
||
log('[lc_mcp] 商店按名字购买已关闭(%s=0), 只用 AALC 的图标模板' % SHOP_NAMES_ENV)
|
||
return None
|
||
path = setting or SHOP_NAMES_FILE
|
||
try:
|
||
names = load_shop_gifts(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 in_shop
|
||
from module.automation import auto
|
||
from module.config import cfg
|
||
except Exception as e:
|
||
log('[lc_mcp] 商店按名字购买跳过: 无法导入 %s' % e)
|
||
return None
|
||
shop_cls, must = getattr(in_shop, 'Shop', None), getattr(in_shop, 'must_purchase', None)
|
||
original = getattr(shop_cls, 'buy_gifts', None)
|
||
if original is None or not isinstance(must, list):
|
||
log('[ERROR] [lc_mcp] 商店按名字购买跳过: 上游没有 Shop.buy_gifts 或 must_purchase 列表')
|
||
return None
|
||
if _source_calls(original, 'click_element', 'mirror/shop/purchase_assets.png') is False or \
|
||
_source_mentions(original, 'for commodity in must_purchase', 'auto.click_element(commodity') is False:
|
||
log('[ERROR] [lc_mcp] 商店按名字购买跳过: 上游 Shop.buy_gifts 不再逐个 click_element(must_purchase), 挂不上')
|
||
return None
|
||
|
||
def pick(state, real_find):
|
||
"""按名字点一格返回 True; 画面上没有表里的名字返回 False。"""
|
||
shot = auto.screenshot
|
||
if shot is not None and shot is state['empty_shot']:
|
||
return False # 这张截图刚 OCR 过且没有命中, 后面几个占位项不用再跑
|
||
coins = real_find(SHOP_COINS)
|
||
hits = []
|
||
if coins:
|
||
scale = cfg.set_win_size / 1440
|
||
hits = [(name, pos) for name, pos in shop_name_hits(_ocr_lines(auto), names, coins, scale)
|
||
if state['clicks'].get(name, 0) < SHOP_NAME_CLICKS]
|
||
if not hits:
|
||
state['empty_shot'] = shot
|
||
return False
|
||
name, (x, y) = hits[0]
|
||
state['clicks'][name] = state['clicks'].get(name, 0) + 1
|
||
if state['clicks'][name] == 1:
|
||
log('[lc_mcp] 商店: 按名字找到「%s」, 点它的图标' % name)
|
||
decisions.record('shop', name, 'name_match', on_screen=[n for n, _ in hits])
|
||
auto.mouse_click(x, y)
|
||
return True
|
||
|
||
def buy_gifts(self, *args, **kwargs):
|
||
state = {'clicks': {}, 'empty_shot': None}
|
||
real_find, real_click = auto.find_element, auto.click_element
|
||
|
||
def click_element(target, *a, **kw):
|
||
if target != SHOP_BY_NAME:
|
||
return real_click(target, *a, **kw)
|
||
try:
|
||
return pick(state, real_find)
|
||
except Exception as e:
|
||
log('[lc_mcp] 商店按名字购买出错(%s: %s), 只用图标模板' % (type(e).__name__, e))
|
||
return False
|
||
|
||
must[0:0] = [SHOP_BY_NAME] * SHOP_BY_NAME_SLOTS
|
||
try:
|
||
with _override(auto, 'click_element', click_element):
|
||
return original(self, *args, **kwargs)
|
||
finally:
|
||
must[:] = [item for item in must if item != SHOP_BY_NAME]
|
||
|
||
buy_gifts.__wrapped__ = original # 让后装的补丁查得到上游源码
|
||
shop_cls.buy_gifts = buy_gifts
|
||
log('[lc_mcp] patch: 商店必买先按中文名找(%s, %d 个名字), 图标模板兜底' % (os.path.basename(path), len(names)))
|
||
return original
|
||
|
||
|
||
THEME_PACK_PICK = re.compile(r'此次选择卡包关键词[::]\s*(\S+)')
|
||
THEME_PACK_WEIGHTS = '当前主题包权重列表'
|
||
THEME_PACK_SOURCE = 'select_theme_pack.py'
|
||
|
||
|
||
class _LogCapture(logging.Handler):
|
||
"""收集某个源文件打出的 AALC 日志。"""
|
||
|
||
def __init__(self, source):
|
||
super().__init__(logging.DEBUG)
|
||
self.source = source
|
||
self.messages = []
|
||
|
||
def emit(self, record):
|
||
if os.path.basename(record.pathname or '') == self.source:
|
||
try:
|
||
self.messages.append(record.getMessage())
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def theme_pack_decision(messages):
|
||
"""从上游 select_theme_pack 的日志里取 (卡包, 理由, 权重列表); 没选就返回 None。"""
|
||
weights = next((m.split(':', 1)[-1] for m in reversed(messages) if m.startswith(THEME_PACK_WEIGHTS)), None)
|
||
for message in reversed(messages):
|
||
if '最左边的(活动)卡包' in message:
|
||
return '最左边的活动卡包', 'event_pack', weights
|
||
match = THEME_PACK_PICK.search(message)
|
||
if match:
|
||
return match.group(1), 'highest_weight' if '无匹配最低阈值' in message else 'preferred', weights
|
||
return None
|
||
|
||
|
||
def install_theme_pack_audit(log=print):
|
||
"""卡包选完后按上游自己的日志记一条审计。只观察, 不改选择。"""
|
||
try:
|
||
from tasks.mirror import mirror as mirror_mod
|
||
except Exception as e:
|
||
log('[lc_mcp] 卡包审计跳过: 无法导入 %s' % e)
|
||
return None
|
||
original = getattr(mirror_mod, 'select_theme_pack', None)
|
||
if original is None:
|
||
log('[lc_mcp] 卡包审计跳过: mirror 模块没有 select_theme_pack')
|
||
return None
|
||
|
||
def select_theme_pack(*args, **kwargs):
|
||
capture = _LogCapture(THEME_PACK_SOURCE)
|
||
logger = logging.getLogger('AALC')
|
||
logger.addHandler(capture)
|
||
try:
|
||
return original(*args, **kwargs)
|
||
finally:
|
||
logger.removeHandler(capture)
|
||
decision = theme_pack_decision(capture.messages)
|
||
if decision:
|
||
pack, reason, weights = decision
|
||
decisions.record('theme_pack', pack, reason, weights=weights,
|
||
floor=kwargs.get('floor', args[1] if len(args) > 1 else None))
|
||
|
||
mirror_mod.select_theme_pack = select_theme_pack
|
||
log('[lc_mcp] patch: 卡包选择写入决策审计')
|
||
return original
|