📝 Worksheet← Lesson← Course
BitWithBite
Pygame Mastery · Quick Reference

Save & Load Systems Cheat Sheet

Pygame Mastery
In one line: Persist player progress, settings and high scores with Python's json module — gather state into a dict, dump it to disk, load it back with safe fallbacks.

Key Ideas

1json module. Maps Python dicts/lists directly onto human-readable text — json.dump() writes, json.load() reads.
2Save pattern. Gather all state into one dict, open the file in "w" mode, then json.dump(data, f, indent=2).
3Load pattern. Check the file exists (or wrap in try/except); fall back to sensible defaults if it's missing or corrupted.
4Settings vs. progress. Keep settings.json separate from savegame.json so starting a New Game never wipes audio/display preferences.
5Merging defaults. DEFAULT_SETTINGS.copy(); merged.update(data) — defaults fill gaps left by an older save file.
6High scores. Append the new entry, sort(key=..., reverse=True), slice to [:MAX_ENTRIES], then save.
7Achievements. Each is {id, desc, check(stats)}; store unlocked ids in the save data so checks stay idempotent.
8Checkpoints. Just another field in the save dict — typically a level id plus an (x, y) spawn position.

Save / Load Core

import json, os
SAVE_FILE = "savegame.json"

def save_progress(data):
  with open(SAVE_FILE,"w") as f:
    json.dump(data, f, indent=2)

def load_progress():
  if not os.path.exists(SAVE_FILE):
    return DEFAULTS.copy()
  try:
    with open(SAVE_FILE) as f:
      return json.load(f)
  except (json.JSONDecodeError, OSError):
    return DEFAULTS.copy()

High-Score Add

scores.append({"name": n, "score": s})
scores.sort(
  key=lambda e: e["score"],
  reverse=True)
scores = scores[:MAX_ENTRIES]
save_highscores(scores)
save_data.jsonplayer{}settings{}high_scores[]
One JSON file, one dict — player state, settings and high scores each live in their own top-level key.