-1

I was coding a "game" in pygame and wanted to store highscore, as a variable that takes the player's highest score and saves it. I would want it to look something like this:

if score > highscore:
     highscore = score

Maybe I could save this in a separate text file, any suggestions??

Edit: I want to be able to close the console between times playing the game and still have the highscore save

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Fishy
  • 76
  • 7

1 Answers1

1

I would use the JSON library that is built-in to Python 3:

You just have to import the library, make a dictionary with the highscore set, stringify, and save.

import json

savedata = {}

def exportSavedata():
    with open('data.json', 'w') as outfile:
        json.dump(savedata, outfile)

After that, just make a function that loads the high-score, and run it whenever the game starts:

def loadSavedata():
    with open('path_to_file/person.json') as infile:
        savedata = json.load(infile)

Then just use the savedata dictionary to store game data and high scores, and run the save function to export it to the file.

  • Viable answer for sure, storing to file requires the least prerequisites. Use a dictionary `{}` as the answer shows and you'll get very simple and obvious JSON outcomes. – stormlifter Feb 17 '21 at 19:12