Python 25 · Save Pip’s progress in JSON

Python lesson 25 of 50 · Intermediate · About 26 minutes

Give Pip a save command that writes the current mission into an easy-to-read local JSON file.

Pip presses a control in front of three mint-green mission screens.

Mission Use json.dumps and pathlib to record room, energy, parts and the rescue flag in one named file.

Get ready

Read this as the next checkpoint in Pip’s mission. You can also start with the complete program below.

Save the complete checkpoint below as moonbase_25.py in a project folder and run python moonbase_25.py from that folder. Use python3 on systems where that is the Python 3 command. Use Python 3.10 or newer.

Player says save. Saving happens at an explicit request.. → Encoder. Convert the complete state to JSON text.. → Local file. Write one readable progress record..
Player says save → Encoder → Local file

Understand the Python in this lesson

Read the explanations, then follow the worked example before changing the code.

Bring in Python’s file tools

import json makes Python’s built-in JSON tools available under the name json. from pathlib import Path brings in one tool directly, the Path class. This lets you write Path(...) without putting pathlib. before it.

Give the progress file one name

SAVE_FILE = Path("moonbase-save.json") builds an object representing a local filename. That line does not create the file. Because the name is relative, the file goes in the working folder from which you ran the program. Keeping the name in one constant gives the save and future load code a shared location.

Turn the live state into text

json.dumps(state, indent=2) returns JSON text. The game's dictionary becomes a JSON object, its list of parts becomes an array, and the Python value False becomes the lowercase JSON value false. The named argument indent=2 formats the text with two-space indents. + "\n" adds a newline at the end.

Write the text and return a message

SAVE_FILE.write_text(..., encoding="utf-8") writes that string as a text file. encoding tells Python how to turn text characters into bytes. write_text replaces any earlier contents at this path. After the write, the function returns a short message that the radio can print.

Give save its own route through the loop

parse_command recognises save as a one-word command. The loop checks for it, calls save_game(state) and prints the returned message. continue jumps to the next loop turn. That keeps save from also falling into apply, which handles the ordinary game actions.

How the pieces fit The file code has a small chain of jobs. json.dumps makes text. write_text stores it. return hands a message to the radio. The next lesson will follow the reverse path from saved text to checked game data.

Follow one run, step by step
  1. Start a new run, go east and type take.
    Pip is in Workshop, energy is 7 and the parts list contains Coil. Why The move spends one energy and the Workshop contains the Coil.
  2. Enter save.
    Progress saved to moonbase-save.json. Why The loop hands the live dictionary to save_game and prints its return value.
  3. Open the file in a text editor.
    The file shows Workshop, energy 7, ["Coil"] and rescued set to false. Why The JSON text holds the data from the moment you saved.

Predict before you run Does moving west after save immediately change the file to Habitat?

Reveal the explanation

The move changes the live dictionary. Enter save again to write the new values to the file.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills JSON, pathlib, encoding, local files.

1. Choose a local folder for the checkpoint

For this lesson, use Python 3 in a folder you can write to. Save the checkpoint as moonbase.py inside it and run python moonbase.py, or use python3 if that is your working command. The save file will appear in your current working folder. The game writes only a single named progress file.

SAVE_FILE = Path("moonbase-save.json")

2. Convert live values into stored text

Use json.dumps to turn the state dictionary into JSON, then write it through the Path object. The indentation makes it easier to recognise the fields in an editor. JSON keeps strings, numbers, booleans and lists distinct, so a collected part list stays different from a sentence about parts.

def save_game(state):
    SAVE_FILE.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
    return "Progress saved to moonbase-save.json."

3. Make saving an explicit command

Add save to the accepted verbs and deal with it in the radio loop before ordinary game actions. At Habitat, move east and collect the Coil. Save and open the file in a text editor. Compare the room, energy and parts with look, then save again and watch the same file update. A new save replaces the previous progress record.

if verb == "save":
            print(save_game(state))
            continue
        print(apply(state, verb, argument))

4. Check what was actually written

A JSON file is text, so you can open the file and compare it with the game’s look report. Find the brackets for the parts list and the lowercase JSON boolean. Saving after a move should update that same file. Type quit when you have finished to close the radio.

Complete Python checkpoint · moonbase_25.py
import json
from pathlib import Path


WORLD = {
    "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None},
    "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"},
    "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"},
    "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None},
}
REQUIRED = {"Coil", "Cell"}
SAVE_FILE = Path("moonbase-save.json")


def new_mission():
    return {"room": "Habitat", "energy": 8, "parts": [], "rescued": False}


def can_repair(room, parts):
    return room == "Beacon" and REQUIRED.issubset(parts)


def describe(state):
    room, energy, cargo, _ = mission_snapshot(state)
    exits = ", ".join(WORLD[room]["exits"])
    parts = ", ".join(cargo) or "none"
    return f"{room} | energy {energy} | parts {parts} | exits {exits}"


