You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现记忆游戏中红色方块的自动点击功能

实现记忆游戏中红色方块消失后自动点击位置

需求说明

我有一款记忆类游戏,其中红色方块会随机出现(示例图:红色方块示例)。我希望用Python实现在红色方块消失后自动点击它之前出现的位置。目前我已经完成了屏幕红色方块的检测功能,代码如下:

from pyautogui import *
import pyautogui
import time
from playsound import playsound

while 0:
    if pyautogui.locateOnScreen('model_square.png', confidence=1) != None:
        print("There is a red square")
        playsound('audio.mp3')
        time.sleep(1)
    else:
        print("No squares")
        time.sleep(1)

解决方案

要实现目标,需要在检测到红色方块时记录它的位置,等方块消失后触发点击操作,修改后的代码如下:

from pyautogui import *
import pyautogui
import time
from playsound import playsound

# 存储红色方块的位置
square_pos = None

while True:
    # 检测红色方块
    current_pos = pyautogui.locateOnScreen('model_square.png', confidence=0.8)  # 适当降低confidence,避免漏检
    if current_pos is not None:
        print("检测到红色方块,记录位置")
        # 记录方块中心位置(点击中心更准确)
        square_pos = pyautogui.center(current_pos)
        playsound('audio.mp3')
        time.sleep(0.1)  # 缩短检测间隔,提升响应速度
    else:
        # 如果之前记录过位置,且现在方块消失,执行点击
        if square_pos is not None:
            print("红色方块消失,执行点击")
            pyautogui.click(square_pos)
            square_pos = None  # 重置位置,避免重复点击
        print("未检测到红色方块")
        time.sleep(0.1)

关键修改点

  • 将while 0改为while True,让循环持续运行
  • 添加square_pos变量存储检测到的红色方块位置
  • 检测到方块时记录其中心坐标(使用pyautogui.center())
  • 方块消失且有记录位置时,执行点击并重置位置变量
  • 降低confidence值(从1调整到0.8),避免因画面细微差异导致漏检
  • 缩短time.sleep()的时长,提升检测和响应的实时性

内容的提问来源于stack exchange,提问作者HaZZe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:50:37