Python lesson 37 of 50 · Advanced · About 40 minutes
Turn a sequence of instructions into a repeatable rescue. Save a command list as JSON text and feed it back into the same rules.

Mission Use existing state transitions to produce a deterministic replay from recorded commands.
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_37.py in a project folder and run python moonbase_37.py from that folder. Use python3 on systems where that is the Python 3 command. Use Python 3.10 or newer.

Understand the Python in this lesson
Read the explanations, then follow the worked example before changing the code.
Save a sequence, then start fresh
DEMO is a tuple, with commas separating the seven fixed commands. replay(commands) accepts an ordered collection of commands. Inside, state = State() gives each replay the same starting room, pack, battery and turn count.
Apply the same rule one command at a time
for command in commands: reads the entries in their original order. state, _ = step(state, command) unpacks the new state and message. The underscore is a regular variable name used by convention for a value you will not read. The next pass uses the updated state.
Turn the sequence into copyable text
json.dumps(DEMO) makes a JSON string representing the commands as an array. json.loads(copied_log) reads that text into a Python list. Replay works with the list because it only needs to loop over the commands. The live log command uses dumps on the history list to show an equivalent format.
Choose demo mode from the terminal
sys.argv[0] is the script name. sys.argv[1] is the first argument after it, when one exists. Checking len(sys.argv) first avoids looking for a missing entry. When the mode is --demo, the file runs the demo function instead of opening the interactive prompt.
How the pieces fit The command history gives us the ingredients for a replay. Starting fresh and applying step in the same order lets you reproduce the final state for a test.
-
Run the file with --demo.
The JSON array of seven commands is printed. Why The main block chooses run_demo and converts DEMO to text. -
Replay reads go east and take first.
Pip is in Workshop with Coil, energy 6 and turns 2. Why Both commands succeed starting from the fresh mission. -
Replay applies the remaining five commands.
Replay: room=Beacon, turns=7, rescued=True. Why The Cell is collected before the two parts are used to repair the Beacon. -
Launch normally and type go east, take and log.
["go east", "take"] Why The interactive history contains those two accepted actions as JSON text.
Predict before you run Does json.dumps(history) create a saved file in this lesson?
Reveal the explanation
It produces a string. The program prints that string. The built-in demo reads a string back with loads, so this version runs without opening a file.
Build the checkpoint
Python skills deterministic replay, JSON, command sequence, command-line arguments.
1. Read a record from the start
A useful replay uses the same rules as the live game. The replay function starts with a new State and applies each command in the supplied order. It keeps the returned state and ignores the human-readable message with _. The next command receives the updated state, just like live play. A fresh state every time avoids carrying extra equipment into the replay. Trace the demo from Habitat to Workshop: the first command moves Pip and the next one packs the Coil. The same steps should produce the same state on every run.
for command in commands:
state, _ = step(state, command)
2. Make a log you can copy
A Python list looks like a set of instructions, but its representation is not a universal save format. json.dumps turns the commands into JSON text and json.loads reads that particular text back into a list. This lesson replays the built-in sequence, which is controlled by the program. It does not ask for an external file. Try the interactive log command after a few moves to see the same format. A copyable record allows two learners to compare the exact sequence that led to a surprising outcome.
copied_log = json.dumps(DEMO)
print(copied_log)
state = replay(json.loads(copied_log))
3. Compare the replay end state
Use a terminal and run the checkpoint filename with --demo after it, such as python lesson-37.py --demo if that is what you saved the file as. Without the flag, the program opens the usual game. The demo prints the record and then the final room, number of turns and rescue status. Run the listed sequence yourself and compare it with status afterward. A replay can reveal a bug without requiring you to act as quickly as the player did. Keep random or time-dependent effects out of this first replay so that the comparison is dependable.
if mode == "--demo":
run_demo()
Complete Python checkpoint · moonbase_37.py
from dataclasses import dataclass, replace
from collections import deque
import json
import sys
WORLD = {
"Habitat": {"east": "Workshop", "south": "Greenhouse"},
"Workshop": {"west": "Habitat", "south": "Beacon"},
"Greenhouse": {"north": "Habitat", "east": "Beacon"},
"Beacon": {"north": "Workshop", "west": "Greenhouse"},
}
PART_AT = {"Workshop": "Coil", "Greenhouse": "Cell"}
REQUIRED = {"Coil", "Cell"}
MAX_ENERGY = 8
@dataclass(frozen=True)
class State:
room: str = "Habitat"
parts: tuple = ()
rescued: bool = False
energy: int = MAX_ENERGY
turns: int = 0
def spend(state, **changes):
return replace(state, energy=state.energy - 1,
turns=state.turns + 1, **changes)
def step(state, command):
if state.rescued:
return state, "Beacon already online."
if command == "charge":
if state.energy == MAX_ENERGY:
return state, "The battery is already full."
return replace(state, energy=MAX_ENERGY, turns=state.turns + 1), "Charged to 8."
if state.energy == 0:
return state, "Battery empty. Use charge to continue."
if command.startswith("go "):
direction = command[3:]
target = WORLD[state.room].get(direction)
if target is None:
return state, "No exit that way."
return spend(state, room=target), f"Arrived at {target}."
if command == "take":
part = PART_AT.get(state.room)
if part is None:
return state, "There is no part here."
if part in state.parts:
return state, "You already have that part."
return spend(state, parts=(*state.parts, part)), f"Packed {part}."
if command == "repair":
if state.room != "Beacon":
return state, "Repair at the Beacon."
if not REQUIRED.issubset(state.parts):
return state, "Find both the Coil and the Cell."
return spend(state, rescued=True), "Beacon online!"
return state, "Unknown command."
def render_map(state):
rooms = []
for room, exits in WORLD.items():
current = " [Pip is here]" if room == state.room else ""
links = ", ".join(f"{direction} to {end}" for direction, end in exits.items())
rooms.append(f"{room}{current}: {links}.")
return "\n".join(rooms)
def route(start, target):
queue = deque([(start, ())])
seen = {start}
while queue:
room, moves = queue.popleft()
if room == target:
return moves
for direction, neighbour in WORLD[room].items():
if neighbour not in seen:
seen.add(neighbour)
queue.append((neighbour, (*moves, direction)))
return None
DEMO = ('go east', 'take', 'go west', 'go south', 'take', 'go east', 'repair')
def replay(commands):
state = State()
for command in commands:
state, _ = step(state, command)
return state
def run_demo():
copied_log = json.dumps(DEMO)
print(copied_log)
state = replay(json.loads(copied_log))
print(f"Replay: room={state.room}, turns={state.turns}, rescued={state.rescued}.")
def describe(state):
pack = ", ".join(state.parts) or "empty"
restored = "online" if state.rescued else "offline"
message = f"{state.room} | pack: {pack} | Beacon: {restored}"
return f"{message} | energy: {state.energy} | turns: {state.turns}"
def normalise(text):
return " ".join(text.lower().split())
def play():
state = State()
history = []
print('Moonbase Rescue. Type go east, take, repair, status or quit.')
while True:
try:
command = normalise(input("> "))
except EOFError:
break
if command == "quit":
break
if command == "status":
print(describe(state))
continue
if command == "map":
print(render_map(state))
continue
if command == "history":
print("History:", " > ".join(history) or "no moves yet")
continue
if command.startswith("hint "):
target = command[5:].title()
if target not in WORLD:
print("Unknown destination.")
else:
moves = route(state.room, target)
print("Route:", " then ".join(moves) if moves else "already there" if moves == () else "unreachable")
continue
if command == "log":
print(json.dumps(history))
continue
next_state, message = step(state, command)
if next_state != state:
history.append(command)
state = next_state
print(message)
print("Mission ended.")
if __name__ == "__main__":
mode = sys.argv[1] if len(sys.argv) > 1 else ""
if mode == "--demo":
run_demo()
else:
play()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–23
-
Line 1
from dataclasses import dataclass, replace - Bring dataclass, replace into this file from dataclasses. These names can now be used directly.
-
Line 2
from collections import deque - Bring deque into this file from collections. These names can now be used directly.
-
Line 3
import json - Bring in json. Its module name gives you access to the tools it contains.
-
Line 4
import sys - Bring in sys. Its module name gives you access to the tools it contains.
-
Lines 6–11
WORLD = { "Habitat": {"east": "Workshop", "south": "Greenhouse"}, "Workshop": {"west": "Habitat", "south": "Beacon"}, "Greenhouse": {"north": "Habitat", "east": "Beacon"}, "Beacon": {"north": "Workshop", "west": "Greenhouse"}, } - Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
-
Line 12
PART_AT = {"Workshop": "Coil", "Greenhouse": "Cell"} - Work out the value on the right, then store it in PART_AT. Each colon pairs a key with its value.
-
Line 13
REQUIRED = {"Coil", "Cell"} - Work out the value on the right, then store it in REQUIRED.
-
Line 16
MAX_ENERGY = 8 - Work out the value on the right, then store it in MAX_ENERGY.
-
Line 19
@dataclass(frozen=True) - Ask Python to create the usual data-handling methods from the listed fields.
-
Line 20
class State: - Define State, a class that groups related data or behaviour.
-
Line 21
room: str = "Habitat" - Describe the expected type of room as str and provide its starting value.
-
Line 22
parts: tuple = () - Describe the expected type of parts as tuple and provide its starting value. Commas group these values into an ordered tuple.
-
Line 23
rescued: bool = False - Describe the expected type of rescued as bool and provide its starting value.
Lines 24–39
-
Line 24
energy: int = MAX_ENERGY - Describe the expected type of energy as int and provide its starting value.
-
Line 25
turns: int = 0 - Describe the expected type of turns as int and provide its starting value.
-
Line 27
def spend(state, **changes): - Define spend, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
-
Lines 28–29
return replace(state, energy=state.energy - 1, turns=state.turns + 1, **changes) - Leave this function now and hand the result back to the line that called it. Make a new state with the named changes. The old state stays available.
-
Line 31
def step(state, command): - Define step, a reusable piece of the program. Its input names are state, command. The indented body runs when something calls it.
-
Line 32
if state.rescued: - Run the indented block only if this check is true.
-
Line 33
return state, "Beacon already online." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 34
if command == "charge": - Run the indented block only if this check is true.
-
Line 35
if state.energy == MAX_ENERGY: - Run the indented block only if this check is true.
-
Line 36
return state, "The battery is already full." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 37
return replace(state, energy=MAX_ENERGY, turns=state.turns + 1), "Charged to 8." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Make a new state with the named changes. The old state stays available.
-
Line 38
if state.energy == 0: - Run the indented block only if this check is true.
-
Line 39
return state, "Battery empty. Use charge to continue." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Lines 40–52
-
Line 40
if command.startswith("go "): - Run the indented block only if this check is true. Check whether this text begins with the given prefix.
-
Line 41
direction = command[3:] - Work out the value on the right, then store it in direction. The slice copies a portion, stopping before the end index if one is given.
-
Line 42
target = WORLD[state.room].get(direction) - Work out the value on the right, then store it in target. Look up a key. Use the given fallback, or None, if the key is missing.
-
Line 43
if target 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 44
return state, "No exit that way." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 45
return spend(state, room=target), f"Arrived at {target}." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run spend with the supplied inputs and come back here when it returns. Python fills the braces with values before it uses the text.
-
Line 46
if command == "take": - Run the indented block only if this check is true.
-
Line 47
part = PART_AT.get(state.room) - Work out the value on the right, then store it in part. Look up a key. Use the given fallback, or None, if the key is missing.
-
Line 48
if part 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 49
return state, "There is no part here." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 50
if part 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.
-
Line 51
return state, "You already have that part." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 52
return spend(state, parts=(*state.parts, part)), f"Packed {part}." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run spend with the supplied inputs and come back here when it returns. Python fills the braces with values before it uses the text.
Lines 53–66
-
Line 53
if command == "repair": - Run the indented block only if this check is true.
-
Line 54
if state.room != "Beacon": - Run the indented block only if this check is true.
-
Line 55
return state, "Repair at the Beacon." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 56
if not REQUIRED.issubset(state.parts): - Run the indented block only if this check is true. The word not reverses which result counts as true. Check whether every item in this set appears in the other collection.
-
Line 57
return state, "Find both the Coil and the Cell." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 58
return spend(state, rescued=True), "Beacon online!" - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run spend with the supplied inputs and come back here when it returns.
-
Line 59
return state, "Unknown command." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 61
def render_map(state): - Define render_map, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
-
Line 62
rooms = [] - Work out the value on the right, then store it in rooms.
-
Line 63
for room, exits in WORLD.items(): - Take one item at a time and give it to room, exits, then run the indented block. Make the dictionary's key and value pairs available to loop over.
-
Line 64
current = " [Pip is here]" if room == state.room else "" - Work out the value on the right, then store it in current. Choose the first value if the condition is true, otherwise choose the value after else.
-
Line 65
links = ", ".join(f"{direction} to {end}" for direction, end in exits.items()) - Work out the value on the right, then store it in links. Put strings together with the text before .join separating them. The expression supplies matching values one at a time to the operation using it. Python fills the braces with values before it uses the text.
-
Line 66
rooms.append(f"{room}{current}: {links}.") - Add the value to the end without replacing the earlier entries. Python fills the braces with values before it uses the text.
Lines 67–80
-
Line 67
return "\n".join(rooms) - Leave this function now and hand the result back to the line that called it. Put strings together with the text before .join separating them.
-
Line 69
def route(start, target): - Define route, a reusable piece of the program. Its input names are start, target. The indented body runs when something calls it.
-
Line 70
queue = deque([(start, ())]) - Work out the value on the right, then store it in queue. Create a queue that can efficiently take items from either end. Commas group these values into an ordered tuple.
-
Line 71
seen = {start} - Work out the value on the right, then store it in seen.
-
Line 72
while queue: - Check queue before each pass. Repeat the indented work while it is true.
-
Line 73
room, moves = queue.popleft() - Give each returned value to the matching name, from left to right. Remove and return the oldest entry at the front of the queue.
-
Line 74
if room == target: - Run the indented block only if this check is true.
-
Line 75
return moves - Leave this function now and hand the result back to the line that called it.
-
Line 76
for direction, neighbour in WORLD[room].items(): - Take one item at a time and give it to direction, neighbour, then run the indented block. Make the dictionary's key and value pairs available to loop over.
-
Line 77
if neighbour not in seen: - Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
-
Line 78
seen.add(neighbour) - Add the value to the set. A set keeps at most one copy.
-
Line 79
queue.append((neighbour, (*moves, direction))) - Add the value to the end without replacing the earlier entries. Commas group these values into an ordered tuple.
-
Line 80
return None - Leave this function now and hand the result back to the line that called it.
Lines 82–99
-
Line 82
DEMO = ('go east', 'take', 'go west', 'go south', 'take', 'go east', 'repair') - Work out the value on the right, then store it in DEMO. Commas group these values into an ordered tuple.
-
Line 85
def replay(commands): - Define replay, a reusable piece of the program. Its input names are commands. The indented body runs when something calls it.
-
Line 86
state = State() - Work out the value on the right, then store it in state. Create a mission state using the supplied field values and any defaults.
-
Line 87
for command in commands: - Take one item at a time and give it to command, then run the indented block.
-
Line 88
state, _ = step(state, command) - Give each returned value to the matching name, from left to right. Run step with the supplied inputs and come back here when it returns.
-
Line 89
return state - Leave this function now and hand the result back to the line that called it.
-
Line 92
def run_demo(): - Define run_demo, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
-
Line 93
copied_log = json.dumps(DEMO) - Work out the value on the right, then store it in copied_log. Turn Python data into JSON text. This step does not write a file.
-
Line 94
print(copied_log) - Show the message or value in the output.
-
Line 95
state = replay(json.loads(copied_log)) - Work out the value on the right, then store it in state. Run replay with the supplied inputs and come back here when it returns. Read JSON text or bytes and turn it back into Python data.
-
Line 96
print(f"Replay: room={state.room}, turns={state.turns}, rescued={state.rescued}.") - Show the message or value in the output. Python fills the braces with values before it uses the text.
-
Line 98
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 99
pack = ", ".join(state.parts) or "empty" - Work out the value on the right, then store it in pack. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Lines 100–114
-
Line 100
restored = "online" if state.rescued else "offline" - Work out the value on the right, then store it in restored. Choose the first value if the condition is true, otherwise choose the value after else.
-
Line 101
message = f"{state.room} | pack: {pack} | Beacon: {restored}" - Work out the value on the right, then store it in message. Python fills the braces with values before it uses the text.
-
Line 102
return f"{message} | energy: {state.energy} | turns: {state.turns}" - 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 104
def normalise(text): - Define normalise, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
-
Line 105
return " ".join(text.lower().split()) - Leave this function now and hand the result back to the line that called it. Put strings together with the text before .join separating them. Separate the string into a list of pieces. Return a lowercase copy so capital letters do not change a command.
-
Line 107
def play(): - Define play, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
-
Line 108
state = State() - Work out the value on the right, then store it in state. Create a mission state using the supplied field values and any defaults.
-
Line 109
history = [] - Work out the value on the right, then store it in history.
-
Line 110
print('Moonbase Rescue. Type go east, take, repair, status or quit.') - Show the message or value in the output.
-
Line 111
while True: - Repeat the indented work until a break, return or error ends this path.
-
Line 112
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 113
command = normalise(input("> ")) - Work out the value on the right, then store it in command. Run normalise with the supplied inputs and come back here when it returns. Show the prompt and wait for the player to type a line. The answer starts as text.
-
Line 114
except EOFError: - Run this part only when the try block raises EOFError.
Lines 115–127
-
Line 115
break - Leave the nearest loop immediately and continue after it.
-
Line 116
if command == "quit": - Run the indented block only if this check is true.
-
Line 117
break - Leave the nearest loop immediately and continue after it.
-
Line 118
if command == "status": - Run the indented block only if this check is true.
-
Line 119
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 120
continue - Skip the rest of this pass and start the next loop check.
-
Line 121
if command == "map": - Run the indented block only if this check is true.
-
Line 122
print(render_map(state)) - Show the message or value in the output. Run render_map with the supplied inputs and come back here when it returns.
-
Line 123
continue - Skip the rest of this pass and start the next loop check.
-
Line 124
if command == "history": - Run the indented block only if this check is true.
-
Line 125
print("History:", " > ".join(history) or "no moves yet") - Show the message or value in the output. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
-
Line 126
continue - Skip the rest of this pass and start the next loop check.
-
Line 127
if command.startswith("hint "): - Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Lines 128–140
-
Line 128
target = command[5:].title() - Work out the value on the right, then store it in target. Return words with title-style capital letters for display.
-
Line 129
if target not in WORLD: - Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
-
Line 130
print("Unknown destination.") - Show the message or value in the output.
-
Line 131
else: - Take this branch if the earlier checks for this decision were false.
-
Line 132
moves = route(state.room, target) - Work out the value on the right, then store it in moves. Run route with the supplied inputs and come back here when it returns.
-
Line 133
print("Route:", " then ".join(moves) if moves else "already there" if moves == () else "unreachable") - Show the message or value in the output. Choose the first value if the condition is true, otherwise choose the value after else. Put strings together with the text before .join separating them.
-
Line 134
continue - Skip the rest of this pass and start the next loop check.
-
Line 135
if command == "log": - Run the indented block only if this check is true.
-
Line 136
print(json.dumps(history)) - Show the message or value in the output. Turn Python data into JSON text. This step does not write a file.
-
Line 137
continue - Skip the rest of this pass and start the next loop check.
-
Line 138
next_state, message = step(state, command) - Give each returned value to the matching name, from left to right. Run step with the supplied inputs and come back here when it returns.
-
Line 139
if next_state != state: - Run the indented block only if this check is true.
-
Line 140
history.append(command) - Add the value to the end without replacing the earlier entries.
Lines 141–150
-
Line 141
state = next_state - Work out the value on the right, then store it in state.
-
Line 142
print(message) - Show the message or value in the output.
-
Line 143
print("Mission ended.") - Show the message or value in the output.
-
Line 145
if __name__ == "__main__": - Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
-
Line 146
mode = sys.argv[1] if len(sys.argv) > 1 else "" - Work out the value on the right, then store it in mode. Choose the first value if the condition is true, otherwise choose the value after else. Count the characters or items. The brackets look up a dictionary key or a position that starts at zero.
-
Line 147
if mode == "--demo": - Run the indented block only if this check is true.
-
Line 148
run_demo() - Run run_demo with the supplied inputs and come back here when it returns.
-
Line 149
else: - Take this branch if the earlier checks for this decision were false.
-
Line 150
play() - Run play with the supplied inputs and come back here when it returns.
Test the mission
- Run the demo twice and compare the two lines of output.
- Play the same seven commands manually and compare the final room and turn count.
- In a separate copy, remove the Coil collection from DEMO and check that its replay cannot complete the repair.
If something goes wrong
- The demo behaves like the live prompt.
- Pass --demo after the filename in a terminal.
- The replay starts with your current inventory.
- Construct a new State at the beginning of replay.
Mission extension
Make a second fixed replay that uses charge halfway through. Predict both the final energy and the number of turns.