def collect(state):
    item = WORLD[state["room"]]["part"]
    if item is None:
        return "There is no repair part here."
    if item in state["parts"]:
        return f"You already have the {item}."
    state["parts"].append(item)
    return f"Collected the {item}."


def repair(state):
    if can_repair(state["room"], state["parts"]):
        state["rescued"] = True
        return "Beacon restored! Pip has sent the rescue signal."
    return "Bring the Coil and the Cell to the Beacon."


def move(state, direction):
    destination = WORLD[state["room"]]["exits"].get(direction)
    if destination is None:
        return "That route is blocked."
    if state["energy"] == 0:
        return "Pip is out of energy."
    state["room"] = destination
    state["energy"] -= 1
    return f"Moved to {destination}."


def parse_command(text):
    words = text.lower().split()
    if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
        return "go", words[0]
    if len(words) == 2 and words[0] == "go":
        return "go", words[1]
    if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save"}:
        return words[0], ""
    return "", ""


def save_game(state):
    SAVE_FILE.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
    return "Progress saved to moonbase-save.json."


def mission_snapshot(state):
    return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]


def apply(state, verb, argument):
    if verb == "look":
        return describe(state)
    if verb == "go":
        return move(state, argument)
    if verb == "take":
        return collect(state)
    if verb == "repair":
        return repair(state)
    return "Unknown command."


def run():
    state = new_mission()
    print("Moonbase Rescue | Pip on duty")
    print(describe(state))
    print("Try look, go, take, repair or quit.")
    while not state["rescued"]:
        try:
            raw = input("Pip> ")
        except EOFError:
            print("Radio closed.")
            break
        verb, argument = parse_command(raw)
        if verb == "quit":
            print("Pip is on standby.")
            break
        if verb == "save":
            print(save_game(state))
            continue
        print(apply(state, verb, argument))


if __name__ == "__main__":
    run()

Read the complete checkpoint line by line

Use this guide beside the checkpoint. Blank lines separate ideas. Indented lines belong to the instruction above them. Lines with brackets still open can carry on below.

