基于PyAutoGUI的像素游戏WASD移动Bot问题:无法定位点击棉花
问题分析与修复方案
你的Bot出现停不下来或异常的问题,核心是代码存在几处逻辑漏洞和细节错误:
- 第一个横向移动循环里的
confidence=0.是笔误,少写了数字8,导致图像识别失效,循环无限执行 - 多个移动判断会依次触发,比如左右移动后,上下判断仍使用旧的位置数据,逻辑顺序混乱
- 移动循环中未处理
pos变为None的情况(比如移动时棉花移出屏幕),会引发报错 - 主循环里的
keyboard.read_key()是阻塞式的,导致Bot无法持续执行检测逻辑 - 移动操作没有添加延迟,游戏可能无法响应连续的按键输入
修复后的代码
import pyautogui as pg import time import keyboard import pydirectinput as pd # 屏幕中心坐标(你的目标定位点) TARGET_X = 950 TARGET_Y = 540 # 识别置信度 CONFIDENCE = 0.8 # 移动后等待时间(给游戏和识别留缓冲) MOVE_DELAY = 0.2 def check_and_approach_cotton(): # 先把鼠标移回中心(可选,不影响游戏移动) pd.moveTo(TARGET_X, TARGET_Y, 0.5) # 定位棉花 pos = pg.locateOnScreen('cotton.PNG', confidence=CONFIDENCE) if not pos: print("未找到棉花") return print("发现棉花!") cotton_x, cotton_y = pos[0], pos[1] # 判断是否已经在可点击范围内 if abs(cotton_x - TARGET_X) <= 20 and abs(cotton_y - TARGET_Y) <= 20: pd.click() print("已点击棉花") time.sleep(0.5) # 点击后留缓冲 return # 横向移动调整 while abs(cotton_x - TARGET_X) > 20: # 重新定位,防止移动中丢失目标 pos = pg.locateOnScreen('cotton.PNG', confidence=CONFIDENCE) if not pos: print("移动中丢失棉花目标") return cotton_x = pos[0] if cotton_x < TARGET_X - 20: pd.press('a') elif cotton_x > TARGET_X + 20: pd.press('d') time.sleep(MOVE_DELAY) # 纵向移动调整 while abs(cotton_y - TARGET_Y) > 20: pos = pg.locateOnScreen('cotton.PNG', confidence=CONFIDENCE) if not pos: print("移动中丢失棉花目标") return cotton_y = pos[1] if cotton_y < TARGET_Y - 20: pd.press('w') elif cotton_y > TARGET_Y + 20: pd.press('s') time.sleep(MOVE_DELAY) # 移动到位后点击 pd.click() print("已移动到位并点击棉花") time.sleep(0.5) # 主循环:非阻塞检测退出按键 active = True while active: check_and_approach_cotton() # 用is_pressed非阻塞检测q键 if keyboard.is_pressed('q'): active = False print("已退出Bot") # 主循环留缓冲,避免占用过高CPU time.sleep(0.1)
关键修复点说明
- 修正了置信度的笔误,确保图像识别正常
- 将横向和纵向移动拆分为顺序执行的循环,避免逻辑冲突
- 每个移动循环内重新定位棉花,处理目标丢失的情况
- 改用
keyboard.is_pressed()实现非阻塞的退出检测,让Bot可以持续运行 - 添加了多处延迟,给游戏响应和图像识别留足缓冲时间
- 简化了点击条件的判断逻辑,代码更清晰
内容的提问来源于stack exchange,提问作者armok
相关产品推荐
相关产品推荐

