如何通过保存和加载json文件来实现我的程序中的排行榜字典?

z3yyvxxp  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(66)

我用pygame编写了一个经典的贪吃蛇。我想保存前5名的分数,当有人击败其中一个分数时,游戏会覆盖当前的最高记录。前5名的字典会是什么样子,我如何制作一个JSON文件来覆盖分数并保存它们。当你打开游戏时,它会自动加载排行榜。
我试过这个,但我不知道它是如何工作的,因为我从来没有用过json文件:

#creating a json file for top scores
#making the dictionary
top5 = {
    "1": 0,
    "2": 0,
    "3": 0,
    "4": 0,
    "5": 0
}
 
#serializing json
json_object = json.dumps(top5, indent=5)

#writing to json file
with open('topfive.json', 'w') as outfile:
    outfile.write(json_object)
 
#opening json file
with open('topfive.json', 'r') as openfile:
    json_object = json.load(openfile) #reading from json

字符串

nhaq1z21

nhaq1z211#

假设导入了json,代码应该可以正常工作
如果在代码中添加一些print语句,可以看到它正在工作

import json

# creating a json file for top scores
# making the dictionary
top5 = {"1": 4, "2": 4, "3": 3, "4": 1, "5": 0}

# serializing json
json_object = json.dumps(top5, indent=5)

# writing to json file
with open("topfive.json", "w") as outfile:
    outfile.write(json_object)

# opening json file
with open("topfive.json", "r") as openfile:
    json_object = json.load(openfile)  # reading from json

    print(json_object)
    print(type(json_object))
    print(json_object["1"])

字符串
输出将是

{'1': 4, '2': 4, '3': 3, '4': 1, '5': 0}
<class 'dict'>
4

更好的实现

另一种更可读的实现是将分数存储为数组,而不是字典中的字符串索引,每当用户有新分数时,您就将其添加到数组中,按如下方式对其进行排序和截断

import json

def load_leaderboard():
    try:
        with open("top_five.json", "r") as infile:
            leaderboard = json.load(infile)
    except (FileNotFoundError, KeyError):
        leaderboard = []
    return leaderboard

def update_leaderboard(new_score):
    leaderboard = load_leaderboard()

    leaderboard.append(new_score)

    # Order the leaderboard by score in descending order
    leaderboard.sort(reverse=True)

    # Keep only the top 5 scores
    leaderboard = leaderboard[:5]

    with open("top_five.json", "w") as outfile:
        json.dump(leaderboard, outfile, indent=4)

# Example usage:

update_leaderboard(100)
update_leaderboard(200)
update_leaderboard(120)
update_leaderboard(130)
update_leaderboard(180)

print("Updated Leaderboard:", load_leaderboard())

update_leaderboard(90)  # should not be added to the leaderboard
update_leaderboard(10)  # should not be added to the leaderboard

print("Updated Leaderboard:", load_leaderboard())

update_leaderboard(500)  # should be added to the leaderboard

print("Updated Leaderboard:", load_leaderboard())


输出将是:

Updated Leaderboard: [200, 180, 130, 120, 100]
Updated Leaderboard: [200, 180, 130, 120, 100]
Updated Leaderboard: [500, 200, 180, 130, 120]

相关问题