from pyvirtualdisplay import Display import os import pyautogui import cv2 import numpy as np from time import sleep from mss import mss import threading # 启动虚拟显示器 display = Display(visible=0, size=(1024, 768)) display.start() # 屏幕捕捉区域 monitor = {"top": 300, "left": 100, "width": 600, "height": 150} # 阈值,用于判断是否有障碍物 threshold = 0.7 # 全局变量,用于控制机器人循环 running = False def process_image(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY) return thresh def detect_obstacle(thresh_img): ground_part = thresh_img[50:, :] air_part = thresh_img[:50, :] ground_nonzero = np.count_nonzero(ground_part) air_nonzero = np.count_nonzero(air_part) if ground_nonzero > 0: return "ground" elif air_nonzero > 0: return "air" return None def game_bot(): global running with mss() as sct: while running: screenshot = np.array(sct.grab(monitor)) processed_img = process_image(screenshot) obstacle = detect_obstacle(processed_img) if obstacle == "ground": pyautogui.press('space') # 地面障碍,跳跃 elif obstacle == "air": pyautogui.press('down') # 空中障碍,低头 sleep(0.05) # 启动机器人 running = True bot_thread = threading.Thread(target=game_bot) bot_thread.start() # 运行一段时间后停止机器人 try: while True: sleep(1) # 主线程保持运行 except KeyboardInterrupt: running = False print("机器人已停止") # 关闭虚拟显示器 display.stop()