PyAutoGUI截图结合多进程仅首次运行正常问题排查求助
游戏挂机脚本截图复用问题排查求助
我无法定位代码错误,已经尝试重写代码、重装Python、相关模块及PyCharm,但问题仍未解决。
代码背景与问题说明
我正在编写一款单人游戏挂机脚本,通过PyAutoGUI的screenshot()函数截图并识别特定颜色,判断是否可开始游戏。若满足启动条件,则通过multiprocessing模块启动自动点击函数,等待游戏时长后终止进程,随后循环检查是否可再次启动游戏(每5分钟可启动一次)。
脚本初始运行正常,但存在核心问题:首次截图触发自动点击后,当游戏结束回到循环开头时,截图代码停止工作——不再重新截图,而是复用之前触发自动点击的旧截图,导致误判并立即再次启动自动点击。
代码展示
import pyautogui as pg import multiprocessing as mp import time def launchAutoclicker(): # I don't think the problem is in this function but here it is anyway while True: screenshot = pg.screenshot(region=(sceneScreenshotCornerX, sceneScreenshotCornerY, sceneScreenshotWidth, sceneScreenshotHeight)) for y in range(topBorderToToilet, sceneScreenshotHeight, toiletToToiletY): # 3 rows for x in range(leftBorderToToilet, sceneScreenshotWidth, toiletToToiletX): # 5 columns if screenshot.getpixel((x,y))[0] > 200: pg.click(x + sceneScreenshotCornerX,y + sceneScreenshotCornerY) def main(): while True: screenshot = pg.screenshot(region=(startScreenshotCornerX, startScreenshotCornerY, 50, 1)) # This is the line that stops working for startX in range(0, 50): if screenshot.getpixel((startX, 0))[2] > 200: # This checks the screenshot colors del screenshot # EXPLAINING OF THIS DEL BELOW clickerProcess = mp.Process(target=launchAutoclicker) clickerProcess.start() pg.click(700, 1000) # This clicks the start button time.sleep(gameplaySeconds + 5) # Here the code sleeps for the duration of the game clickerProcess.kill() time.sleep(1) if __name__ == '__main__': main()
关于del screenshot的说明
我在PyCharm中添加该语句尝试清空变量(已无计可施),但PyCharm在main函数的截图行提示警告:Local variable "screenshot" might be referenced before assignment。
恳请各位帮忙排查问题!
内容的提问来源于stack exchange,提问作者TripleCreeper3
相关产品推荐
相关产品推荐

