skip to Main Content

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


  1. When someone beats a high score, you can update the dictionary, by using

    for topscorer in top5.keys():
        if(new_highscore > top5[topscorer]):
            top5[topscorer] = new_highscore
            break
    

    and then do:

    open('topfive.json', 'w').close()
    

    to erase previous contents of the file, then do:

    top5_file = open("topfive.json", "w") 
      
    json.dump(top5, out_file, indent = 6)
    
    Login or Signup to reply.
  2. 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

    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"])
    
    

    the output would be

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

    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

    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())
    
    

    the output would be:

    Updated Leaderboard: [200, 180, 130, 120, 100]
    Updated Leaderboard: [200, 180, 130, 120, 100]
    Updated Leaderboard: [500, 200, 180, 130, 120]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search