Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 41 ยท Packaging and Next Steps

Saving High Scores and Settings in Pygame

Persist game data in Pygame: JSON high score tables, user settings, safe file locations per operating system, atomic writes, validation and handling corrupt save files.

A game that forgets everything when you close it is a toy. Players expect their high scores, volume setting, chosen controls and level progress to be there tomorrow. Python makes saving easy: a small JSON file is enough for nearly every game.

In this lesson you will save and load a high score table and a settings file, choose a safe folder on each operating system, write files so that a crash cannot corrupt them, and cope with missing or broken data. Pygame is not involved in the file handling, so every example runs here, using an in-memory stand-in for the disk where a real folder would be.

Why JSON

JSON is plain text that Python can read and write with one function call, humans can open and edit, and it survives game updates well, since unknown keys can be ignored. Use pickle rarely: it can run arbitrary code when loading a tampered file and breaks when your classes change.

Python
import json

settings = {"music_volume": 0.4, "sfx_volume": 0.8, "fullscreen": False,
            "keys": {"jump": "space", "left": "a", "right": "d"}}

text = json.dumps(settings, indent=2)      # Python -> JSON text
back = json.loads(text)                    # JSON text -> Python

JSON supports dictionaries, lists, strings, numbers, booleans and null. Tuples become lists and dictionary keys become strings, which is worth remembering for grid coordinates.

Python Round trip a settings dictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The tuple became a list and the integer keys became strings, so the round trip is not identical. Convert on load (tuple(back["resolution"])) when types matter.

Where to store files

Do not write next to your script: when the game is installed in Program Files or packaged as one executable, that folder is read-only or temporary. Use a per-user data folder:

System Typical location
Windows %APPDATA%\MyGame
macOS ~/Library/Application Support/MyGame
Linux ~/.local/share/MyGame (or $XDG_DATA_HOME)
Python
import os, sys
from pathlib import Path

def save_dir(game_name):
    if sys.platform == "win32":
        base = Path(os.environ.get("APPDATA", Path.home()))
    elif sys.platform == "darwin":
        base = Path.home() / "Library" / "Application Support"
    else:
        base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
    folder = base / game_name
    folder.mkdir(parents=True, exist_ok=True)
    return folder

The package platformdirs does the same job in one call if you accept an extra dependency.

A high score table

A table keeps the top ten entries sorted. Insert, sort, trim, and tell the caller whether the player made the list.

Python
class HighScores:
    def __init__(self, path, limit=10):
        self.path, self.limit = path, limit
        self.entries = self.load()

    def load(self):
        try:
            data = json.loads(self.path.read_text(encoding="utf-8"))
            return [e for e in data if isinstance(e.get("score"), int) and isinstance(e.get("name"), str)]
        except (FileNotFoundError, json.JSONDecodeError, AttributeError, TypeError):
            return []                               # first run or damaged file

    def qualifies(self, score):
        return len(self.entries) < self.limit or score > self.entries[-1]["score"]

    def add(self, name, score):
        self.entries.append({"name": name[:12], "score": score})
        self.entries.sort(key=lambda e: e["score"], reverse=True)
        del self.entries[self.limit:]
        self.save()
        return self.entries.index({"name": name[:12], "score": score}) + 1   # rank

Always catch the specific errors that reading can raise. A missing file on first launch is normal, not an error to show the player.

Python A high score table in memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The table never grows past five, "Zed" with 50 does not qualify, and a fresh HighScores(store) reads the saved text back.

Safe writes: never half-save a file

If the game crashes or the power fails while write_text is running, the file can be left half-written and unreadable, which would delete the player's progress. The safe pattern is to write a temporary file and then atomically replace the original:

Python
import os, tempfile

def atomic_write(path, text):
    fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            f.write(text)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, path)          # atomic on Windows, macOS and Linux
    except BaseException:
        os.unlink(tmp)
        raise

os.replace swaps the file in a single step, so a reader sees either the old complete file or the new complete file, never a mix. Keep one backup (save.json.bak) for important progress.

Settings with defaults and validation

Never trust the file. It may be missing keys (from an older version), have wrong types (edited by hand) or out-of-range numbers. Start from defaults and overlay only valid values:

Python Load settings safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every input produces a usable dictionary. Values were clamped, wrong types ignored, and missing keys filled from DEFAULTS, so adding a new setting in a game update needs no migration code.

Versioning your save data

When your save format changes, store a version number and convert old files on load:

Python
SAVE_VERSION = 2

def migrate(data):
    version = data.get("version", 1)
    if version == 1:
        data["lives"] = 3          # new in v2
        version = 2
    data["version"] = version
    return data

What not to save

  • Passwords or personal data: a game rarely needs them.
  • Absolute paths, which break on another computer.
  • Anything the player can edit to cheat, if cheating matters. Online leaderboards need a server; a local file can always be edited, so treat local scores as friendly, not secure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is JSON usually preferred over pickle for save files?

    pickle can execute code from a tampered file and breaks when classes change, while JSON is plain data.
  2. 2. Where should a packaged game write its save files?

    The install folder may be read-only; per-user folders are writable and survive updates.
  3. 3. What does os.replace(tmp, path) guarantee?

    Writing to a temporary file and replacing it atomically prevents half-written saves.
  4. 4. A settings file has "music_volume": 7. What should the loader do?

    Treat the file as untrusted input: validate and clamp values.

Summary

  • JSON files are the easiest way to save scores, settings and progress; remember that tuples become lists and keys become strings.
  • Use a per-user data folder, not the game's install directory.
  • Keep sorted, trimmed high score lists and handle a missing file as a normal first run.
  • Write atomically (temporary file, then os.replace) and validate everything you load, falling back to defaults.
  • Add a version number so you can migrate old saves.

Next: Performance and Debugging