为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

jeck猫 2021-10-19 16:13:17
我正在做一个 1 名球员测验,需要实施一个高分系统,记录前 5 名高分球员的分数和适合该得分球员的球员姓名。这应该写入文本文件 (.txt) 并在分数更高时覆盖(从 1. 最高分到 5. 最低分排序)。如果有人可以分享一些我可以用于我的高分系统的代码,那将非常有帮助。通过 n 轮的玩家应该从最高 n 分到最低 n 分排序。它应该在 txt 文件中包含前 5 个 n 分数,并按顺序排列。我已经看了几个小时的论坛,但无法在我的代码中实现我发现的代码。旁注:我根本不知道该怎么做counter = 0print("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 + 1while counter < 3 and songnameguess != randomsong :        songnameguess = input("Nope! Try again!")        counter = counter + 1if songnameguess == randomsong:    print ("Well done!")    if counter == 2:        score = score + 1    elif counter == 1:        score = score + 3elif counter >=3 and songnameguess != randomsong:    print ("Sorry, you've had two chances. Come back soon!")    print ("Game over.")    print (score)
查看完整描述

2 回答

?
慕森卡

TA贡献1806条经验 获得超8个赞

您可以以多种格式存储分数,我将使用json,因为它是可读且内置的:


score_file = r"/pat/to/score/file.json"


# at the beginning of your script: load the current scores

try:

    with open(score_file, 'r') as f:

        scores = json.load(f)

except FileNotFoundError:

    scores = {}


# (...)


# during your script: update the scores with the player's new

scores[player_name] = new_score


# (...)


# at the end of your script: store the new scores

with open(score_file, 'w+') as f:

    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:

    print(player, score)


查看完整回答
反对 回复 2021-10-19
  • 2 回答
  • 0 关注
  • 216 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号