使用Python结合OpenCV开发游戏脚本,核心是通过图像模板匹配找到屏幕上目标元素的位置,再模拟鼠标点击完成自动操作,适合处理游戏中重复性的点击任务。

环境准备
首先需要在本地安装对应的依赖库,确保后续代码可以正常运行。需要安装的库包括OpenCV用于图像处理,pyautogui用于模拟鼠标操作,Pillow用于屏幕截图。执行以下命令完成安装:
pip install opencv-python pyautogui pillow
图像模板匹配原理
模板匹配是OpenCV提供的功能,原理是将小尺寸的模板图像在大的源图像上滑动,逐个位置计算模板和源图像对应区域的相似度,相似度最高的位置就是匹配到的目标位置。OpenCV提供了多种相似度计算方式,常用的有cv2.TM_CCOEFF_NORMED,返回值的范围是-1到1,越接近1表示匹配度越高。
实现步骤
1. 准备模板图像
首先需要截取游戏中需要点击的目标元素的图片,保存为模板图像,比如保存为target.png,尽量保证模板图像清晰,没有多余的背景内容,尺寸不要过大。
2. 获取屏幕截图
使用Pillow库获取当前屏幕的截图,再转换为OpenCV可以处理的格式。示例代码如下:
import cv2
import pyautogui
from PIL import Image
def get_screen_shot():
# 获取屏幕截图
screen_img = pyautogui.screenshot()
# 转换为OpenCV的BGR格式
screen_np = cv2.cvtColor(np.array(screen_img), cv2.COLOR_RGB2BGR)
return screen_np
注意需要导入numpy库,在代码开头添加import numpy as np。
3. 模板匹配找图
读取模板图像和屏幕截图,执行模板匹配操作,获取匹配位置的坐标。代码示例如下:
def find_target_position(screen_img, template_path, threshold=0.8):
# 读取模板图像
template = cv2.imread(template_path)
# 获取模板的高度和宽度
th, tw = template.shape[:2]
# 执行模板匹配
result = cv2.matchTemplate(screen_img, template, cv2.TM_CCOEFF_NORMED)
# 获取匹配结果中大于阈值的位置
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# 如果最大相似度大于阈值,返回目标中心坐标
if max_val >= threshold:
# 计算目标中心坐标
center_x = max_loc[0] + tw // 2
center_y = max_loc[1] + th // 2
return center_x, center_y, max_val
else:
return None, None, max_val
4. 模拟鼠标点击
当找到目标位置后,使用pyautogui模拟鼠标点击操作,同时可以添加适当的延迟,避免操作过快被游戏检测。代码示例如下:
import time
def auto_click():
template_path = "target.png"
threshold = 0.8
while True:
# 获取屏幕截图
screen = get_screen_shot()
# 查找目标位置
x, y, match_val = find_target_position(screen, template_path, threshold)
if x is not None:
print(f"找到目标,相似度:{match_val},坐标:({x}, {y})")
# 移动鼠标到目标位置并点击
pyautogui.click(x, y)
# 点击后等待1秒再进行下一次检测
time.sleep(1)
else:
print(f"未找到目标,最高相似度:{match_val}")
# 未找到时等待0.5秒再重试
time.sleep(0.5)
if __name__ == "__main__":
# 预留5秒时间切换到游戏窗口
print("请在5秒内切换到游戏窗口")
time.sleep(5)
auto_click()
注意事项
- 模板图像需要和游戏内的目标元素比例一致,如果游戏窗口分辨率变化,可能需要重新截取模板图像。
- 阈值可以根据实际情况调整,如果匹配不到目标可以适当降低阈值,但过低容易出现误匹配。
- 部分游戏有反作弊机制,使用脚本前需要确认游戏允许相关操作,避免账号被封禁。
- 运行脚本时如果需要停止,可以将鼠标快速移动到屏幕左上角,pyautogui会触发失败安全机制停止操作。
完整示例代码
以下是整合所有功能的完整代码,保存为game_script.py后可以直接运行:
import cv2
import pyautogui
import time
import numpy as np
from PIL import Image
def get_screen_shot():
screen_img = pyautogui.screenshot()
screen_np = cv2.cvtColor(np.array(screen_img), cv2.COLOR_RGB2BGR)
return screen_np
def find_target_position(screen_img, template_path, threshold=0.8):
template = cv2.imread(template_path)
th, tw = template.shape[:2]
result = cv2.matchTemplate(screen_img, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
if max_val >= threshold:
center_x = max_loc[0] + tw // 2
center_y = max_loc[1] + th // 2
return center_x, center_y, max_val
else:
return None, None, max_val
def auto_click():
template_path = "target.png"
threshold = 0.8
while True:
screen = get_screen_shot()
x, y, match_val = find_target_position(screen, template_path, threshold)
if x is not None:
print(f"找到目标,相似度:{match_val},坐标:({x}, {y})")
pyautogui.click(x, y)
time.sleep(1)
else:
print(f"未找到目标,最高相似度:{match_val}")
time.sleep(0.5)
if __name__ == "__main__":
print("请在5秒内切换到游戏窗口")
time.sleep(5)
auto_click()