如何在单人游戏的文本文件中为前 5 名玩家创建一个简单的有序排行榜

我正在做一个 1 名球员测验,需要实施一个高分系统,记录前 5 名高分球员的分数和适合该得分球员的球员姓名。这应该写入文本文件 (.txt) 并在分数更高时覆盖(从 1. 最高分到 5. 最低分排序)。如果有人可以分享一些我可以用于我的高分系统的代码,那将非常有帮助。


通过 n 轮的玩家应该从最高 n 分到最低 n 分排序。它应该在 txt 文件中包含前 5 个 n 分数,并按顺序排列。


我已经看了几个小时的论坛,但无法在我的代码中实现我发现的代码。旁注:我根本不知道该怎么做


counter = 0

print("The songs' initials are " ,initialsofsong, " and the name of the artist is " ,randomartist)

print (randomsong)

songnameguess = input("Guess the name of the song!")

counter = counter + 1

while counter < 3 and songnameguess != randomsong :

        songnameguess = input("Nope! Try again!")

        counter = counter + 1

if songnameguess == randomsong:

    print ("Well done!")

    if counter == 2:

        score = score + 1

    elif counter == 1:

        score = score + 3


elif counter >=3 and songnameguess != randomsong:

    print ("Sorry, you've had two chances. Come back soon!")

    print ("Game over.")

    print (score)


jeck猫
浏览 217回答 2
2回答

慕森卡

您可以以多种格式存储分数,我将使用json,因为它是可读且内置的:score_file = r"/pat/to/score/file.json"# at the beginning of your script: load the current scorestry:&nbsp; &nbsp; with open(score_file, 'r') as f:&nbsp; &nbsp; &nbsp; &nbsp; scores = json.load(f)except FileNotFoundError:&nbsp; &nbsp; scores = {}# (...)# during your script: update the scores with the player's newscores[player_name] = new_score# (...)# at the end of your script: store the new scoreswith open(score_file, 'w+') as f:&nbsp; &nbsp; json.dump(scores, f)打印你的分数排序:scores_sorted = sorted([(p, s) for p, s in scores.items()], reverse=True, key=lambda x: x[1])for player, score in scores_sorted:&nbsp; &nbsp; print(player, score)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python