Python脚本需求:基于相对位置的RGB像素匹配后点击
解决方案
核心逻辑
- 通过图片定位找到目标区域,移动鼠标到指定相对位置
- 获取鼠标当前悬停点的RGB值,与预设目标RGB做容差匹配
- 匹配成功则执行点击操作,无需依赖固定坐标
修改后的完整代码
from pyautogui import * import pyautogui import time import keyboard import random import win32api, win32con # 替换成你需要检测的目标RGB值,可通过截图工具获取 TARGET_RGB = (255, 0, 0) # 示例为红色,自行修改 # 颜色容差,应对屏幕色差,范围建议5-20 COLOR_TOLERANCE = 10 def click(x, y): # 封装底层点击函数,模拟人类点击延迟 win32api.SetCursorPos((x, y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) time.sleep(random.uniform(0.1, 0.3)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) def is_rgb_match(pixel_rgb, target_rgb, tolerance): # 判断像素RGB是否在目标颜色的容差范围内 return (abs(pixel_rgb[0] - target_rgb[0]) <= tolerance and abs(pixel_rgb[1] - target_rgb[1]) <= tolerance and abs(pixel_rgb[2] - target_rgb[2]) <= tolerance) time.sleep(2) print("脚本已启动,按ESC键退出") while True: # 监听ESC键退出脚本 if keyboard.is_pressed('esc'): print("脚本已退出") break time.sleep(2) # 定位boss图片 boss_pos = pyautogui.locateOnScreen('boss monster.png', confidence=0.8) if boss_pos is not None: # 移动到图片中心 center_pos = pyautogui.locateCenterOnScreen('boss monster.png', grayscale=True, confidence=0.8) pyautogui.moveTo(center_pos, duration=0.3) # 相对移动到目标像素位置 pyautogui.moveRel(361, 209, duration=0.5) # 获取当前鼠标位置及对应RGB current_x, current_y = pyautogui.position() current_rgb = pyautogui.pixel(current_x, current_y) print(f"当前鼠标位置RGB: {current_rgb}") # 匹配成功则执行点击 if is_rgb_match(current_rgb, TARGET_RGB, COLOR_TOLERANCE): print("检测到目标颜色,执行点击") click(current_x, current_y) else: print("未检测到目标颜色,跳过点击")
重点说明
- 获取目标RGB:用系统截图工具或pyautogui的
screenshot()功能,取目标像素的精确RGB值替换TARGET_RGB - 容差设置:
COLOR_TOLERANCE可根据屏幕显示效果调整,避免因轻微色差导致匹配失败 - 退出机制:添加ESC键退出逻辑,方便随时终止脚本
- 防检测优化:点击时加入随机延迟,模拟人类操作节奏
内容的提问来源于stack exchange,提问作者Taco
相关产品推荐
相关产品推荐

