用户反馈: 点击有时候一直点也没点上, 位置明明正确。
---
## 实测排查过程
第一版假设是两个时序问题(按下 30ms 太短 / 移动后立刻按下)。实测否决:
press= 30ms -> 画面切换 4/4
press= 60ms -> 画面切换 4/4
press=120ms -> 画面切换 4/4
在干净环境里三种时长全中, 所以时长不是元凶。
(第一版测试本身有缺陷: 它只验证 click() 返回 True, 而 True 只代表"定位
到了", 不代表游戏收到点击。改成截图前后比对画面是否变化才有意义。)
真实原因: **前台不是游戏**。现场证据:
窗口位置: (-7, 0) ← 出界
前台窗口: '...DeepSeek Harness' ← 不是游戏
点击结果: True ← 但光标最后在 (204,1063), 没到目标
排查中还否定了一个想当然的结论: 窗口出界**本身不致命**(坐标按实际窗口位置
算, 目标只要还在屏幕内就能点中) —— 实测窗口在 (-8,0) 时画面照样切换成功。
真正致命的是前台窗口不是游戏。
## 修复
click() 加 require_foreground 校验。**关键是比对句柄而不是比对矩形**:
第一版只判断"点击点是否落在前台窗口矩形内", 结果把浏览器切到前台、点游戏里
同一个坐标, 校验**照样通过** —— 那个屏幕坐标同时也落在浏览器窗口的矩形里。
窗口重叠时几何判断毫无意义。
现在给了 hwnd 就要求前台窗口就是它(或是它的子窗口), 否则拒绝并说明"这次点击
会打到别的窗口"。DriverInput 新增 bind_window(), 代理安装时自动绑定游戏句柄。
拒绝比静默失败好: 以前"点了个寂寞"也返回 True, AALC 无从知道要重试。
## 顺带调整
press_ms 30 -> 60, 定位成功后加 settle 间隔。这两项实测在干净环境下不是必需,
但负载高/掉帧时更稳, 成本只有几十毫秒。
## 验证
真机(游戏窗口 133358):
[1] 前台是 DSH -> False | 前台不是目标窗口(前台='...DeepSeek Harness',
目标='LimbusCompany') —— 这次点击会打到别的窗口
[2] DSH 在前台同点 -> False | 同上(正确拒绝)
[3] 游戏在前台 -> True | ok
测试新增 HwndForegroundCheckTest 4 个 + ForegroundCheckTest 6 个, 全套 441 通过。
359 lines
14 KiB
Python
359 lines
14 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 os
|
|
import re
|
|
import threading
|
|
import time
|
|
from contextlib import contextmanager
|
|
|
|
TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE)
|
|
|
|
|
|
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('无法激活游戏窗口, 未发送驱动输入')
|
|
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
|
|
self._driver.down(1)
|
|
return True
|
|
|
|
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
|
|
|
|
|
|
@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
|