#chatgpt-4
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 获取游戏状态
def get_game_state(driver):
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
grid_container = soup.find('div', {'class': 'tile-container'})
return str(grid_container)
# 获取当前分数
def get_current_score(driver):
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
score_container = soup.find('div', {'class': 'score-container'})
score_text = score_container.contents[0].strip()
return int(score_text)
# 检查游戏是否结束
def game_over(driver):
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
game_over_text = soup.find('div', {'class': 'game-message game-over'})
return game_over_text and 'Game over!' in game_over_text.text
# 主执行函数
def main():
# 设置WebDriver
driver = webdriver.Edge()
driver.get("https://marysera.github.io")
# 等待页面加载
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
# 找到游戏主体
body = driver.find_element(By.TAG_NAME, 'body')
actions = [Keys.LEFT, Keys.DOWN, Keys.RIGHT, Keys.DOWN]
while True:
state_before = get_game_state(driver)
for action in actions:
body.send_keys(action)
time.sleep(0.2) # 调整游戏速度,提高响应速度
if game_over(driver):
print('游戏结束!')
current_score = get_current_score(driver)
print('最终分数:', current_score)
return
state_after = get_game_state(driver)
if state_before == state_after: # 状态没有变化
body.send_keys(Keys.UP)
if game_over(driver):
print('游戏结束!')
current_score = get_current_score(driver)
print('最终分数:', current_score)
return
if __name__ == "__main__":
main()