1

I have my score in a while loop in pygame, so it looks something like this.

score = 0
while True: 
     score += 0.1
     text = font.render("Score: "+str(int(score)), True, (255, 255, 255))
     display.blit(text, (0,0))

How would I get my program to store a new high score every time the player beats his old high score. And how do you even store a score? I want the score to be the same if the user closes the program and opens it later. If this is possible can someone explain it.

T Ali
  • 43
  • 5
  • If you want to store player related data (i.e their high score), you'll need to write to a file in some kind of data format. Perhaps [JSON](https://docs.python.org/3/library/json.html). – Christian Dean Jan 15 '18 at 22:07
  • The duplicate - link question contains an example for a "log file type" leaderboard, the answer uses a mongodb - have a look at them, they should point you in the right direction. On new highscore, save data to file, on game start, load data into a dict and compare it against reached scores. – Patrick Artner Jan 15 '18 at 22:10
  • well I don't really need a leader board cause the user is anonymous and his new score just replaces his old one if he gets a higher score. But thx this should help. – T Ali Jan 15 '18 at 22:51

1 Answers1

3

In essence, you want to store data in a way that can be retrieved after the game has ended.

This can be done by writing the relevant data/variable content to a file with either a predetermined format(JSON) or your own simple format. Either way you should be able to correctly parse the information when the game starts.

How to do this:

  • Identify the point in your code where you should open the file and write the new high score to the file.

  • Check if a new file must be created. If so, then create it.

  • Implement the code which will write the high score to the file.

  • When the game starts up again you must open the file in "read-only" mode and retrieve the information.

Note: Make sure you close all files that you open to prevent memory leakage.

I hope that this answer helped you and if you have any further questions please feel free to post a comment below!

Micheal O'Dwyer
  • 1,237
  • 1
  • 16
  • 26