【问题标题】:Trying to add an external Score File to a Python Guessing Game尝试将外部分数文件添加到 Python 猜谜游戏
【发布时间】:2020-09-23 05:40:50
【问题描述】:

我正在为学校创建一个 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()

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

我完全不知所措。

【问题讨论】:

    标签: python text-files


    【解决方案1】:

    您在最后一个区块中有多个错误。您打开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")
    

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

    【讨论】:

    • 哈哈谢谢老兄。是的,我最终使用 append 完全重做了整个块。没有文件关闭和一个打开而不是两个。这整件事让我发疯了一段时间
    【解决方案2】:

    我相信您可以使用 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. 文件 score.json 存在,如果不存在,将创建它。
    2. 当前玩家存在于 score.JSON 文件中,如果存在,将更新他们的分数。如果他们不这样做,它将向 JSON 文件添加一个新用户。

    然后将相应地打印分数列表。 但请注意,如果用户名以任何方式拼写错误,则会创建一个新用户。

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

    【讨论】:

    • 有趣的想法,但我认为它不符合包含获胜者姓名的简单.txt 文件的要求,对吧?
    • 是的,但我认为 OP 想要一个包含名称和分数的文件,所以这种方法允许添加/更新参与者的分数。
    • 如果我是为自己做这件事,那将是一个很好的方法,但不幸的是,简报要求专门使用文本文件。不过还是谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多