【发布时间】:2021-07-31 02:10:33
【问题描述】:
我有一个(有点)播放 2048 的 python 脚本。它的工作方式是向左按,检测是否有变化,如果没有(AKA 移动不起作用)它按下,如果不起作用,则按下,等等。如果有变化,它会继续下一步。
同时,我希望它不断检查用户是否按下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
顺便说一句,我知道我可以通过从网站上抓取代码来更简单地做到这一点,但我想挑战自己并且几乎完全通过图像来做到这一点。
【问题讨论】:
-
你应该在一个循环中运行所有内容。
-
而不是
if bbox is not None: continue else: ...你可以在没有continue的情况下使用if bbox is None: ... -
@furas 实际上,我最初有这个。由于某种原因它不起作用,当我长时间这样做时,它起作用了。