Lines 1–26
Line 1 import json
Bring in json. Its module name gives you access to the tools it contains.
Line 2 from pathlib import Path
Bring Path into this file from pathlib. These names can now be used directly.
Lines 5–10 WORLD = { "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None}, "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"}, "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"}, "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 11 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 12 SAVE_FILE = Path("moonbase-save.json")
Work out the value on the right, then store it in SAVE_FILE. Represent a file location so the program can work with it.
Line 15 def new_mission():
Define new_mission, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 16 return {"room": "Habitat", "energy": 8, "parts": [], "rescued": False}
Leave this function now and hand the result back to the line that called it. Each colon pairs a key with its value.
Line 19 def can_repair(room, parts):
Define can_repair, a reusable piece of the program. Its input names are room, parts. The indented body runs when something calls it.
Line 20 return room == "Beacon" and REQUIRED.issubset(parts)
Leave this function now and hand the result back to the line that called it. With and, every check must be true. Check whether every item in this set appears in the other collection.
Line 23 def describe(state):
Define describe, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 24 room, energy, cargo, _ = mission_snapshot(state)
Give each returned value to the matching name, from left to right. Run mission_snapshot with the supplied inputs and come back here when it returns.
Line 25 exits = ", ".join(WORLD[room]["exits"])
Work out the value on the right, then store it in exits. Put strings together with the text before .join separating them. The brackets look up a dictionary key or a position that starts at zero.
Line 26 parts = ", ".join(cargo) or "none"
Work out the value on the right, then store it in parts. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Lines 27–43
Line 27 return f"{room} | energy {energy} | parts {parts} | exits {exits}"
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 30 def collect(state):
Define collect, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 31 item = WORLD[state["room"]]["part"]
Work out the value on the right, then store it in item. The brackets look up a dictionary key or a position that starts at zero.
Line 32 if item is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 33 return "There is no repair part here."
Leave this function now and hand the result back to the line that called it.
Line 34 if item in state["parts"]:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection. The brackets look up a dictionary key or a position that starts at zero.
Line 35 return f"You already have the {item}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 36 state["parts"].append(item)
Add the value to the end without replacing the earlier entries.
Line 37 return f"Collected the {item}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 40 def repair(state):
Define repair, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 41 if can_repair(state["room"], state["parts"]):
Run the indented block only if this check is true. Run can_repair with the supplied inputs and come back here when it returns. The brackets look up a dictionary key or a position that starts at zero.
Line 42 state["rescued"] = True
Work out the value on the right, then store it in state["rescued"].
Line 43 return "Beacon restored! Pip has sent the rescue signal."
Leave this function now and hand the result back to the line that called it.
Lines 44–60
Line 44 return "Bring the Coil and the Cell to the Beacon."
Leave this function now and hand the result back to the line that called it.
Line 47 def move(state, direction):
Define move, a reusable piece of the program. Its input names are state, direction. The indented body runs when something calls it.
Line 48 destination = WORLD[state["room"]]["exits"].get(direction)
Work out the value on the right, then store it in destination. Look up a key. Use the given fallback, or None, if the key is missing.
Line 49 if destination is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 50 return "That route is blocked."
Leave this function now and hand the result back to the line that called it.
Line 51 if state["energy"] == 0:
Run the indented block only if this check is true. The brackets look up a dictionary key or a position that starts at zero.
Line 52 return "Pip is out of energy."
Leave this function now and hand the result back to the line that called it.
Line 53 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 54 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Line 55 return f"Moved to {destination}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 58 def parse_command(text):
Define parse_command, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 59 words = text.lower().split()
Work out the value on the right, then store it in words. Return a lowercase copy so capital letters do not change a command. Separate the string into a list of pieces.
Line 60 if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Lines 61–79
Line 61 return "go", words[0]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 62 if len(words) == 2 and words[0] == "go":
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. The brackets look up a dictionary key or a position that starts at zero.
Line 63 return "go", words[1]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 64 if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Line 65 return words[0], ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 66 return "", ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 69 def save_game(state):
Define save_game, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 70 SAVE_FILE.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
Write text to the file using the chosen encoding. Turn Python data into JSON text. This step does not write a file.
Line 71 return "Progress saved to moonbase-save.json."
Leave this function now and hand the result back to the line that called it.
Line 74 def mission_snapshot(state):
Define mission_snapshot, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 75 return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero. Collect ordered items in a tuple, whose entries cannot be reassigned.
Line 78 def apply(state, verb, argument):
Define apply, a reusable piece of the program. Its input names are state, verb, argument. The indented body runs when something calls it.
Line 79 if verb == "look":
Run the indented block only if this check is true.
Lines 80–94
Line 80 return describe(state)
Leave this function now and hand the result back to the line that called it. Run describe with the supplied inputs and come back here when it returns.
Line 81 if verb == "go":
Run the indented block only if this check is true.
Line 82 return move(state, argument)
Leave this function now and hand the result back to the line that called it. Run move with the supplied inputs and come back here when it returns.
Line 83 if verb == "take":
Run the indented block only if this check is true.
Line 84 return collect(state)
Leave this function now and hand the result back to the line that called it. Run collect with the supplied inputs and come back here when it returns.
Line 85 if verb == "repair":
Run the indented block only if this check is true.
Line 86 return repair(state)
Leave this function now and hand the result back to the line that called it. Run repair with the supplied inputs and come back here when it returns.
Line 87 return "Unknown command."
Leave this function now and hand the result back to the line that called it.
Line 90 def run():
Define run, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 91 state = new_mission()
Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
Line 92 print("Moonbase Rescue | Pip on duty")
Show the message or value in the output.
Line 93 print(describe(state))
Show the message or value in the output. Run describe with the supplied inputs and come back here when it returns.
Line 94 print("Try look, go, take, repair or quit.")
Show the message or value in the output.
Lines 95–107
Line 95 while not state["rescued"]:
Check not state["rescued"] before each pass. Repeat the indented work while it is true.
Line 96 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 97 raw = input("Pip> ")
Work out the value on the right, then store it in raw. Show the prompt and wait for the player to type a line. The answer starts as text.
Line 98 except EOFError:
Run this part only when the try block raises EOFError.
Line 99 print("Radio closed.")
Show the message or value in the output.
Line 100 break
Leave the nearest loop immediately and continue after it.
Line 101 verb, argument = parse_command(raw)
Give each returned value to the matching name, from left to right. Run parse_command with the supplied inputs and come back here when it returns.
Line 102 if verb == "quit":
Run the indented block only if this check is true.
Line 103 print("Pip is on standby.")
Show the message or value in the output.
Line 104 break
Leave the nearest loop immediately and continue after it.
Line 105 if verb == "save":
Run the indented block only if this check is true.
Line 106 print(save_game(state))
Show the message or value in the output. Run save_game with the supplied inputs and come back here when it returns.
Line 107 continue
Skip the rest of this pass and start the next loop check.
Lines 108–112
Line 108 print(apply(state, verb, argument))
Show the message or value in the output. Run apply with the supplied inputs and come back here when it returns.
Line 111 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 112 run()
Run run with the supplied inputs and come back here when it returns.

Test the mission

  • Run in a writable folder. Type east, take, save, quit.
  • Open moonbase-save.json and verify the Coil appears inside the parts list.
  • Restart the program. This version starts fresh and writes saves; the next checkpoint will restore them.

If something goes wrong

There is no save file next to the program.
Check the terminal’s current working directory and confirm the game reported Progress saved.

Mission extension

Save once in Habitat and once in Workshop. Compare the energy and room values.