Files
lc-mcp/scripts/lc_ui.py

138 lines
4.3 KiB
Python

# -*- coding: utf-8 -*-
"""levelup.py / auto_cycle.py 共用的 MCP 调用与坐标换算。
脚本里的坐标都是在 1600x900 客户区上实测的。实际客户区随 set_win_size
和桌面分辨率变化(720/900/1080 都出现过), 所以:
- get_state 返回的 OCR 坐标先换算到 1600x900 再交给脚本逻辑;
- click/drag 的坐标从 1600x900 换算回当前客户区再发出。
脚本内部因此只需要面对一套坐标。
"""
import json
import os
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
def _console_python(exe):
"""计划任务用 pythonw 启动(不弹窗、不抢游戏焦点), 但子进程要读 stdout, 换成同目录的 python。"""
head, name = os.path.split(exe)
if name.lower() == 'pythonw.exe' and os.path.exists(os.path.join(head, 'python.exe')):
return os.path.join(head, 'python.exe')
return exe
# 默认用运行本脚本的解释器(AALC 的 venv); 需要时用 LC_PY 指定
PY = os.environ.get('LC_PY') or _console_python(sys.executable)
PROBE = os.path.join(HERE, 'mcp_probe.py')
# Windows 上不给子进程弹控制台窗口(从 pythonw 启动时每次调用都会闪一下)
NO_WINDOW = {'creationflags': 0x08000000} if os.name == 'nt' else {}
BASE_W, BASE_H = 1600, 900
_scale = None
def run(cmd, *, check=False):
r = subprocess.run(cmd, capture_output=True, text=True,
encoding='utf-8', errors='replace', check=check, **NO_WINDOW)
return (r.stdout or '') + (r.stderr or '')
def probe(tool, args=None, quiet=True):
cmd = [PY, '-X', 'utf8', PROBE, tool]
if args is not None:
cmd.append(json.dumps(args, ensure_ascii=False))
out = run(cmd).strip()
for line in reversed(out.splitlines()):
line = line.strip()
if line.startswith('{'):
try:
return json.loads(line)
except json.JSONDecodeError:
continue
if not quiet:
print('[warn] probe %s 无 JSON 输出: %r' % (tool, out[:200]))
return {}
def state():
"""get_state, 并把 OCR 坐标换算到 1600x900。"""
global _scale
r = probe('get_state', quiet=False)
screen = r.get('screen') or {}
if screen.get('w') and screen.get('h'):
if abs(screen['w'] / screen['h'] - BASE_W / BASE_H) > 0.02:
print('[warn] 客户区 %sx%s 不是 16:9, 坐标会偏' % (screen['w'], screen['h']))
_scale = screen['w'] / BASE_W
s = _scale or 1.0
for it in r.get('items', []):
for k in ('x', 'y', 'w', 'h'):
if k in it:
it[k] = round(it[k] / s)
return r
def items():
return state().get('items', [])
def screen_text(its):
return ' | '.join(i.get('text', '') for i in its)
def _to_client(x, y):
if _scale is None:
state()
s = _scale or 1.0
return int(round(x * s)), int(round(y * s))
def click(x, y, times=1):
cx, cy = _to_client(x, y)
return probe('click', {'x': cx, 'y': cy, 'times': times})
def find_text(needle, contains=True):
"""按文本找画面元素; 返回元素本身(含 x/y/w/h)或 None。
默认子串匹配、忽略大小写。OCR 结果里 w/h 可能缺失, 调用方要能容忍。
"""
needle = needle.lower()
for it in items():
t = it.get('text', '').lower()
if (needle in t) if contains else (needle == t):
return it
return None
def click_text(needle, contains=True):
"""按文本点击元素, 点的是识别框的**中心**。
实测坑: 直接点 OCR 返回的 (x, y) 是文本框左上角, 按下去常常落空
(2026-10-13 Uptie 弹窗的 Cancel: 文本在 (346,660), 实际可点区域中心在
(380,675), 点前者毫无反应, 弹窗一直卡着挡住后续所有输入)。
"""
it = find_text(needle, contains=contains)
if not it:
return False
w = it.get('w') or 0
h = it.get('h') or 0
click(it['x'] + w / 2.0, it['y'] + h / 2.0)
return True
def drag(from_x, from_y, to_x, to_y):
fx, fy = _to_client(from_x, from_y)
tx, ty = _to_client(to_x, to_y)
return probe('drag', {'from_x': fx, 'from_y': fy, 'to_x': tx, 'to_y': ty})
def long_press(x, y):
"""drag 起点==终点 即长按(实测可打开人格详情)。"""
return drag(x, y, x, y)
def keypress(key):
return probe('keypress', {'key': key})