在python中运行其他代码时如何在后台运行循环

问题描述

我有一个(有点)播放 2048 的 python 脚本。它的工作方式是按下左键,检测是否有变化,如果没有(也称为移动不起作用)它按下,如果这不起作用,它会按下,等等。如果有变化,它会继续下一步。

同时,我希望它不断检查用户是否按下 esc,如果按下,则结束程序。这样你就可以随时结束。

这是检查 esc 的代码:

while True:
    if keyboard.read_key() == "esc":
        endofgame = True
        break

这是执行移动的代码:

while not endofgame:
    endgameim = grab()
    pxcolour = endgameim.getpixel((818,453))
    print(pxcolour)
    if pxcolour == (123,110,101):
        endofgame = True
        print(endofgame)
        break
    while True:
        im = grab()
        pyautogui.press("left")
        im2 = grab()
        diff = ImageChops.difference(im2,im)
        bbox = diff.getbbox()
        print(bbox)
        if bbox is not None:
            continue
        else:
            pyautogui.press("up")
            im2 = grab()
            diff = ImageChops.difference(im2,im)
            bbox = diff.getbbox()
            if bbox is not None:
                continue
            else:
                pyautogui.press("down")
                im2 = grab()
                diff = ImageChops.difference(im2,im)
                bbox = diff.getbbox()
                if bbox is not None:
                    continue
                else:
                    pyautogui.press("right")
                    continue
                    break
            break
    break

顺便说一下,我知道我可以通过从网站上抓取代码来更简单地做到这一点,但我想挑战自己并且几乎完全通过图片来做到这一点。

解决方法

只需在 while 循环的开头添加您的条件,它将与其余代码一起循环。

while not endofgame:
    if keyboard.read_key() == "esc":
        endofgame = True
        break
    endgameim = grab()
    pxcolour = endgameim.getpixel((818,453))
    print(pxcolour)
    if pxcolour == (123,110,101):
        endofgame = True
        print(endofgame)
        break
    while True:
        im = grab()
        pyautogui.press("left")
        im2 = grab()
        diff = ImageChops.difference(im2,im)
        bbox = diff.getbbox()
        print(bbox)
        if bbox is not None:
            continue
        else:
            pyautogui.press("up")
            im2 = grab()
            diff = ImageChops.difference(im2,im)
            bbox = diff.getbbox()
            if bbox is not None:
                continue
            else:
                pyautogui.press("down")
                im2 = grab()
                diff = ImageChops.difference(im2,im)
                bbox = diff.getbbox()
                if bbox is not None:
                    continue
                else:
                    pyautogui.press("right")
                    continue
                    break
            break
    break

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...