- 包住 Mirror.event_handling:上游每轮挑选项前(找 unknown_event 那一步), 画面有选项框时整屏 OCR,按行把文字归到各选项;认出表里的事件就点对应选项, 没收录/选项不在画面上照常交给上游,调用结束还原 click_element - 表 lc_mcp/data/event_choices.json 10 条,取自事件速查里的直出/免费奖励; 按选项文字优先,按编号只用于第一屏、画面没变时最多重试 3 次 - 每屏选项打一次日志(含未收录事件的选项文字,便于补表) - LCP_EVENT_CHOICES=0 关闭,=<路径> 换表;表读不了记 [ERROR] 不装 - 单测执行上游真实 event_handling Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1144 lines
49 KiB
Python
1144 lines
49 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 os
|
|
import re
|
|
import threading
|
|
import time
|
|
import unicodedata
|
|
from contextlib import contextmanager
|
|
|
|
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])
|
|
return True
|
|
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])]
|
|
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)
|
|
return True
|
|
log('[lc_mcp] 点了 %s 但顶栏没变(顶栏读到: %s), 继续往下翻'
|
|
% (label, '/'.join(normalize_team_name(t) for t in _header_texts(auto) or ()) or '无'))
|
|
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))
|
|
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
|
|
|
|
|
|
# ---------------------------------------------------------------- 镜牢商店清单
|
|
|
|
# 上游 ebb6629 把图片挪到 assets/images/<主题>/<语言>/ 下, tasks/mirror/__init__.py 却仍按
|
|
# ./assets/images/share/mirror/shop/... 列目录, 三个清单恒为空。2026-11-14 实测进店 51 秒,
|
|
# 打印三次 "开始购买必买项" 一件没买; 弃用饰品识别与公式合成也一起空转。
|
|
# 按名字找图(mirror/shop/<清单>/<文件>)由 path_manager 依次搜各主题/语言目录, 那一层没坏。
|
|
SHOP_LISTS = ('must_purchase', 'must_be_abandoned', 'fusion_result')
|
|
IMAGE_ROOTS = ('dark/zh_cn', 'dark/en', 'dark/share', 'default/zh_cn', 'default/en', 'default/share')
|
|
|
|
|
|
def shop_list_images(kind, images_dir=os.path.join('assets', 'images'), roots=IMAGE_ROOTS):
|
|
"""各主题/语言目录下 mirror/shop/<kind> 的图片, 按 AALC 图片名格式去重排序。"""
|
|
names = set()
|
|
for root in roots:
|
|
folder = os.path.join(images_dir, *root.split('/'), 'mirror', 'shop', kind)
|
|
try:
|
|
entries = os.listdir(folder)
|
|
except OSError:
|
|
continue
|
|
names.update(name for name in entries
|
|
if name.lower().endswith('.png') and os.path.isfile(os.path.join(folder, name)))
|
|
return ['mirror/shop/%s/%s' % (kind, name) for name in sorted(names)]
|
|
|
|
|
|
def install_shop_lists(log=print, images_dir=os.path.join('assets', 'images')):
|
|
"""原地补齐 tasks.mirror 的三个商店清单; 上游清单已非空时不动。
|
|
|
|
in_shop 用 from tasks.mirror import ... 在导入时绑定列表对象, 所以必须原地 extend,
|
|
给模块属性重新赋值对它无效。
|
|
"""
|
|
try:
|
|
import tasks.mirror as mirror_pkg
|
|
except Exception as e:
|
|
log('[lc_mcp] 商店清单补丁跳过: 无法导入 tasks.mirror: %s' % e)
|
|
return {}
|
|
try:
|
|
from utils.path_manager import PathManager
|
|
roots = tuple(PathManager.DEFAULT_ACTIVE_PATHS)
|
|
except Exception:
|
|
roots = IMAGE_ROOTS
|
|
filled = {}
|
|
for kind in SHOP_LISTS:
|
|
current = getattr(mirror_pkg, kind, None)
|
|
if not isinstance(current, list):
|
|
log('[lc_mcp] 商店清单补丁跳过 %s: 上游没有这个列表' % kind)
|
|
continue
|
|
if current:
|
|
continue # 上游已修好或已补过
|
|
current.extend(shop_list_images(kind, images_dir, roots))
|
|
filled[kind] = len(current)
|
|
if filled:
|
|
log('[lc_mcp] patch: 镜牢商店清单按 assets/images/<主题>/<语言> 补齐: %s'
|
|
% ', '.join('%s=%d' % item for item in filled.items()))
|
|
return filled
|
|
|
|
|
|
# ---------------------------------------------------------------- 镜牢键盘寻路按节点类型
|
|
|
|
# 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))
|
|
return original()
|
|
if not ranked:
|
|
log('[lc_mcp] 键盘寻路: %s, 退回按 ↑' % ('没找到巴士' if not bus else '下一列没识别到节点'))
|
|
return original()
|
|
log('[lc_mcp] 键盘寻路: 下一列 %s, 按权重从低到高依次尝试'
|
|
% ' '.join('%s=%s(%d)' % item for item in ranked))
|
|
for direction, kind, weight in ranked:
|
|
auto.key_press(ROAD_KEYS[direction])
|
|
time.sleep(1)
|
|
if road._keyboard_enter_succeeded():
|
|
reason = '下一列中最低' if direction == ranked[0][0] else '更优的方向没能进入'
|
|
log('[lc_mcp] 键盘寻路: 进入 %s 方向的 %s(权重 %d, %s)' % (direction, kind, weight, reason))
|
|
return True
|
|
log('[lc_mcp] 键盘寻路: %s 方向的 %s 没能进入, 试下一个' % (direction, kind))
|
|
log('[lc_mcp] 键盘寻路: 按类型都没进入, 退回按 ↑')
|
|
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
|
|
|
|
|
|
# ---------------------------------------------------------------- 饰品选择按体系关键词
|
|
|
|
# 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
|
|
|
|
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))
|
|
if any(hits):
|
|
log('[lc_mcp] 饰品选择(体系 %s): %s; 命中体系关键词, 先看第%d张'
|
|
% (system, detail, by_x.index(order[0]) + 1))
|
|
else:
|
|
log('[lc_mcp] 饰品选择(体系 %s): %s; 未命中体系关键词, 保持原顺序' % (system, detail))
|
|
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
|
|
own = vars(auto).get('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
|
|
|
|
auto.find_element = find_element
|
|
try:
|
|
return original(self, *args, **kwargs)
|
|
finally:
|
|
if own is None:
|
|
vars(auto).pop('find_element', None)
|
|
else:
|
|
auto.find_element = own
|
|
|
|
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() 不认事件, 有 "???"/直接拿饰品/优势判定就选它, 否则点第一个选项。
|
|
# 这里在上游每轮挑选项之前(它先找 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 # 一次事件里按文字最多点几次
|
|
EVENT_INDEX_TRIES = 3 # 按编号点: 只在第一屏选项, 画面没变时最多重试几次
|
|
|
|
|
|
def load_event_choices(path=EVENT_CHOICES_FILE):
|
|
"""读事件表, 返回 [{'name', 'match', 'text', 'index'}]; 格式不对抛 ValueError。"""
|
|
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": [...]}')
|
|
|
|
def words(item, key):
|
|
value = item.get(key, [])
|
|
if not isinstance(value, list) or not all(isinstance(w, str) for w in value):
|
|
raise ValueError('%s 的 %s 应是字符串列表' % (item.get('name', '?'), key))
|
|
return tuple(normalize_team_name(w) for w in value if normalize_team_name(w))
|
|
|
|
rules = []
|
|
for item in events:
|
|
if not isinstance(item, dict):
|
|
raise ValueError('events 的每一项应是对象')
|
|
name = str(item.get('name') or '?')
|
|
index = item.get('index')
|
|
if index is not None and (isinstance(index, bool) or not isinstance(index, int) or index < 1):
|
|
raise ValueError('%s 的 index 应是 >= 1 的整数' % name)
|
|
rule = {'name': name, 'match': words(item, 'match'), 'text': words(item, 'text'), 'index': index}
|
|
if not rule['match']:
|
|
raise ValueError('%s 缺少 match' % name)
|
|
if not rule['text'] and index is None:
|
|
raise ValueError('%s 至少要有 text 或 index' % 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_team_name(text))
|
|
return [(m, ''.join(t)) for m, t in zip(markers, texts)]
|
|
|
|
|
|
def match_event_rule(rules, lines):
|
|
"""画面上的文字命中的第一条规则; 没有返回 None。"""
|
|
screen = [normalize_team_name(text) for text, _, _ in lines]
|
|
for rule in rules:
|
|
if any(word in text for word in rule['match'] for text in screen):
|
|
return rule
|
|
return None
|
|
|
|
|
|
def choose_event_option(rule, texts):
|
|
"""返回 (第几项(0 起), 'text'|'index', 理由); 选不出返回 (None, None, 理由)。"""
|
|
for word in rule['text']:
|
|
for i, text in enumerate(texts):
|
|
if word in text:
|
|
return i, 'text', '选项文字含「%s」' % word
|
|
if rule['index'] is not None:
|
|
if rule['index'] <= len(texts):
|
|
return rule['index'] - 1, 'index', '按表选第 %d 项' % rule['index']
|
|
return None, None, '表里是第 %d 项, 画面上只有 %d 项' % (rule['index'], len(texts))
|
|
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
|
|
|
|
def decide(state):
|
|
"""按表点了一个选项返回 True; 其余情况返回 False 交给上游。"""
|
|
markers = auto.find_element(EVENT_OPTION, find_type='image_with_multiple_targets', threshold=0.75)
|
|
if not markers:
|
|
return False
|
|
lines = _ocr_lines(auto)
|
|
options = event_options(markers, lines, cfg.set_win_size / 1440)
|
|
texts = tuple(text for _, text in options)
|
|
state['rule'] = state['rule'] or match_event_rule(rules, lines)
|
|
rule = state['rule']
|
|
shown = ' | '.join('%d=%s' % (i + 1, text or '?') for i, text in enumerate(texts))
|
|
|
|
def once(message):
|
|
if (texts, message) not in state['logged']:
|
|
state['logged'].add((texts, message))
|
|
log(message)
|
|
|
|
if rule is None:
|
|
once('[lc_mcp] 事件选项: %s; 表里没有这个事件, 交给 AALC' % shown)
|
|
return False
|
|
i, how, reason = choose_event_option(rule, texts)
|
|
if how == 'text' and state['text_clicks'] >= EVENT_TEXT_CLICKS:
|
|
how, reason = None, '按文字已点 %d 次' % EVENT_TEXT_CLICKS
|
|
if how == 'index' and (state['signature'] not in (None, texts) or state['index_tries'] >= EVENT_INDEX_TRIES):
|
|
how, reason = None, '编号只用于第一屏选项'
|
|
if how is None:
|
|
once('[lc_mcp] 事件 %s: %s; %s, 交给 AALC' % (rule['name'], shown, reason))
|
|
return False
|
|
if how == 'text':
|
|
state['text_clicks'] += 1
|
|
else:
|
|
state['index_tries'] += 1
|
|
state['signature'] = texts
|
|
log('[lc_mcp] 事件 %s: %s; 选第 %d 项(%s)' % (rule['name'], shown, i + 1, reason))
|
|
position = options[i][0]
|
|
auto.mouse_click(position[0], position[1])
|
|
return True
|
|
|
|
def event_handling(self, *args, **kwargs):
|
|
state = {'rule': None, 'signature': None, 'index_tries': 0, 'text_clicks': 0, 'logged': set()}
|
|
real = auto.click_element
|
|
own = vars(auto).get('click_element')
|
|
|
|
def click_element(target, *a, **kw):
|
|
if target == EVENT_HOOK:
|
|
try:
|
|
if decide(state):
|
|
return True # 上游当作点到了选项: event_chance -= 1, 重新截图
|
|
except Exception as e:
|
|
log('[lc_mcp] 事件选项表出错(%s: %s), 交给 AALC' % (type(e).__name__, e))
|
|
return real(target, *a, **kw)
|
|
|
|
auto.click_element = click_element
|
|
try:
|
|
return original(self, *args, **kwargs)
|
|
finally:
|
|
if own is None:
|
|
vars(auto).pop('click_element', None)
|
|
else:
|
|
auto.click_element = own
|
|
|
|
mirror_mod.Mirror.event_handling = event_handling
|
|
log('[lc_mcp] patch: 镜牢事件按选项表选择(%s, %d 条)' % (os.path.basename(path), len(rules)))
|
|
return original
|