How to save the max score in a game

This is an example of how someone could implement a system to save and load the maxscore for a game.

def get_maxscore() -> int:
    filename = "maxscore.txt"
    if filename in os.listdir():
        with open(filename, "r") as file:
            val = file.read()
            if val == "":
                maxscore = 0
            else:
                maxscore = int(val)
    else:
        maxscore = 0
    return maxscore


def set_score(maxscore) -> None:

    with open("maxscore.txt", "w") as file:
        file.write(str(maxscore))

The get_maxscore function

Call this function and it will load the score from a file that will be created the first time by the function itself. So you just have to put somewhere at the beginning of your code

maxscore = get_maxscore()

and you will have the maxscore memorized in the game.

Set_score

This function is to be called when the score the user is making is more than the previous maxiscore. Put a statement like this when you assign the score.

                if score > int(maxscore):
                    maxscore = score
                    set_score(maxscore)

so that if the score is greater it will take the place of the previous and then will be saved to a file through the set_score function.

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.