PHP前端开发

如何自动挂机2048游戏

百变鹏仔 3小时前 #Python
文章标签 游戏

前言

2048游戏您玩过吗?https://gabrielecirulli.github.io/2048/ 可以在线玩

人的精力总是有限的,不可能没日没夜的玩,但机器可以;做一个自动玩2048游戏的小功能,熟悉selenium的使用

分析

2048游戏本质就是通过四个方向键,来合成数字,其实过程单一、枯燥(先不关注人的思考问题),机器就擅长干这事。

使用selenium可以打开浏览器,发送键盘指令等一系列操作;

游戏会有game over的时候,selenium发送四个方向键指令是常态,那么解决game over问题就是特殊处理

标签

1)得分:div >0div>

2)game over : div >p>Game over!p> 

注:在正常游戏状态下,

值为空,游戏结束时显示Game over!,根据这个特征来判断游戏是否结束

3)try again : a >Try againa>

注:当游戏结束时,需找到该按钮,点击它重新继续开始游戏

环境

1)windows 7

2)这是一个简单的功能,直接在python IDLE下编写

3)使用的是firefox浏览器,需要安装驱动,可以到这下载(),我是直接放在system32下

源代码  

def play2048():from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport 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

 

有兴趣的可以试一试,还是有点意思的~~