I am trying to play 2048 automatically with Selenium as directed in Automate the Boring Stuff.
But every move is DOWN no matter what argument I send to send_keys().
Here is the code:
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import time, requests
browser.get('https://play2048.co/')
time.sleep(2)
game = browser.find_element_by_tag_name('body')
over = browser.find_element_by_class_name('retry-button')
control = ['Keys.UP','Keys.RIGHT','Keys.DOWN','Keys.LEFT']
act = 0
while True:
if over.is_displayed() is False:
if act == 4:
act = 0
game.send_keys(control[act])
print('act=' + str(act) + ' control =' + control[act]) # To check every move output.
act += 1
time.sleep(0.1)
else:
print('Done')
time.sleep(2)
over.click()
The argument sent to game.send_keys() is different for every move (UP > RIGHT > DOWN > LEFT > UP).
But the actual results in the game is always moving DOWN each time.
After several attempts, I changed the "control" dict to:
control = ['\ue013','\ue014','\ue015','\ue012']
And the problem solved...
I am just wondering what leads the problem, and why it always moving DOWN as arguments are all different.
Thanks, guys.
--------------------------------- Edit ---------------------------------
The problem here is I send strings, not keys, to send_keys() as Iain Shelvington (Thanks mate) answered.
And why the game is always moving down?
Because 2048 could also be controlled via W,D,S,A instead of UP, LEFT, DOWN, and RIGHT, so the game will receive commands from the string 'Keys.UP' letter by letter.
'K', 'e', and 'y' means nothing to the game, but 's' will make the blocks go DOWN.
Therefore all the strings start with 'Keys.' will direct the game to go DOWN.