前言
2048游戏您玩过吗?https://gabrielecirulli.github.io/2048/ 可以在线玩
人的精力总是有限的,不可能没日没夜的玩,但机器可以;做一个自动玩2048游戏的小功能,熟悉selenium的使用
分析
2048游戏本质就是通过四个方向键,来合成数字,其实过程单一、枯燥(先不关注人的思考问题),机器就擅长干这事。
使用selenium可以打开浏览器,发送键盘指令等一系列操作;
游戏会有game over的时候,selenium发送四个方向键指令是常态,那么解决game over问题就是特殊处理
标签
1)得分:d2df9353bb63b9dcc0dd059eb0258fde08b3457a4573b6dc8e4ec19c91471719a
2)game over : 85e68feace15eba8aee7cb16033042a5ab6f3b1e90a946996cff414f69232a8bgame over!cce7ef22a65adee44a4800849cb869c116b28748ea4df4d9c2150843fecfba68
注:在正常游戏状态下,e388a4556c0f65e1904146cc1a846bee值为空,游戏结束时显示game over!,根据这个特征来判断游戏是否结束
3)try again : 32cdfe679c9dc4be724eaaa0504aa749try again43f9c1b6599ebf6d9427b3cde7d6cda8
注:当游戏结束时,需找到该按钮,点击它重新继续开始游戏
环境
1)windows 7
2)这是一个简单的功能,直接在python idle下编写
3)使用的是firefox浏览器,需要安装驱动,可以到这下载(),我是直接放在system32下
源代码
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()
运行
在python idle下,调用play2048()即可,程序自动执行的步骤为:
1)打开firefox
2)在当前打开的firefox窗口,访问https://gabrielecirulli.github.io/2048/
3)等待页面加载完成,开始进行四个方向箭的发送
4)当game over时,自动try again
5)无限循环步骤3和4
有兴趣的可以试一试,还是有点意思的~~
以上就是如何自动挂机2048游戏的详细内容。