我是Python新手,正在经历“自动化无聊的东西”——阿尔·斯维加特
我写了一个脚本,在“https://gabrielecirulli.github.io/2048”玩“2048”瓷砖游戏。在几次移动之后,平铺游戏将“最大输出”,并弹出一个“游戏结束!”,我还不知道如何读取它-因此,我实现了逻辑,在每4次移动后读取分数,确定分数是否停止增加,如果是,游戏结束
我发现我读分数的语句返回了一个错误有时。我不明白为什么它要么有效,要么无效。为什么它有时会返回错误
我把它放在一个try/except块中,所以如果我得到一个错误,我就把它加起来。有时是一些,有时是大约一半的时间
如果有任何帮助或建议,我将不胜感激
谢谢
output...
Evolutions: 40 oldScore1308 newScore: 1736
Evolutions: 41 oldScore1736 newScore: 1736
GAME OVER!
Good Game.
Final Score:
Evolutions: 41 OldScore1736 NewScore: 1736 Errors:23
Pausing before program closes. Hit enter to continue.
代码:
#! python
import webbrowser
from selenium import webdriver
from selenium.webdriver.common.keys import Keys # import Keys to send special keys
from selenium.common.exceptions import NoSuchElementException
import time
def opensite():
# open browser
global browser # stop chrome window from closing by itself.
browser = webdriver.Chrome()
browser.get("https://gabrielecirulli.github.io/2048")
return browser
def botKeys():
# function to send arrow keys to browser :up, right, down, left.
w = 0.025 # time to wait between plays
try:
element = browser.find_element_by_tag_name("body")
gameOn = True
counter = 0
oldScore = 0
error = 0
while gameOn == True:
counter += 1
# Send keys to move pieces
time.sleep(w)
element.send_keys(Keys.UP)
time.sleep(w)
element.send_keys(Keys.RIGHT)
time.sleep(w)
element.send_keys(Keys.DOWN)
time.sleep(w)
element.send_keys(Keys.LEFT)
# check the score. Keep track of it to determine if GAME OVER!
try:
newScore = browser.find_element_by_class_name(
"score-container"
) # get the object with the score.
newScore = int(
newScore.text
) # read the text of the object, which is the score in a string. Convert it to an integer.
print(
f"Evolutions: {counter} oldScore{oldScore} newScore: {newScore}"
)
if oldScore != newScore:
oldScore = newScore
else: # old and new are the same, game over
print(f"GAME OVER!\nGood Game.")
print(f"\nFinal Score:")
print(
f"Evolutions: {counter} OldScore{oldScore} NewScore: {newScore} Errors:{error}"
)
gameOn = False
except ValueError:
error += 1 # count value errors, but that's all.
except NoSuchElementException:
print("Could not find element")
input("Pausing before program closes. Hit enter to continue.")
def main():
# TODO open the site
driver = opensite()
# TODO send keystrokes
botKeys()
driver.close()
if __name__ == "__main__":
main()
看起来不错!以下是我的解决方案:
如果显示错误
然后你就知道问题出在哪里了
问题是,有时它会显示结果
3060
,并将点添加到结果+20
当您在
\n
上拆分它并获取第一个元素时,它会正常工作要识别
Game Over
您需要但是,当没有类
game-over
时,它会产生错误,因此我将使用find_elements
(在单词find_elements
的末尾使用s
)来获取空列表,而不是生成错误顺便说一句:我改变了一些名字,因为PEP 8 Style Guide for Python Code
也许下一步是使用Gym(或类似的东西)来使用
Reinforcement Learning
(Machine Learning
,Artificial Intelligence
)相关问题 更多 >
编程相关推荐