DataMower

Automate the game 2048 with Python

Feb 12th, 2022 (edited)
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. #! python3
  2. #_2048.py - A program that plays the game 2048 (https://play2048.co/)
  3. # automatically.
  4.  
  5. from selenium import webdriver
  6. from selenium.webdriver.common.keys import Keys
  7. from selenium.webdriver.common.by import By
  8. from selenium.webdriver.support import expected_conditions as EC
  9. from random import randint
  10.  
  11. browser = webdriver.Firefox() # Open Firefox
  12. browser.get('https://play2048.co/') # Go to https://play2048.co/
  13. wait = WebDriverWait(browser, 10)
  14.  
  15. wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".game-container)))
  16.  
  17. def random_click(): # Function for random click
  18. rand_int = randint(1, 4)
  19. if rand_int == 1:
  20. Keys.UP
  21. elif rand_int == 2:
  22. Keys.RIGHT
  23. elif rand_int == 3:
  24. Keys.DOWN
  25. else:
  26. Keys.LEFT
  27.  
  28. random_click()
  29.  
  30. while '2048' not in board.values():
  31. tileContainer = browser.find_element(By.CLASS_NAME, 'tile-container') # finds the tile container
  32. tiles = tileContainer.find_elements(By.TAG_NAME, "div[class*='tile-position']") # finds every tile
  33. board = {'1-1': None, '1-2': None, '1-3': None, '1-4': None, '2-1': None,
  34. '2-2': None, '2-3': None, '2-4': None, '3-1': None, '3-2': None,
  35. '3-3': None, '3-4': None, '4-1': None, '4-2': None, '4-3': None,
  36. '4-4': None,
  37. } # creates an empty dictionary for the board which is filled right afterwards
  38. for tile in tiles: # fills the board
  39. board[tile.get_attribute('class')[26:29]] = tile.get_attribute('class')[10]
  40. # decision structure
  41.  
Add Comment
Please, Sign In to add comment