run_task(task="mirror", strategy="rabbit_hole") 时生效, 不带 strategy 时不装: - 选队按 rabbit_hole.json 的编队名(默认「兔子洞」); - 每回合 P → 长按浮士德打开 E.G.O 列表 → OCR 找「空洞」, 第一回合长按卡片超频 (侵蚀「空洞」直接打人; 普通「空洞」只叠弹孔), 其余回合单击 → Enter; 审计 battle/hollow 记 overclock/ego/ego_unavailable/no_option; - 路线卡包加分: 赌徒 → 地狱鸡 → 去·海·边 → 憎恶与绝望 → 2号线(OurPlay 全程困难路线), 按 AALC 默认权重模拟每层都选到路线卡包。 长按点 press_at 出厂未校准: 只记 [ERROR], 照常 P+Enter。 机制和超频操作按零协游戏文本/教程核实; 编队、路线按 codex 检索的 OurPlay/Reddit 攻略。 实机校准步骤见 docs/feedback/2026-11-15/RABBIT-HOLE.md, 台账 R-08。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2159 lines
101 KiB
Python
2159 lines
101 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
|
||
|
||
find_element.__wrapped__ = original
|
||
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 attempt in range(3):
|
||
# 选队页刚加载时图标和列表可能还没出来: 等一下、重新截图再认, 别对着同一张图认三次
|
||
if attempt:
|
||
time.sleep(0.8)
|
||
if auto.take_screenshot() is None:
|
||
continue
|
||
if auto.find_element(TEAM_SCREEN_ICON) or _looks_like_team_screen(auto):
|
||
break
|
||
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, names=None):
|
||
"""镜牢选队改成"按队伍体系对应的中文名"在列表里点。
|
||
|
||
AALC 原生只认 编队#N; 本账号的编队是自定义名字(流血/斩击/...), 原生逻辑永远选不上。
|
||
names 给了就不看体系, 直接按这些名字选(兔子洞这类固定编队的打法用)。
|
||
"""
|
||
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': (), 'enter_failed': False}
|
||
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'] = tuple(names) if names else (SYSTEM_TEAM_NAMES.get(system, ())
|
||
+ TEAM_PREFERENCES.get(system, ()))
|
||
wanted['enter_failed'] = False
|
||
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):
|
||
names = wanted['names']
|
||
if (target != ENTER_ASSET or not names or wanted['enter_failed']
|
||
or kwargs.get('click') is False):
|
||
return original_click(target, *args, **kwargs)
|
||
# 镜牢主循环和 road_to_mir 每轮都会问一次「进入」; 先用模板确认按钮真在画面上,
|
||
# 再做整屏 OCR, 不然每轮白跑一次 OCR。没找到时上游也是返回 False。
|
||
if not original_click(target, *args, **dict(kwargs, click=False)):
|
||
return False
|
||
try:
|
||
if _looks_like_team_screen(auto) and not _header_is(auto, names):
|
||
log('[lc_mcp] 入场前切队伍: %s' % '/'.join(names))
|
||
if not _select_team_by_name(auto, names, log=log):
|
||
# 显式报错, 但不拦着进入: 拦住的话上游会一直点「进入」、一直重翻列表。
|
||
# 本局不再重试, 免得每一轮都把列表从头翻一遍。
|
||
wanted['enter_failed'] = True
|
||
log('[ERROR] [lc_mcp] 入场前没切到 %s, 本局按游戏当前编队进入' % '/'.join(names))
|
||
except Exception as e:
|
||
log('[lc_mcp] 入场前切队伍出错: %s: %s' % (type(e).__name__, e))
|
||
return original_click(target, *args, **kwargs)
|
||
|
||
click_element.__wrapped__ = original_click
|
||
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 时不装这个补丁, 完全回到原简单键盘寻路
|
||
# 连续这么多个节点按键都没进去, 本次任务就不再按键寻路(直接交给 AALC 的常规寻路)。
|
||
# 2026-11-14 实机 24/24 失败, 每个节点白按 5 次键 ≈ 5 秒; 进去一次就清零重新计。
|
||
ROAD_KEY_GIVE_UP = 3
|
||
|
||
|
||
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)
|
||
|
||
state = {'fails': 0, 'off': False}
|
||
|
||
def search_road_simple_keyboard():
|
||
if not cfg.mirror_keyboard_navigation:
|
||
return original() # 上游会说明需要开启键盘寻路
|
||
if state['off']:
|
||
return False # 上游接着走常规寻路
|
||
entered = _typed_keyboard_road()
|
||
if entered:
|
||
state['fails'] = 0
|
||
return entered
|
||
state['fails'] += 1
|
||
if state['fails'] >= ROAD_KEY_GIVE_UP:
|
||
state['off'] = True
|
||
log('[lc_mcp] 键盘寻路: 连续 %d 个节点按键都没进去, 本次任务不再按键寻路, 交给 AALC 常规寻路'
|
||
% state['fails'])
|
||
decisions.record('road', None, 'keyboard_off', fails=state['fails'])
|
||
return entered
|
||
|
||
def _typed_keyboard_road():
|
||
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
|
||
|
||
|
||
# 取到行尾: 卡包按体系加分会加带空格的全名键(如「WARP快车谋杀案 复刻」), \S+ 会截在空格前
|
||
THEME_PACK_PICK = re.compile(r'此次选择卡包关键词[::]\s*(.+?)\s*$', re.M)
|
||
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
|
||
extra = {}
|
||
if pack in THEME_PACK_BOOSTED: # 选中的是按体系加过分的卡包
|
||
extra['system_bonus'] = THEME_PACK_BOOSTED[pack]
|
||
decisions.record('theme_pack', pack, reason, weights=weights,
|
||
floor=kwargs.get('floor', args[1] if len(args) > 1 else None), **extra)
|
||
|
||
select_theme_pack.__wrapped__ = original
|
||
mirror_mod.select_theme_pack = select_theme_pack
|
||
log('[lc_mcp] patch: 卡包选择写入决策审计')
|
||
return original
|
||
|
||
|
||
# ---------------------------------------------------------------- 卡包按体系加分
|
||
|
||
# BACKLOG R-01 / ISSUES I-08: theme_pack_list.yaml 几乎全是 0, 所有卡包并列最高分, 每层都拿最左边那个。
|
||
# 这里在 AALC 选卡包时把它的权重表临时加上「卡包对当局体系的加分」(lc_mcp/data/theme_pack_systems.json),
|
||
# 不改配置文件。AALC 拿卡包卡面 OCR 文字按权重表的键做子串匹配、取第一个命中的键, 所以加过分的键排在最前面。
|
||
THEME_PACK_SYSTEMS_ENV = 'LCP_THEME_PACK_SYSTEMS' # 0 = 关闭; 文件路径 = 用这张表代替默认表
|
||
THEME_PACK_SYSTEMS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'theme_pack_systems.json')
|
||
THEME_PACK_UNKNOWN_KEYS = ('未知', 'unknown') # AALC 认不出卡包时的兜底权重键, 不当卡包名用
|
||
THEME_PACK_BOOSTED = {} # 本次选卡包加过分的键 → {pack, system, from, to}; 卡包审计记到 decisions 里
|
||
|
||
|
||
def load_theme_pack_systems(path=THEME_PACK_SYSTEMS_FILE):
|
||
"""读卡包体系表, 返回 (bonus, packs); 格式不对抛 ValueError。
|
||
|
||
community 里的推荐/避开按卡包中文名挂到对应卡包上(recommend / avoid 两个体系集合, avoid 里 '*' 表示所有体系)。
|
||
"""
|
||
with open(path, encoding='utf-8') as fh:
|
||
data = json.load(fh)
|
||
bonus = data.get('bonus') if isinstance(data, dict) else None
|
||
if not isinstance(bonus, dict) or not isinstance(bonus.get('featured'), int) \
|
||
or not isinstance(bonus.get('unique'), list) or not bonus['unique'] \
|
||
or not all(isinstance(v, int) for v in bonus['unique']) \
|
||
or not all(isinstance(bonus.get(k, 0), int) for k in ('recommend', 'avoid')):
|
||
raise ValueError('bonus 要有整数 featured、非空整数列表 unique, recommend/avoid 也要是整数')
|
||
packs = data.get('packs')
|
||
if not isinstance(packs, list) or not packs:
|
||
raise ValueError('packs 必须是非空列表')
|
||
systems = set(SYSTEM_TEAM_NAMES)
|
||
loaded = {}
|
||
for pack in packs:
|
||
if not isinstance(pack, dict) or not str(pack.get('zh') or '').strip() or not str(pack.get('en') or '').strip():
|
||
raise ValueError('卡包要有 zh 和 en 名字: %r' % (pack,))
|
||
if not set(pack.get('featured') or ()) <= systems or not set(pack.get('unique') or {}) <= systems:
|
||
raise ValueError('卡包 %s 的体系名不认识' % pack['zh'])
|
||
if not all(isinstance(n, int) and n > 0 for n in (pack.get('unique') or {}).values()):
|
||
raise ValueError('卡包 %s 的专属饰品件数必须是正整数' % pack['zh'])
|
||
loaded[pack['zh']] = dict(pack, recommend=set(), avoid=set())
|
||
community = data.get('community') or {}
|
||
for field, allowed in (('recommend', systems), ('avoid', systems | {'*'})):
|
||
for entry in community.get(field) or ():
|
||
name = entry.get('pack') if isinstance(entry, dict) else None
|
||
wanted = set(entry.get('systems') or ()) if isinstance(entry, dict) else set()
|
||
if name not in loaded:
|
||
raise ValueError('community.%s 里的卡包 %r 不在 packs 里' % (field, name))
|
||
if not wanted or not wanted <= allowed:
|
||
raise ValueError('community.%s 里 %s 的体系不对: %r' % (field, name, sorted(wanted)))
|
||
loaded[name][field] |= wanted
|
||
result = {'featured': bonus['featured'], 'unique': tuple(bonus['unique']),
|
||
'recommend': bonus.get('recommend', 0), 'avoid': bonus.get('avoid', 0)}
|
||
return result, list(loaded.values())
|
||
|
||
|
||
def theme_pack_bonus(pack, system, bonus):
|
||
"""卡包对体系的加分(可以是负的)。
|
||
|
||
体系包给 featured 档, 有这个体系的专属饰品按件数给 unique 档, 社区推荐给 recommend 档, 取最大;
|
||
社区说这个体系走它不划算(avoid 里有这个体系)就不加; 速刷要避开的(avoid 里有 '*')再减 avoid。
|
||
打法指定的路线卡包(pack['route'] 是它的加分, 如兔子洞)最后算, 至少给这么多, 不受体系和 avoid 影响。
|
||
"""
|
||
score = bonus['featured'] if system in (pack.get('featured') or ()) else 0
|
||
count = (pack.get('unique') or {}).get(system, 0)
|
||
if count:
|
||
score = max(score, bonus['unique'][min(count, len(bonus['unique']) - 1)])
|
||
if system in (pack.get('recommend') or ()):
|
||
score = max(score, bonus.get('recommend', 0))
|
||
avoid = pack.get('avoid') or ()
|
||
if system in avoid:
|
||
score = min(score, 0)
|
||
if '*' in avoid:
|
||
score -= bonus.get('avoid', 0)
|
||
if pack.get('route'):
|
||
score = max(score, pack['route'])
|
||
return score
|
||
|
||
|
||
def _pack_text(text):
|
||
"""AALC find_str_in_text 的比较方式: 去空格、不分大小写。"""
|
||
return str(text).replace(' ', '').lower()
|
||
|
||
|
||
def boost_theme_pack_weights(weights, packs, system, bonus, language='zh_cn', hard_mode=None):
|
||
"""把体系加分加进 AALC 的卡包权重表。返回 (新表, {键: {packs, system, from, to}})。
|
||
|
||
hard_mode 给了(True/False)时, 只看这个难度会出现的卡包(表里 hard/normal 楼层不为空的): 活动专用包、
|
||
只在困难出现的复刻不会出现在普通模式, 不该拿来和同名短键的普通卡包「冲突」。
|
||
|
||
一个键会命中所有名字里含有它的卡包(AALC 的「谋杀」同时是 WARP快车谋杀案 原版和复刻), 所以键的加分
|
||
取这些卡包里离 0 最近的那个(都加分取最少的, 都减分取减得最少的); 有一个不变、或者有加有减, 就不动这个键,
|
||
免得连带改了别的卡包。某个卡包的分没被已有的键表达出来(复刻比原版多、或者 AALC 表里没有它)时,
|
||
再用卡包全名做键。原权重: 键在表里就用表里的; 全名键用这个卡包被 AALC 认成的那个键的分, 认不出来按
|
||
「未知」。改过分的键按长度从长到短排在最前面: AALC 按表的顺序取第一个命中的键, 全名(更具体)要先于短片段。
|
||
"""
|
||
field = 'en' if language == 'en' else 'zh'
|
||
unknown = next((weights[k] for k in THEME_PACK_UNKNOWN_KEYS if k in weights), -5)
|
||
if hard_mode is not None:
|
||
packs = [pack for pack in packs if pack.get('hard' if hard_mode else 'normal')]
|
||
scored = [(pack, theme_pack_bonus(pack, system, bonus), _pack_text(pack[field])) for pack in packs]
|
||
aalc_keys = [k for k in weights if k not in THEME_PACK_UNKNOWN_KEYS and _pack_text(k)]
|
||
|
||
def holders(key):
|
||
return [(pack, extra) for pack, extra, name in scored if _pack_text(key) in name]
|
||
|
||
def key_bonus(key):
|
||
extras = [extra for _, extra in holders(key)]
|
||
if extras and all(e > 0 for e in extras):
|
||
return min(extras)
|
||
if extras and all(e < 0 for e in extras):
|
||
return max(extras)
|
||
return 0
|
||
|
||
changed, info = {}, {}
|
||
|
||
def add(key, start, extra):
|
||
changed[key] = start + extra
|
||
info[key] = {'packs': [pack['zh'] for pack, _ in holders(key)], 'system': system,
|
||
'from': start, 'to': start + extra}
|
||
|
||
for key in aalc_keys:
|
||
extra = key_bonus(key)
|
||
if extra:
|
||
add(key, weights[key], extra)
|
||
for pack, extra, name in scored:
|
||
if not extra:
|
||
continue
|
||
own = [k for k in aalc_keys if _pack_text(k) in name]
|
||
if any(key_bonus(k) == extra for k in own):
|
||
continue # 已有的键已经表达了这个卡包的分
|
||
full = pack[field]
|
||
full_extra = key_bonus(full)
|
||
if full_extra and full not in changed:
|
||
add(full, weights.get(full, weights[own[0]] if own else unknown), full_extra)
|
||
ordered = sorted(changed, key=lambda k: -len(_pack_text(k)))
|
||
result = {k: changed[k] for k in ordered}
|
||
result.update((k, v) for k, v in weights.items() if k not in changed)
|
||
return result, {k: info[k] for k in ordered}
|
||
|
||
|
||
def install_theme_pack_systems(log=print, env=None, route=None, route_name='路线'):
|
||
"""镜牢选卡包时按当局体系给卡包加分。返回原 select_theme_pack, 未安装返回 None。
|
||
|
||
route 是打法指定的路线卡包 {中文名: 加分}(如兔子洞的 rabbit_hole.json theme_packs), 每个至少加这么多,
|
||
当局没有体系也照加。
|
||
"""
|
||
env = os.environ if env is None else env
|
||
setting = env.get(THEME_PACK_SYSTEMS_ENV, '').strip()
|
||
if setting == '0':
|
||
log('[lc_mcp] 卡包按体系加分已关闭(%s=0)' % THEME_PACK_SYSTEMS_ENV)
|
||
return None
|
||
path = setting or THEME_PACK_SYSTEMS_FILE
|
||
try:
|
||
bonus, packs = load_theme_pack_systems(path)
|
||
except (OSError, ValueError) as e:
|
||
log('[ERROR] [lc_mcp] 卡包体系表读不了(%s): %s, 卡包按 AALC 原权重选' % (path, e))
|
||
return None
|
||
route = dict(route or {})
|
||
if route:
|
||
known = {pack['zh'] for pack in packs}
|
||
missing = [name for name in route if name not in known]
|
||
if missing:
|
||
log('[ERROR] [lc_mcp] %s卡包不在卡包表里, 不加分: %s' % (route_name, '/'.join(missing)))
|
||
route = {name: extra for name, extra in route.items() if name in known}
|
||
packs = [dict(pack, route=route[pack['zh']]) if pack['zh'] in route else pack for pack in packs]
|
||
try:
|
||
import inspect
|
||
from tasks.mirror import mirror as mirror_mod
|
||
from tasks.mirror import select_theme_pack as theme_pack_mod
|
||
except Exception as e:
|
||
log('[lc_mcp] 卡包按体系加分跳过: 无法导入 %s' % e)
|
||
return None
|
||
original = getattr(mirror_mod, 'select_theme_pack', None)
|
||
theme_list = getattr(theme_pack_mod, 'theme_list', None)
|
||
try:
|
||
source = inspect.getsource(theme_pack_mod) # 上游装饰器没用 functools.wraps, 只能看整个模块
|
||
except (OSError, TypeError):
|
||
source = None
|
||
if original is None or theme_list is None or (
|
||
source is not None and 'theme_list.get_effective_theme_pack_list(' not in source):
|
||
log('[ERROR] [lc_mcp] 上游 select_theme_pack 不再从 theme_list.get_effective_theme_pack_list 取权重, '
|
||
'卡包按体系加分挂不上, 跳过')
|
||
return None
|
||
state = {'system': None}
|
||
original_init = mirror_mod.Mirror.__init__
|
||
|
||
def __init__(self, *args, **kwargs):
|
||
original_init(self, *args, **kwargs)
|
||
state['system'] = getattr(self, 'system', None)
|
||
|
||
def select_theme_pack(*args, **kwargs):
|
||
THEME_PACK_BOOSTED.clear()
|
||
system = state['system']
|
||
if system not in SYSTEM_TEAM_NAMES:
|
||
if not route:
|
||
return original(*args, **kwargs)
|
||
system = None # 没有体系: 只加路线分(体系包、专属饰品、社区推荐都按 None 算 0)
|
||
real = theme_list.get_effective_theme_pack_list
|
||
|
||
def get_effective_theme_pack_list(hard_mode, language, *more, **kw):
|
||
weights = real(hard_mode, language, *more, **kw)
|
||
try:
|
||
result, info = boost_theme_pack_weights(dict(weights), packs, system, bonus, language,
|
||
bool(hard_mode))
|
||
except Exception as e:
|
||
log('[lc_mcp] 卡包按体系加分出错(%s: %s), 用 AALC 原权重' % (type(e).__name__, e))
|
||
return weights
|
||
if info:
|
||
log('[lc_mcp] 卡包按体系 %s%s 加分: %s' % (
|
||
system or '(无)', ('+' + route_name) if route else '', ', '.join(
|
||
'%s %d→%d' % (key, item['from'], item['to']) for key, item in info.items())))
|
||
THEME_PACK_BOOSTED.update(info)
|
||
return result
|
||
|
||
with _override(theme_list, 'get_effective_theme_pack_list', get_effective_theme_pack_list):
|
||
return original(*args, **kwargs)
|
||
|
||
select_theme_pack.__wrapped__ = original
|
||
mirror_mod.Mirror.__init__ = __init__
|
||
mirror_mod.select_theme_pack = select_theme_pack
|
||
log('[lc_mcp] patch: 镜牢卡包按体系加分(%s, %d 个卡包%s)' % (
|
||
os.path.basename(path), len(packs),
|
||
', %s %s' % (route_name, ' '.join('%s+%d' % item for item in route.items())) if route else ''))
|
||
return original
|
||
|
||
|
||
# ---------------------------------------------------------------- 「获得E.G.O饰品」确认弹窗兜底
|
||
|
||
# ISSUES I-06(2026-11-14 18:45): 开局「获得E.G.O饰品」弹窗上 AALC 一直点确认模板的匹配点(模板是勾号,
|
||
# 1280x720 下约 (602,525)), 弹窗不关, 连点了 5 分钟; 手动点按钮中心 (640,530) 一次就过。
|
||
# 上游 select_init_ego_gift 的 loop_count 退出判断在循环底部, 点到确认就 continue, 永远走不到;
|
||
# 镜牢主循环点到确认也是 continue, 同样不减计数。所以兜底放在 click_element 这一层, 两处都管:
|
||
# 连续命中第 3 次起改点按钮中心, 连续 20 次还在就记 [ERROR] 结束任务。
|
||
GIFT_CONFIRM = 'mirror/road_in_mir/ego_gift_get_confirm_assets.png'
|
||
GIFT_CONFIRM_BUTTON_DX = 76 # 勾号模板中心 → 按钮中心的横向距离(1440 标定; 1280x720 实测 602 → 640)
|
||
GIFT_CONFIRM_SHIFT_AT = 3 # 连续第几次命中起改点按钮中心(正常一个弹窗点 1~2 次就关)
|
||
GIFT_CONFIRM_LIMIT = 20 # 连续命中这么多次弹窗还在: 记 [ERROR] 并结束任务(卡住时约 1.5 秒一次)
|
||
GIFT_CONFIRM_GAP = 60 # 两次命中隔了这么多秒就不算连续
|
||
|
||
|
||
class TaskAbort(BaseException):
|
||
"""补丁判断再跑只会空转时抛出; aalc_task 在最外层接住, 记 [ERROR] 后按未完成退出。
|
||
|
||
不继承 Exception: AALC 的 onetime_mir_process 会吞掉 Exception 再开一局, 弹窗还在, 新的一局接着空转。
|
||
"""
|
||
|
||
|
||
def install_gift_confirm_guard(log=print, clock=time.monotonic):
|
||
"""「获得E.G.O饰品」确认点了不关时换落点, 再不行就结束任务。返回原 click_element, 未安装返回 None。
|
||
|
||
"连续"= 中间没有别的 click_element 点成功过、确认也一直找得到。别的东西点成功、确认没找到、
|
||
或者隔了 GIFT_CONFIRM_GAP 秒, 都清零重新计。
|
||
"""
|
||
try:
|
||
from module.automation import auto
|
||
from module.config import cfg
|
||
except Exception as e:
|
||
log('[lc_mcp] 饰品确认兜底跳过: 无法导入 %s' % e)
|
||
return None
|
||
real_click = getattr(auto, 'click_element', None)
|
||
if real_click is None:
|
||
log('[lc_mcp] 饰品确认兜底跳过: auto 没有 click_element')
|
||
return None
|
||
state = {'streak': 0, 'last': None}
|
||
|
||
def click_element(target, *args, **kwargs):
|
||
lookup_only = kwargs.get('click') is False
|
||
if target != GIFT_CONFIRM or lookup_only:
|
||
result = real_click(target, *args, **kwargs)
|
||
if result and not lookup_only:
|
||
state['streak'] = 0
|
||
return result
|
||
now = clock()
|
||
if state['last'] is not None and now - state['last'] > GIFT_CONFIRM_GAP:
|
||
state['streak'] = 0
|
||
shifting = state['streak'] + 1 >= GIFT_CONFIRM_SHIFT_AT
|
||
result = real_click(target, *args, **(dict(kwargs, click=False) if shifting else kwargs))
|
||
if not result:
|
||
state['streak'] = 0
|
||
return result
|
||
state['streak'] += 1
|
||
state['last'] = now
|
||
streak = state['streak']
|
||
if not shifting:
|
||
return result
|
||
if streak >= GIFT_CONFIRM_LIMIT:
|
||
log('[ERROR] [lc_mcp] 「获得E.G.O饰品」确认连点 %d 次弹窗还在, 结束任务(免得空转到超时)' % streak)
|
||
decisions.record('gift_confirm', None, 'stuck', clicks=streak)
|
||
raise TaskAbort('「获得E.G.O饰品」弹窗关不掉(连点 %d 次)' % streak)
|
||
x = int(round(result[0] + GIFT_CONFIRM_BUTTON_DX * cfg.set_win_size / 1440))
|
||
y = int(round(result[1]))
|
||
if streak == GIFT_CONFIRM_SHIFT_AT:
|
||
log('[lc_mcp] 「获得E.G.O饰品」确认点了 %d 次还在, 改点按钮中心 (%d,%d)' % (streak - 1, x, y))
|
||
decisions.record('gift_confirm', 'button_center', 'repeated', clicks=streak - 1)
|
||
auto.mouse_click(x, y)
|
||
return True
|
||
|
||
click_element.__wrapped__ = real_click
|
||
auto.click_element = click_element
|
||
log('[lc_mcp] patch: 「获得E.G.O饰品」确认连点不关时改点按钮中心, %d 次还在就结束任务' % GIFT_CONFIRM_LIMIT)
|
||
return real_click
|
||
|
||
|
||
# ---------------------------------------------------------------- 按键: 带扫描码、按住再松开
|
||
|
||
# ISSUES I-05: 2026-11-14 镜牢键盘寻路 24/24 没进去(旧版只按 ↑ 也是 32/32)。AALC 前台模式的 key_press
|
||
# 是 pyautogui.press: keybd_event 的扫描码填 0、方向键不带扩展键标志, 按下抬起紧挨着。上游在后台模式的
|
||
# _make_key_lparam 注释里写了"Unity 6+ 会校验 scan code 和 extended flag", 本仓库 aalc_engine 也记过
|
||
# Unity 会吞掉同一帧里的 down/up。这里把前台按键换成带扫描码和扩展键标志的 keybd_event,
|
||
# 各模式都按住 KEY_HOLD 秒再松开。
|
||
KEY_HOLD = 0.12 # 与 aalc_engine 的 key 工具一致
|
||
KEY_HOLD_ENV = 'LCP_KEY_HOLD' # 0 = 不装, 按键完全走 AALC 原逻辑
|
||
KEYEVENTF_EXTENDEDKEY = 0x0001
|
||
KEYEVENTF_KEYUP = 0x0002
|
||
MAPVK_VK_TO_VSC = 0
|
||
|
||
|
||
def press_vk(user32, vk, extended, hold=KEY_HOLD):
|
||
"""向前台窗口按一次键: keybd_event 带扫描码(方向键等再带扩展键标志), 按住 hold 秒再松开。"""
|
||
scan = user32.MapVirtualKeyW(vk, MAPVK_VK_TO_VSC) & 0xFF
|
||
flags = KEYEVENTF_EXTENDEDKEY if extended else 0
|
||
user32.keybd_event(vk, scan, flags, 0)
|
||
try:
|
||
time.sleep(hold)
|
||
finally:
|
||
user32.keybd_event(vk, scan, flags | KEYEVENTF_KEYUP, 0)
|
||
return scan
|
||
|
||
|
||
def install_key_hold(log=print, env=None, user32=None):
|
||
"""改 AALC 各 Windows 输入后端的 key_press。返回 {类名: 原 key_press}, 未安装返回 None。
|
||
|
||
前台(Input): 先确认游戏窗口在前台(不在就激活一次, 还不在就不发, 免得按到别的程序里),
|
||
再用 press_vk 发。后台(BackgroundInput / WindowMoveInput): 仍用上游自己的 key_down/key_up
|
||
消息(扫描码上游已经填对), 只在中间按住 KEY_HOLD 秒。不认识的键名交回原逻辑。模拟器不动。
|
||
"""
|
||
env = os.environ if env is None else env
|
||
if env.get(KEY_HOLD_ENV) == '0':
|
||
log('[lc_mcp] 按键补丁已关闭(%s=0), 按键走 AALC 原逻辑' % KEY_HOLD_ENV)
|
||
return None
|
||
try:
|
||
from module.automation.input_handlers import input as input_mod
|
||
from module.game_and_screen import screen
|
||
except Exception as e:
|
||
log('[lc_mcp] 按键补丁跳过: 无法导入 %s' % e)
|
||
return None
|
||
key_list = getattr(input_mod, 'key_list', None)
|
||
extended_vks = getattr(input_mod, 'EXTENDED_KEY_VKS', None)
|
||
if not key_list or extended_vks is None:
|
||
log('[lc_mcp] 按键补丁跳过: 上游没有 key_list / EXTENDED_KEY_VKS')
|
||
return None
|
||
originals = {}
|
||
|
||
foreground = getattr(input_mod, 'Input', None)
|
||
if foreground is not None:
|
||
original_fg = foreground.key_press
|
||
if _source_mentions(original_fg, 'pyautogui.press') is False:
|
||
log('[ERROR] [lc_mcp] 按键补丁: 上游前台 Input.key_press 不再用 pyautogui.press, 挂不上, 前台按键照旧')
|
||
else:
|
||
if user32 is None:
|
||
import ctypes
|
||
user32 = ctypes.windll.user32
|
||
|
||
def key_press(self, key):
|
||
name = str(key).lower()
|
||
vk = key_list.get(name)
|
||
if vk is None:
|
||
return original_fg(self, key)
|
||
handle = screen.handle
|
||
if not handle.isActive:
|
||
try:
|
||
handle.setForeground()
|
||
except Exception as e:
|
||
log('[lc_mcp] 按键前激活游戏窗口出错: %s: %s' % (type(e).__name__, e))
|
||
time.sleep(0.15)
|
||
if not handle.isActive:
|
||
log('[lc_mcp] 按键 %s 没发: 游戏窗口不在前台(避免按到别的程序里)' % name)
|
||
return None
|
||
press_vk(user32, vk, vk in extended_vks)
|
||
return None
|
||
|
||
key_press.__wrapped__ = original_fg
|
||
foreground.key_press = key_press
|
||
originals['Input'] = original_fg
|
||
|
||
for name in ('BackgroundInput', 'WindowMoveInput'):
|
||
cls = getattr(input_mod, name, None)
|
||
if cls is None or not all(hasattr(cls, m) for m in ('set_active', 'key_down', 'key_up')):
|
||
continue
|
||
original_bg = cls.key_press
|
||
|
||
def key_press(self, key, _original=original_bg):
|
||
if str(key).lower() not in key_list:
|
||
return _original(self, key)
|
||
self.set_active()
|
||
self.key_down(key)
|
||
try:
|
||
time.sleep(KEY_HOLD)
|
||
finally:
|
||
self.key_up(key)
|
||
|
||
key_press.__wrapped__ = original_bg
|
||
cls.key_press = key_press
|
||
originals[name] = original_bg
|
||
|
||
if not originals:
|
||
log('[lc_mcp] 按键补丁跳过: 没有可改的 Windows 输入后端')
|
||
return None
|
||
log('[lc_mcp] patch: 按键按住 %dms 再松开, 前台改发带扫描码的按键(%s)'
|
||
% (KEY_HOLD * 1000, '/'.join(sorted(originals))))
|
||
return originals
|
||
|
||
|
||
# ---------------------------------------------------------------- 镜牢「兔子洞」速刷: 每回合给浮士德放「空洞」
|
||
|
||
# 「兔子洞」(英文社区 Mao Hollow Faust) = 黑兽 - 卯 魁首 浮士德 + 浮士德的 E.G.O「空洞」。游戏数据(零协 2026111301):
|
||
# 普通「空洞」不打敌人, 只给自己叠 5 发弹孔; 弹孔不低于 1 发时改用「填补空洞」(大伤害); 侵蚀「空洞」随机打人。
|
||
# E.G.O 被动: 弹孔满 5 发时「空洞」(觉醒、侵蚀)不耗 E.G.O 资源, 每回合开始 +1 发。攻略(OurPlay 777774): 每场第一回合
|
||
# 超频(强制用侵蚀技能)直接清场。AALC 战斗只会 P+Enter, 不会放 E.G.O。游戏教程: 按住罪人的头像打开 E.G.O 列表
|
||
# (wiki.gg 写的是按住技能格), 单击 E.G.O 是普通放, 长按 E.G.O 是超频。完整依据见 docs/feedback/2026-11-15/RABBIT-HOLE.md。
|
||
RABBIT_HOLE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'rabbit_hole.json')
|
||
RABBIT_HOLE_POPUP_WAIT = 0.6 # 长按松开后等 E.G.O 列表弹出
|
||
RABBIT_HOLE_SETTLE = 0.4 # 点完 E.G.O 等界面刷新
|
||
|
||
|
||
def load_rabbit_hole(path=RABBIT_HOLE_FILE):
|
||
"""读兔子洞配置; 格式不对抛 ValueError。"""
|
||
with open(path, encoding='utf-8') as fh:
|
||
data = json.load(fh)
|
||
if not isinstance(data, dict):
|
||
raise ValueError('配置必须是 JSON 对象')
|
||
|
||
def names(field):
|
||
value = data.get(field)
|
||
if not isinstance(value, list) or not value or \
|
||
not all(isinstance(v, str) and normalize_team_name(v) for v in value):
|
||
raise ValueError('%s 必须是非空字符串列表' % field)
|
||
return tuple(normalize_team_name(v) for v in value)
|
||
|
||
press_at = data.get('press_at')
|
||
if press_at is not None:
|
||
if not isinstance(press_at, list) or len(press_at) != 2 or \
|
||
not all(isinstance(v, (int, float)) and 0 < v < 1 for v in press_at):
|
||
raise ValueError('press_at 必须是 null 或 [宽比例, 高比例], 都在 0~1 之间')
|
||
press_at = (float(press_at[0]), float(press_at[1]))
|
||
hold = data.get('hold_seconds', 1.0)
|
||
if isinstance(hold, bool) or not isinstance(hold, (int, float)) or not 0.2 <= hold <= 5:
|
||
raise ValueError('hold_seconds 必须在 0.2~5 秒之间')
|
||
overclock = data.get('overclock_first_turn', False)
|
||
if not isinstance(overclock, bool):
|
||
raise ValueError('overclock_first_turn 必须是 true/false')
|
||
packs = data.get('theme_packs', {})
|
||
if not isinstance(packs, dict) or not all(
|
||
isinstance(k, str) and k.strip() and not isinstance(v, bool) and isinstance(v, int) and 0 < v <= 50
|
||
for k, v in packs.items()):
|
||
raise ValueError('theme_packs 必须是 {卡包中文名: 加分(1~50 的整数)}')
|
||
return {'team_names': names('team_names'), 'ego_names': names('ego_names'),
|
||
'press_at': press_at, 'hold_seconds': float(hold), 'overclock_first_turn': overclock,
|
||
'theme_packs': {k.strip(): v for k, v in packs.items()}}
|
||
|
||
|
||
def find_ego_option(lines, ego_names, near=None):
|
||
"""OCR 逐行结果里找 E.G.O 名字(归一后完全相等); 有几条取离长按点最近的。返回 (文本, x, y) 或 None。"""
|
||
hits = [(text, x, y) for text, x, y in lines if normalize_team_name(text) in ego_names]
|
||
if not hits:
|
||
return None
|
||
if near is None:
|
||
return hits[0]
|
||
return min(hits, key=lambda hit: (hit[1] - near[0]) ** 2 + (hit[2] - near[1]) ** 2)
|
||
|
||
|
||
def rabbit_hole_turn(auto, cfg, config, log=print, overclock=False):
|
||
"""接管一回合: P → 长按浮士德(press_at)打开 E.G.O 列表 → 选「空洞」→ Enter。
|
||
|
||
overclock=True 时长按 E.G.O 卡片(超频: 1.5 倍资源和理智, 强制用侵蚀技能), 否则单击。
|
||
返回结果: ego / overclock / ego_unavailable / no_option。
|
||
按过 P 就一定按 Enter(中途出错也一样): 交回 AALC 会再按一次 P, 而 P 是在胜率/伤害之间切换。
|
||
"""
|
||
width, height = cfg.set_win_size * 16 / 9, cfg.set_win_size
|
||
x, y = config['press_at'][0] * width, config['press_at'][1] * height
|
||
names = config['ego_names']
|
||
result = 'no_option'
|
||
auto.key_press('p')
|
||
try:
|
||
time.sleep(0.5)
|
||
auto.mouse_drag(x, y, drag_time=config['hold_seconds'], dx=0, dy=0)
|
||
time.sleep(RABBIT_HOLE_POPUP_WAIT)
|
||
auto.take_screenshot()
|
||
lines = _ocr_lines(auto)
|
||
hit = find_ego_option(lines, names, near=(x, y))
|
||
if hit is None:
|
||
log('[lc_mcp] 兔子洞: 长按 (%d,%d) 后没找到 E.G.O「%s」; 这一屏: %s'
|
||
% (x, y, '/'.join(names), '/'.join(str(t) for t, _, _ in lines[:20]) or '(空)'))
|
||
else:
|
||
if overclock:
|
||
auto.mouse_drag(hit[1], hit[2], drag_time=config['hold_seconds'], dx=0, dy=0)
|
||
else:
|
||
auto.mouse_click(hit[1], hit[2])
|
||
time.sleep(RABBIT_HOLE_SETTLE)
|
||
auto.take_screenshot()
|
||
if find_ego_option(_ocr_lines(auto), names) is None:
|
||
result = 'overclock' if overclock else 'ego'
|
||
else:
|
||
result = 'ego_unavailable' # 列表还开着: 资源不够(灰的)或没点上
|
||
log('[lc_mcp] 兔子洞: %s「%s」后列表还在(可能 E.G.O 资源不够), 这回合按胜率打'
|
||
% ('长按' if overclock else '点了', hit[0]))
|
||
if result not in ('ego', 'overclock'):
|
||
auto.mouse_click_blank() # 关掉弹出的列表
|
||
time.sleep(RABBIT_HOLE_SETTLE)
|
||
finally:
|
||
auto.key_press('enter')
|
||
decisions.record('battle', 'hollow', result)
|
||
return result
|
||
|
||
|
||
def install_rabbit_hole(log=print, config=None):
|
||
"""镜牢战斗每回合给浮士德放「空洞」。返回原 Battle._battle_operation, 未安装返回 None。"""
|
||
try:
|
||
config = config or load_rabbit_hole()
|
||
except (OSError, ValueError) as e:
|
||
log('[ERROR] [lc_mcp] 兔子洞配置读不了(%s): %s' % (RABBIT_HOLE_FILE, e))
|
||
return None
|
||
try:
|
||
from tasks.battle.battle import Battle
|
||
from module.automation import auto
|
||
from module.config import cfg
|
||
except Exception as e:
|
||
log('[lc_mcp] 兔子洞补丁跳过: 无法导入 %s' % e)
|
||
return None
|
||
original = getattr(Battle, '_battle_operation', None)
|
||
if original is None or _source_mentions(original, 'auto.key_press("p")', 'auto.key_press("enter")') is False:
|
||
log('[ERROR] [lc_mcp] 上游 Battle._battle_operation 不再是 P+Enter 出手, 兔子洞补丁挂不上, 跳过')
|
||
return None
|
||
state = {'warned': False}
|
||
overclock = config.get('overclock_first_turn', False)
|
||
signature = None
|
||
if overclock:
|
||
import inspect
|
||
try:
|
||
signature = inspect.signature(original)
|
||
except (TypeError, ValueError):
|
||
signature = None
|
||
if signature is None or 'first_turn' not in signature.parameters:
|
||
log('[ERROR] [lc_mcp] 上游 Battle._battle_operation 没有 first_turn 参数, 兔子洞第一回合不超频, 只放普通「空洞」')
|
||
overclock = False
|
||
|
||
def first_turn(self, args, kwargs):
|
||
try:
|
||
return bool(signature.bind(self, *args, **kwargs).arguments.get('first_turn'))
|
||
except TypeError:
|
||
return False
|
||
|
||
def _battle_operation(self, *args, **kwargs):
|
||
if config['press_at'] is None:
|
||
if not state['warned']:
|
||
state['warned'] = True
|
||
log('[ERROR] [lc_mcp] 兔子洞: rabbit_hole.json 的 press_at 还没在实机上量, 本次按 AALC 原来的 P+Enter 打')
|
||
return original(self, *args, **kwargs)
|
||
try:
|
||
rabbit_hole_turn(auto, cfg, config, log=log,
|
||
overclock=overclock and first_turn(self, args, kwargs))
|
||
except InterruptedError:
|
||
raise # AALC 的暂停/停止
|
||
except Exception as e: # Enter 已经在 rabbit_hole_turn 的 finally 里按过, 这回合照常打
|
||
log('[lc_mcp] 兔子洞: 这回合出错(%s: %s), 已按 Enter' % (type(e).__name__, e))
|
||
return False # 上游的返回值是「小指良单通的连续防御是否执行」
|
||
|
||
_battle_operation.__wrapped__ = original
|
||
Battle._battle_operation = _battle_operation
|
||
log('[lc_mcp] patch: 镜牢兔子洞: 每回合给浮士德放 E.G.O「%s」%s(%s)'
|
||
% ('/'.join(config['ego_names']), ', 每场第一回合超频' if overclock else '',
|
||
'长按点未校准, 先按 P+Enter' if config['press_at'] is None else '长按 %.3f,%.3f' % config['press_at']))
|
||
return original
|