【问题标题】:How to fix my leaderboard for my Music Quiz如何修复我的音乐测验排行榜
【发布时间】:2020-12-18 05:18:08
【问题描述】:

我正在为一个学校项目做一个音乐测验。

我已经制作了一个可以运行的游戏,但是我无法让排行榜(应该是文本并保存为 leaderboard.txt)显示不同的名称,因为它会覆盖以前的名称。

例如,如果“Sam”得 9 分,“Ben”得 3 分,它会显示为“Ben-3-9”,这不是我想要的。

我正在尝试让我的排行榜像这样工作:

Sam - 9
Ben - 3
...

我的代码现在看起来像这样:

username = input("What is your username?")
# this will ask for the persons name
password = str(input("What is the password?"))

# this will ask for a password which has been set already
if password == "1234":
    print("User Authenticated")

# if the password is incorrect, tell the user so and exit
elif password != "1234":
    print("Password Denied")
    exit()

# GAME
# Creating a score variable
score=0
x = 0
# Reading song names and artist from the file
read = open("songnames.txt", "r")
songs = read.readlines()
songlist = []

# Removing the 'new line' code
for i in range(len(songs)):
    songlist.append(songs[i].strip('\n'))

while x == 0:
    # Randomly choosing a song and artist from the list
    import random
    choice = random.choice(songlist)
    artist, song = choice.split('-')

    # Splitting the song into the first letters of each word
    songs = song.split()
    letters = [word[0] for word in songs]

    # Loop for guessing the answer
    for x in range(0, 2):
        print(artist, "".join(letters))
        guess = str(input("Guess the song!"))
        if guess == song:
            if x == 0:
                score = score + 3
                break
            if x == 1:
                score = score + 1
                break
            quit()

    # Printing score, Then waiting to start loop again.
    import time
    print("Your score is", score)
    print("Nice Work!")
    time.sleep(3)

leaderboard = open("leaderboard.txt", "r+")
leaderboard.write(username + '-' + '{}'.format(score))
leaderboard.close()
leaderboard = open("leaderboard.txt", "r+")
leaderboardlist = leaderboard.readlines()
print(leaderboardlist)
leaderboard.close()

PS:这不是 100% 我的代码我正试图从不同的地方获得帮助,因为由于大流行关闭学校,我的学校还没有教我们如何编码。

【问题讨论】:

    标签: python leaderboard


    【解决方案1】:

    问题出在最后几行代码中,您正在写入 leaderboard.txt 文件。

    使用"r+" 表示您正在更新(读取和写入)文件。以这种方式打开文件,将光标移动到文件的开头。因此,任何写入文件的尝试都将覆盖已经存在的内容。

    正确的做法是使用"a"(或"a+",如果您也打算阅读)打开文件。这是append 模式,会将光标移动到文件末尾。

    其他一些一般说明:

    • 使用with-as 语句处理完成后自动关闭文件。
    • 使用 f-strings 而不是字符串连接来提高可读性

    考虑到这一点,代码如下:

    with open("leaderboards.txt", "a") as f:
        f.write(f"{username}-{score}")
    

    有关文件的更多信息,请查看this 问题。
    有关 f 字符串的更多信息,请查看 this 对它们的相当广泛的概述。

    【讨论】:

    • 谢谢亚历克斯,我不知道附加模式,使用它真的对我有帮助,我很感激你的帮助,它奏效了 :)
    【解决方案2】:

    当你这样做时:

    leaderboard = open("leaderboard.txt", "r+")
    leaderboard.write(username + '-' + '{}'.format(score))
    

    您以读写模式打开排行榜,但它会从文件的开头开始写入,覆盖其中的任何内容。如果你只是想在排行榜上添加新的分数,最简单的方法是以“追加”模式打开文件"a"

    with open("leaderboard.txt", "a") as leaderboard:
        leaderboard.write(username + '-' + '{}'.format(score))
    

    或者,您可以在"r" 模式下打开文件,然后首先读取列表或字典中的所有行(分数),将它们与当前玩家的新分数合并/更新(例如添加到最后一个分数,替换最后一个分数,或者获取该玩家新的和最后一个分数的max),然后以"w"模式再次打开文件并写入更新的分数。 (留给读者作为练习。)

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多