尝试将外部分数文件添加到Python猜测游戏

2024-04-29 05:17:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为学校制作一个Python猜谜游戏。 游戏本身运行良好,但我需要添加一个外部分数文件(.txt) 我尝试了很多不同的方法来实现这一点,但我遇到的问题是; 如果文件中存在用户名,如何更新该用户名的分数线

最后一个方法(在代码中)只是一个测试,如果找不到新用户名,则将其添加到文件中。这似乎覆盖了文件,没有添加新的用户名

# Import random library
import random
import os

# Welcome User to the game
print("Welcome to the game")

# Collect user details
userName = input("Please enter your Name: ")

# Roll the die for the number of guesses
print("Rolling the Dice!")
diceRoll = random.randint(1,6)
print("You have %d Guesses: " %diceRoll)

# Random picks the number to guess
number = random.randint(1,99)

guesses = 0
win = 0
lose = 0

# Loop checks the users input against the randint and supplies a hint, or breaks if correct
while guesses < diceRoll:
    guess = int(input("Enter a number from 0 to 99: "))
    guesses += 1
    print("This is guess %d " %guesses)

    if guess > 100:
        print("Number out of range. Lose a turn")

    if guess < number:
        print("You guessed to low")

    elif guess > number:
        print("you guessed to high")

    elif guess == number:
        guesses = str(guesses)
        print("You Win! you guessed the right number in",guesses + " turns")
        win = +1
        break

# If the user cannot guess the number in time, they receive a message    
if guess !=number:
    number = str(number)
    print("You Lose. The number was: ",number)
    lose = +1

with open('scoreList.txt', 'r') as scoreRead:
    with open('scoreList.txt', 'w') as scoreWrite:
        data = scoreRead.readlines()
    for line in data:
        if userName not in line:
            scoreWrite.write(userName + "\n")
    scoreRead.close()
    scoreWrite.close()

分数文件的格式是什么并不重要,只要我可以在游戏开始时输入现有分数的名称时编辑它们。如果新用户不存在,请添加新用户。然后在每场比赛结束时打印分数

我完全不知所措


Tags: 文件thetointxtyou游戏number
2条回答

你在最后一个街区有多处失误。您可以打开scoreList.txt,但在with .. as块之外执行写操作。在此块之外,文件将关闭。另外,由于您使用的是with .. as,因此最终不必手动关闭文件

然后,您迭代所有行,并为不包含它的每一行编写名称,可能会重复很多次。然后用'w'打开文件,告诉它覆盖。如果要追加,请使用'a'

试着这样做:

with open('scoreList.txt', 'r') as scoreRead:
    data = scoreRead.readlines()
with open('scoreList.txt', 'a') as scoreWrite:
    if userName + "\n" not in data:
        scoreWrite.write(userName + "\n")

另外请注意,您当前正在将每个名字写入得分列表,而不仅仅是那些赢得比赛的名字

我相信您可以使用json模块实现这一点,因为它将允许使用json文件格式的字典中的数据

字典将是存储用户和相关分数的最佳方法,因为如果使用相关文本文件,在python中更容易访问这些值

我已使用有效的解决方案更新了您的代码:

#! usr/bin/python

# Import random library
import random
import os
import json

# Welcome User to the game
print("Welcome to the game")

# Collect user details
userName = input("Please enter your Name: ")

#Added section
current_player = {"name": userName,
                    "wins": 0,
                    "losses": 0,
                    }

try:
    with open('scores.json', 'r') as f:
        data = json.load(f)

    for i in data['players']:
        if i["name"] == current_player["name"]:
            current_player["wins"] = i["wins"]
            current_player["losses"] = i["losses"] 
except:
    pass

print(current_player)
#end added section

"""begin game"""
# Roll the die for the number of guesses
print("Rolling the Dice!")
diceRoll = random.randint(1,6)
print("You have %d Guesses: " %diceRoll)

# Random picks the number to guess
number = random.randint(1,99)

guesses = 0
win = 0
lose = 0

# Loop checks the users input against the randint and supplies a hint, or breaks if correct
while guesses < diceRoll:
    guess = int(input("Enter a number from 0 to 99: "))
    guesses += 1
    print("This is guess %d " %guesses)

    if guess > 100:
        print("Number out of range. Lose a turn")

    if guess < number:
        print("You guessed to low")

    elif guess > number:
        print("you guessed to high")

    elif guess == number:
        guesses = str(guesses)
        print("You Win! you guessed the right number in", guesses + " turns")
        win = +1
        break

# If the user cannot guess the number in time, they receive a message    
if guess !=number:
    number = str(number)
    print("You Lose. The number was: ", number)
    lose = +1
"""end game"""

#added section
current_player["wins"] += win
current_player["losses"] += lose

try:
    for i in data['players']:
        if current_player["name"] == i["name"]:
            i["wins"] = current_player["wins"]
            i["losses"] = current_player["losses"]

    if current_player not in data['players']:
        data['players'].append(current_player)


    print("Current Scores:\n")
    for i in data['players']:

        print(i["name"], ": wins", i["wins"], " losses: ", i["losses"])

    with open('scores.json', 'w') as f:
        f.write(json.dumps(data))
except:
    start_dict = {"players":[current_player]}
    with open('scores.json', 'w') as f:
        f.write(json.dumps(start_dict))
    print("Current Scores:\n")
    for i in start_dict['players']:
        print(i["name"], ": wins", i["wins"], " losses: ", i["losses"])
#end added section

这将检查JSON文件中是否存在当前玩家,然后将他们的分数添加到当前玩家字典中

在游戏结束时,它将检查是否:

  1. 文件scores.json存在,如果不存在,将创建它
  2. 当前玩家存在于scores.JSON文件中,如果存在,将更新他们的分数。如果他们不这样做,它将向JSON文件添加一个新用户

然后将相应地打印分数列表。 不过要小心,如果用户名有任何错误,就会创建一个新用户

如果需要,还可以手动更新.json文件中的分数

相关问题 更多 >