1

我有一个(有点)播放 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

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

4

1 回答 1

0

只需在 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
于 2021-05-09T12:23:55.917 回答