| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- # -*- coding: utf-8 -*-
- """Interception 鼠标控制(硬件级相对/绝对移动)。
- 依赖:已安装 Interception 驱动 + pip 包 interception-python。
- 驱动未装时 move_* 会抛 DriverNotFoundError,上层可降级或直接报错。
- """
- from __future__ import annotations
- import threading
- from typing import Optional, Tuple
- _lock = threading.Lock()
- _ready = False
- _last_error: Optional[str] = None
- def last_error() -> Optional[str]:
- return _last_error
- def ensure_ready() -> bool:
- """捕获鼠标设备;成功返回 True。可重复调用。"""
- global _ready, _last_error
- with _lock:
- if _ready:
- return True
- try:
- import interception
- interception.auto_capture_devices()
- # 读一次位置,确认驱动通路活着
- interception.mouse_position()
- _ready = True
- _last_error = None
- return True
- except Exception as exc:
- _ready = False
- _last_error = str(exc)
- return False
- def position() -> Tuple[int, int]:
- import interception
- return interception.mouse_position()
- def move_to(x: int, y: int) -> None:
- """绝对移动到屏幕坐标(像素)。"""
- if not ensure_ready():
- raise RuntimeError(_last_error or "Interception 未就绪")
- import interception
- interception.move_to(int(x), int(y))
- def move_relative(dx: int, dy: int) -> None:
- """相对当前光标移动。"""
- if not ensure_ready():
- raise RuntimeError(_last_error or "Interception 未就绪")
- if dx == 0 and dy == 0:
- return
- import interception
- interception.move_relative(int(dx), int(dy))
- def follow_screen_point(
- sx: float,
- sy: float,
- *,
- gain: float = 1.0,
- deadzone: float = 1.5,
- max_step: float = 0.0,
- ) -> Tuple[int, int]:
- """把鼠标朝屏幕点 (sx, sy) 拉过去。
- gain=1 且 max_step=0:每帧尽量一次到位(跟着红准星跑)。
- 返回本次实际相对位移 (dx, dy)。
- """
- cx, cy = position()
- dx = (float(sx) - cx) * float(gain)
- dy = (float(sy) - cy) * float(gain)
- if abs(dx) < deadzone and abs(dy) < deadzone:
- return (0, 0)
- if max_step and max_step > 0:
- mag = (dx * dx + dy * dy) ** 0.5
- if mag > max_step:
- scale = max_step / mag
- dx *= scale
- dy *= scale
- idx, idy = int(round(dx)), int(round(dy))
- if idx == 0 and idy == 0:
- # 亚像素误差:至少挪 1px 朝目标靠
- if abs(sx - cx) >= abs(sy - cy):
- idx = 1 if sx > cx else -1
- else:
- idy = 1 if sy > cy else -1
- move_relative(idx, idy)
- return (idx, idy)
|