ThisCalculator

Everyday

Python Arcade Save/Load Game Data

Updated · Standard formula, shown below

Python Arcade provides a straightforward way to save and load game data using its built-in arcade module, primarily through JSON files. You can save player positions, scores, inventory, and any other serializable object, then reload it to resume a game exactly where it left off. This article explains the core concepts, provides working code examples, and covers common pitfalls and best practices.

Why Save and Load Matters

Persistent game data is essential for any game that expects players to return. Without it, every session starts from scratch, which is fine for arcade-style games but frustrating for RPGs, platformers, or puzzle games with progress. Saving lets players pause their journey, close the app, and pick up later. It also enables features like high-score tables, level editors, and cloud sync (if you add that later).

Python Arcade, being a modern library built on Pyglet, gives you full control over the file format. You are not locked into a proprietary binary format—you can use JSON, which is human-readable, easy to debug, and works with Python’s standard json module.

Core Concepts: What to Save

Before writing code, decide what data represents your game state. Typically you need:

  • Player state: position (x, y), health, score, current level, inventory items.
  • World state: which doors are open, which enemies are defeated, time remaining, collected flags.
  • Settings: volume, resolution, key bindings (often saved separately).

You can store these in a Python dictionary and then serialize it to JSON. For example:

game_data = {
    "player": {"x": 100, "y": 200, "health": 75, "score": 1500},
    "level": 3,
    "inventory": ["sword", "potion"],
    "doors_open": [True, False, True]
}

This dictionary is the heart of your save system. You can add or remove keys as your game evolves.

How to Save: Writing a JSON File

Python Arcade does not provide a dedicated save function—you use Python’s built-in json module. The typical pattern is:

  1. Build a dictionary containing all the data you want to persist.
  2. Open a file in write mode (using with open()).
  3. Use json.dump() to write the dictionary to the file.

Here is a minimal example inside an Arcade Window class:

import json
import arcade

class MyGame(arcade.Window):
    def save_game(self):
        data = {
            "player_x": self.player.x,
            "player_y": self.player.y,
            "score": self.score,
            "level": self.current_level
        }
        with open("savegame.json", "w") as f:
            json.dump(data, f)

Note that json.dump() writes the data as a single line. For readability, you can pass indent=4 to pretty-print it. That does not affect loading.

How to Load: Reading the JSON File

Loading is the reverse process. You read the file, parse the JSON into a dictionary, and then assign the values back to your game objects. A robust load function handles the case where the file does not exist or is corrupted.

def load_game(self):
    try:
        with open("savegame.json", "r") as f:
            data = json.load(f)
        self.player.x = data["player_x"]
        self.player.y = data["player_y"]
        self.score = data["score"]
        self.current_level = data["level"]
    except FileNotFoundError:
        # No save file, start a new game
        self.new_game()
    except (KeyError, json.JSONDecodeError):
        # Corrupt or incomplete data
        self.new_game()

It is wise to validate that the loaded data contains the expected keys. Using data.get("key", default) instead of data["key"] can prevent crashes if the file is partially written.

Choosing Where to Save Files

Hard-coding a filename like "savegame.json" works but is not ideal for distribution. On different operating systems, the user’s home directory or application data folder is more appropriate. Python’s pathlib module helps:

from pathlib import Path

save_path = Path.home() / ".mygame" / "save.json"
save_path.parent.mkdir(parents=True, exist_ok=True)

with open(save_path, "w") as f:
    json.dump(data, f)

This creates a hidden folder in the user’s home directory. Alternatively, you can use the platformdirs library to get the correct location for each OS, but that adds a dependency. For a simple game, a subfolder next to your script is acceptable, but note that users may not have write permissions in program files directories on Windows.

Common Pitfalls and How to Avoid Them

Several issues frequently trip up developers new to saving in Arcade:

  • Not closing the file: Using with open() ensures the file is closed even if an error occurs. Always use it.
  • Saving non-serializable objects: Arcade sprites, textures, and sound objects cannot be directly saved to JSON. Save only their attributes (position, type, etc.) and recreate the objects on load.
  • Overwriting on crash: If the game crashes during saving, the file may be corrupted. Write to a temporary file first, then rename it. This is an atomic operation on most systems.
  • Not handling missing keys: If you update your game and add new fields, old save files will lack those keys. Use data.get() with sensible defaults.
  • Storing floats with too much precision: JSON stores floats exactly as they are, but you may want to round to a few decimal places to keep the file small.

Another common misconception is that you need to save the entire arcade.Window object. That is impossible—you only save the data, not the objects.

Alternative Formats and Advanced Techniques

JSON is the simplest, but not the only option. Depending on your needs, consider:

  • Pickle: Python’s native serialization. It can save almost any object, but it is not human-readable and can be a security risk if you load files from untrusted sources.
  • SQLite: Overkill for a simple save file, but useful if you have a large amount of structured data (e.g., a game with many levels and achievements).
  • YAML: More readable than JSON but requires an external library (pyyaml).
  • Compressed JSON: For large save files, you can compress the JSON string with gzip before writing, and decompress on load.

For auto-save functionality, you can call your save function every few seconds using arcade.schedule() or after significant events (e.g., completing a level). Just be careful not to save too frequently, as disk I/O can cause stutters.

Frequently Asked Questions

Can I save and load sprites directly?

No. Sprites are complex objects with textures and physics properties. You should save their position, velocity, and any custom attributes, then recreate them on load using arcade.Sprite() and assign the saved values.

How do I save multiple save slots?

Create a directory for saves and use different filenames, e.g., slot1.json, slot2.json. On load, let the player choose a slot. You can also store metadata (like timestamp or level) in a separate index file.

What happens if the save file is corrupted?

Your load function should catch json.JSONDecodeError and handle it gracefully—either by starting a new game or by showing an error message. Never let the game crash with an unhandled exception.

Is JSON the most secure format?

JSON itself is not secure against tampering; a player can edit the file to give themselves more health. If you need to prevent cheating, you can add a checksum (e.g., SHA-256 hash) to the file and verify it on load. That is not foolproof but deters casual editing.

Can I save data to a server?

Yes, but that requires networking code. You can send the JSON string to a server via HTTP POST and retrieve it later. This is outside the scope of the Arcade library itself, but the JSON format works well for such transfers.

How do I save high scores?

High scores are just a list of numbers. Save them in a JSON list, sort it, and keep only the top N entries. Load it at startup and display it in your game over screen.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.