Preface
Have you played the 2048 game? https://gabrielecirulli.github.io/2048/ You can play online
Human energy is always limited, and it is impossible to play day and night, but machines can; make a small player that automatically plays the 2048 game Function, familiar with the use of selenium
Analysis
## The essence of the 2048 game is to synthesize numbers through the four direction keys , in fact, the process is simple and boring (let’s not pay attention to people’s thinking problems for now), machines are good at doing this. Use selenium to open a browser, send keyboard commands and a series of operations; When the game has a game over, it is normal for selenium to send four direction key commands, so solve the game over problem It’s special processingtag## 1) Score: <
divclass=" score-container">0div>
## 2) game over: <div class="game-message"><p>Game over!p>
Note: Under normal game conditions, If the value is empty, Game over! will be displayed when the game ends. Use this feature to determine whether the game is over.
## 3) try again: <a class="retry-button">Try againa>
## Note: When the game is over, you need to find this button and click it to resume the game
#environment
# 1) Windows 7
# 2) This is a simple function, written directly under python IDLE
Source code ## Run Under python IDLE, just call play2048(). The steps for automatic execution of the program are: 1) Open firefox 2) In the currently opened firefox window, visit https://gabrielecirulli.github.io/2048/ 3) Wait for the page to load and start. Sending arrows in four directions 4) When the game is over, automatically try again 5) Infinite loop steps 3 and 4 are interested You can give it a try, it’s still interesting~~ def play2048():
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
# 打开firefox,并访问2048游戏界面
bs = webdriver.Firefox()
bs.get('https://gabrielecirulli.github.io/2048/')
html = bs.find_element_by_tag_name('html')
while True:
print('send up,right,down,left')
html.send_keys(Keys.UP)
time.sleep(0.3)
html.send_keys(Keys.RIGHT)
time.sleep(0.3)
html.send_keys(Keys.DOWN)
time.sleep(0.3)
html.send_keys(Keys.LEFT)
time.sleep(0.3)
# 每四个方向操作后判断游戏是否结束
game_over = bs.find_element_by_css_selector('.game-message>p')
if game_over.text == 'Game over!':
score = bs.find_element_by_class_name('score-container') #当前得分
print('game over, score is %s' % score.text)
print('wait 3 seconds, try again')
time.sleep(3)
# 游戏结束后,等待3秒,自动点击try again重新开始
try_again = bs.find_element_by_class_name('retry-button')
try_again.click()
The above is the detailed content of How to automatically hang up the 2048 game. For more information, please follow other related articles on the PHP Chinese website!