Home > Blockchain >  creating a leaderboard for noughts and crosses game
creating a leaderboard for noughts and crosses game

Time:12-19

{"Bob": 50,"Jane": 2,"Sarah": 5, "Amelia": 20}

I have a txt file like this and I wrote a code to be able to get different players name and score that will be saved to the dictionary from highest to lowest.but when ever a new player saves their name&score, my txt file create a new dictionary like this ("

{"tie": 0}{"bobby": 0}

"). here is my code>

import json
import os
def save_score(score):
    filename = 'leaderboard.txt'
    player = input('what is your name')
    dictionary = {}
    if os.path.exists(filename):
        with open("leaderboard.txt", "a") as leaderboard:
            dictionary[player]=score
            json.dump(dictionary,leaderboard)
        print("score"  " "   str(score)  " "  "for"   " "  str(player)  " " "saved.")
    return

I want to be able to append and also update the new players name and score to the existing dictionary. eg. if bob plays and gets 5{"bob": 5}, and he plays again and gets 7. instead of creating a new dictionary for bob it should update {"bob": 5} to {"bob": 6}. and also if new users play the game, their name and score should be added to the same dictionary with bob. {"bob": 5}. instead of creating a new dictionary. so instead of this {"bob": 5} {"tina": 5}. I want to have this {"bob": 5, "tina": 1}. please how do I go on about it?. thanks in advance.

CodePudding user response:

First load the scores from the file with json.load, then change the score of the specific player, then save the scores back to the file with json.dump.

with open("leaderboard.txt", "r ") as leaderboard:
    dictionary = json.load(leaderboard)
    dictionary[player] = score
    json.dump(dictionary,leaderboard)
  • Related