Files
lc-mcp/lc_mcp/aalc_patches.py
T
ywsandClaude Opus 5.5 72d2ca1a5b AALC 升级到 V1.6.1 并按零协汉化核对镜牢补丁
- 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>
2026-11-14 08:43:27 +00:00

1260 lines
55 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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': ('打击',),
}
# 左侧编队列表的 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), ...]。用列表而不是 dict: 同名条目(列表里的队名和顶栏队名)
落在不同位置, dict 会把它们覆盖成一条。不用 my_crop: 裁剪区的坐标系不可靠。"""
ocr = auto._run_ocr_for_text(my_crop=None)
result = []
for text, pos in (ocr or {}).items():
clean = str(text).replace(' ', '').strip()
if not clean:
continue
try:
x, y = float(pos[0]), float(pos[1])
except (TypeError, IndexError, ValueError):
continue
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)
# 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=4):
"""在编队列表里按名字点选。成功返回 True, 没找到返回 False。
名字先归一化(空白/全半角/常见误读); 精确匹配优先, 否则接受唯一的"名字+后缀"。
没找到时把每一屏看到的名字打进日志。
"""
if auto.take_screenshot() is None:
return False
if not auto.find_element('teams/identify_assets.png'):
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)
_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, names)
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, '/'.join(names), ', ' + reason if reason else '',
'/'.join(_list_names(items)) or '(空)'))
_scroll_team_list(auto, -1, times=3)
log('[lc_mcp] 编队列表里没找到 %s(共 %d 轮)' % ('/'.join(names), rounds))
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)
wanted['names'] = SYSTEM_TEAM_NAMES.get(getattr(self, 'system', ''), ())
log('[lc_mcp] 镜牢体系 %s -> 目标编队 %s'
% (getattr(self, 'system', '?'), '/'.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)
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_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 _ocr_lines(auto):
"""整屏 OCR 的每一行 [(文本, x, y)]。直接用 OCR 引擎, 不经 _run_ocr_for_text 的 {文本: 坐标}:
同一句描述出现在两张卡上时 dict 只留一条。引擎不可用时退回 _team_ocr。"""
try:
from module.ocr import ocr as engine
except Exception:
return _team_ocr(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 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):
hits = gift_card_hits(cards, _ocr_lines(auto), keywords, cfg.set_win_size / 1440)
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])
return [cards[i] for i in order]
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
def find_element(target, *a, **kw):
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' and found and len(found) > 1:
try:
return prefer(list(found), system, keywords)
except Exception as e:
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 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}
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
try:
clicked = decide(state)
except Exception as e:
log('[lc_mcp] 事件选项表出错(%s: %s), 交给 AALC' % (type(e).__name__, e))
clicked = 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
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