如何用Python将Pokemon Top Trumps游戏分数写入文件并读取?
Pokemon Top Trumps 分数存储功能实现方案
要实现分数的写入和读取,我们可以通过Python的文件操作完成,分为读取历史分数和保存当前游戏分数两个核心步骤,以下是具体实现:
一、核心逻辑说明
- 读取历史分数:游戏启动时尝试从文件(比如
pokemon_scores.txt)读取之前的分数记录,若文件不存在则初始化记录。 - 保存当前分数:当玩家选择结束游戏时,将本次游戏的玩家名称、玩家分数、对手分数写入文件,可选择追加记录或覆盖最新记录。
二、修改后的完整代码
import random import requests # 定义获取随机宝可梦的函数(移到循环外,避免重复定义) def random_pokemon(): pokemon_number = random.randint(1, 151) url = f'https://pokeapi.co/api/v2/pokemon/{pokemon_number}/' response = requests.get(url) pokemon = response.json() return { 'name': pokemon['name'], 'id': pokemon['id'], 'height': pokemon['height'], 'weight': pokemon['weight'], 'hp': pokemon['stats'][0]['base_stat'], 'attack': pokemon['stats'][1]['base_stat'], 'defense': pokemon['stats'][2]['base_stat'], 'special-attack': pokemon['stats'][3]['base_stat'], 'special-defense': pokemon['stats'][4]['base_stat'], 'speed': pokemon['stats'][5]['base_stat'], } # ---------------------- 读取历史分数 ---------------------- score_file = 'pokemon_scores.txt' try: with open(score_file, 'r', encoding='utf-8') as f: print("=== 历史游戏记录 ===") for line in f: print(line.strip()) print("===================") except FileNotFoundError: print("暂无历史游戏记录") # 初始化当前游戏分数 my_score = 0 opponent_score = 0 print("\n~~ Welcome to the Pokemon Top Trumps Game! ~~") player1name = input("Player 1, please enter your name: ") print(f"Hello {player1name}, get ready to enter the world of Pokemon!\n") choice = True while choice: my_pokemon = random_pokemon() print(f'You were given {my_pokemon["name"]}') stat_choice = input( 'Which stat do you want to use? (id, height, weight, hp, attack, defense, special-attack, special-defense, speed) ') opponent_pokemon = random_pokemon() print(f'The opponent got {opponent_pokemon["name"]}') my_stat = my_pokemon[stat_choice] opponent_stat = opponent_pokemon[stat_choice] if my_stat > opponent_stat: print(f'Your value: {my_stat}') print(f'Opponent value: {opponent_stat}') print('You Win!') my_score += 1 print(f"Your points: {my_score}") elif my_stat < opponent_stat: print(f'Your value: {my_stat}') print(f'Opponent value: {opponent_stat}') print('You Lose!') opponent_score += 1 print(f"Opponent points: {opponent_score}") else: print(f'Your value: {my_stat}') print(f'Opponent value: {opponent_stat}') print('Draw!') play_again = input('Play again? (Y/N): ') if play_again.upper() != 'Y': choice = False # ---------------------- 保存当前游戏分数 ---------------------- # 用追加模式('a')保存每次游戏记录,若想只保留最新记录可改为('w')覆盖模式 with open(score_file, 'a', encoding='utf-8') as f: record = f"玩家: {player1name} | 你的分数: {my_score} | 对手分数: {opponent_score}\n" f.write(record) print(f"本次游戏记录已保存到 {score_file}")
三、关键代码解释
- 函数位置调整:把
random_pokemon()移到while循环外,避免每次循环重复定义函数,提升代码效率。 - 读取历史记录:使用
try-except处理文件不存在的情况,确保程序不会崩溃;若文件存在则逐行打印历史记录。 - 保存记录:游戏结束时用
with open(..., 'a')以追加模式写入文件,每次游戏记录会新增一行,方便查看所有历史成绩;如果只需要保留最新一次的成绩,将'a'改为'w'即可覆盖原有内容。
内容的提问来源于stack exchange,提问作者Ele C
相关产品推荐
相关产品推荐

