python學習:(2)自動玩2048游戲


前言

  2048游戲您玩過嗎?https://gabrielecirulli.github.io/2048/ 可以在線玩

  人的精力總是有限的,不可能沒日沒夜的玩,但機器可以;做一個自動玩2048游戲的小功能,熟悉selenium的使用

分析

  2048游戲本質就是通過四個方向鍵,來合成數字,其實過程單一、枯燥(先不關注人的思考問題),機器就擅長干這事。

  使用selenium可以打開瀏覽器,發送鍵盤指令等一系列操作;

  游戲會有game over的時候,selenium發送四個方向鍵指令是常態,那么解決game over問題就是特殊處理

標簽

  1)得分:<div class="score-container">0</div>

  2)game over : <div class="game-message"><p>Game over!</p></div> 

    注:在正常游戲狀態下,<p>值為空,游戲結束時顯示Game over!,根據這個特征來判斷游戲是否結束

  3)try again : <a class="retry-button">Try again</a>

    注:當游戲結束時,需找到該按鈕,點擊它重新繼續開始游戲

環境

  1)windows 7

  2)這是一個簡單的功能,直接在python IDLE下編寫

  3)使用的是firefox瀏覽器,需要安裝驅動,可以到這下載(https://github.com/mozilla/geckodriver/releases/),我是直接放在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

 

有興趣的可以試一試,還是有點意思的~~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM