I programmed a classic Snake using pygame. i want to save the top 5 scores and when someone beats one of those scores the game overrides the current top records. what would the topfive dictionary look like and how can i make a json file to overwrite the scores and save them. Also when you open the game it will automatically load the leaderboard.
I tried this but i dont know how it works exactly because i never worked with json files before:
#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
2
Answers
When someone beats a high score, you can update the dictionary, by using
and then do:
to erase previous contents of the file, then do:
Your code should work fine, assuming you have imported
json
if you add some print statements to your code you can see it is working
the output would be
A better implementation
an alternative and more readable implementation would be to store the scores as an array instead of the string indexes in a dictionary, and whenever the user has a new score you add it to the array sort it and truncate it as follows
the output would be: