I have made a very simple game in python using pygame. The score is based on whatever level the player reached. I have the level as a variable called score
. I want to display the top level at the start or end of the game.
I would be even more happy to display more than one score, but all of the other threads I have seen were too complicated for me to understand, so please keep it simple: I'm a beginner, only one score is necessary.
I recommend you use shelve. For example:
Next time you open your program use:
and it will be read from disk. You can use this technique to save a list of scores if you want in the same way.
I come from a Java background, and my Python isn't great, but I would look into the Python documentation on reading and writing to files: http://docs.python.org/2/tutorial/inputoutput.html
You could write a score variable to a plaintext file before you end the game, and then load the same file the next time you start the game.
Look into the
read()
,readline()
, andwrite()
methods.First create a highscore.txt with a value zero initially. Then use the following code:
I could make a permanent highscore storer with this simple method, no need for shelves or pickle.
I would suggest:
You can use the
pickle
module to save variables to disk and then reload them.Example:
This saves a single score to disk. The nice thing about pickle is that you can easily extend it to save multiple scores - just change
scores
to be an array instead of a single value.pickle
will save pretty much any type of variable you throw at it.You can use a dict to hold your highscore and simply write it into a file:
Usage:
Output: