I have a python script that (somewhat) plays 2048. The way it works is it presses left, detects if there has been a change or not, and if there hasn't (AKA the move didn't work) it presses up, if that doesn't work it presses down, etc.. If there had been a change it moves on to the next move.
At the same time, I want it to constantly be checking if the user is pressing esc
, and if they are, end the program. This way you can end it at any time.
Here's the code that checks for esc
:
while True:
if keyboard.read_key() == "esc":
endofgame = True
break
And here's the code that does the moving:
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
By the way, I know I could do this more simply by just scraping the code from the site, but I wanted to challenge myself and do it almost purely by images.