Python lesson 31 of 50 · Advanced · About 30 minutes
Build a mission log that records Pip’s room, equipment and beacon status in one place. Use a fresh dataclass value whenever Pip changes the world.

Mission Model Moonbase Rescue with a frozen dataclass and observe how a game command produces a new state.
Get ready
This chapter starts with a fresh checkpoint of Pip’s mission. Compare it with your previous version to see how the game is organised for the next set of skills.
Save the complete checkpoint below as moonbase_31.py in a project folder and run python moonbase_31.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.
Describe the mission record
class State: names a kind of object for mission records. The indented lines belong to the class. room: str = "Habitat" gives the field a name, a type hint for text and a starting value. bool is the type for True and False. Type hints tell readers what to expect.
Let Python build the record
@dataclass(frozen=True) adds useful behaviour to the class, such as accepting field values in State() and comparing field values. Frozen means the fields cannot be reassigned on an existing record. replace(state, room=target) constructs another record and copies the fields you leave out.
Pack a new tuple
() starts the pack empty. (*state.parts, part) unpacks the old entries with * and places the new part after them. The result is a new tuple, an ordered collection whose entries stay fixed. The comma matters even for a tuple containing just one item.
Hand back both answers
step returns a state and a message. The comma pairs them. state, message = step(state, command) unpacks the result so the loop can remember the new state and print the message. WORLD supplies the exits, and REQUIRED.issubset(state.parts) checks that the pack contains both required parts.
How the pieces fit The map describes where Pip could go. State describes where Pip is now. An action reads both, and the loop carries the result into the next action.
-
Call State().
Room Habitat, parts (), rescued False. Why No arguments were given, so the dataclass uses its defaults. -
Enter go east.
Arrived at Workshop. Why The Workshop is Habitat’s east exit, so replace creates a State with that room. -
Enter take.
Packed Coil. The pack is now ('Coil',). Why Workshop has the Coil and the tuple expression adds it once. -
Enter repair in Workshop.
Repair at the Beacon. Why The room guard returns the same state before the pack check.
Predict before you run If you call replace(old_state, room="Workshop") and ignore what it returns, where is Pip in old_state?
Reveal the explanation
Still in Habitat if that was its room before the call. Keep the new value by assigning it to a variable. The loop captures the value returned by step every turn.
Build the checkpoint
Python skills dataclass, immutable state, tuple, replace.
1. Write down what can change
Mission Control needs to know where Pip is, which parts are packed, and whether the beacon has been restored. These three facts belong together. The State dataclass declares their names and starting values. The moon base layout belongs in WORLD because it tells you what rooms exist, regardless of what Pip has done. In the same way, a station map stays on the wall while a rover moves between stations. Read that distinction before continuing. Try constructing State() mentally. You should see Habitat, an empty tuple of parts and a beacon that is offline.
@dataclass(frozen=True)
class State:
room: str = "Habitat"
parts: tuple = ()
rescued: bool = False
2. Replace one field when Pip moves
Trace go east from Habitat. The east exit leads to Workshop. The replace function makes a new State with just that room changed. The incoming value still describes the situation before the move. When collecting a part, the expression (*state.parts, part) copies the existing tuple entries into a new tuple before adding the new part. The comma makes the result a tuple. Combining a frozen dataclass with a tuple makes it much harder to change the old mission record by accident. Find the two places where a failed action returns the original state.
return replace(state, room=target), f"Arrived at {target}."
3. Close the mission loop
The command loop updates its state variable after each move. This is how Pip remembers previous actions even though each individual state is frozen. Type status before and after collecting the Coil in Workshop. For a full rescue, return west to Habitat, go south to Greenhouse, take the Cell, then go east to Beacon and repair. The two components are needed together. If you try repairing from a different room or before collecting both pieces, the reply tells you what to do next. Keep this checkpoint as the starting point for the engine work.
state, message = step(state, command)
Complete Python checkpoint · moonbase_31.py
from dataclasses import dataclass, replace
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"}
@dataclass(frozen=True)
class State:
room: str = "Habitat"
parts: tuple = ()
rescued: bool = False
def step(state, command):
if state.rescued:
return state, "Beacon already online."
if command.startswith("go "):
direction = command[3:]
target = WORLD[state.room].get(direction)
if target is None:
return state, "No exit that way."
return replace(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 replace(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 replace(state, rescued=True), "Beacon online!"
return state, "Unknown command."
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 message
def play():
state = State()
print('Moonbase Rescue. Type go east, take, repair, status or quit.')
while True:
try:
command = input("> ").strip().lower()
except EOFError:
break
if command == "quit":
break
if command == "status":
print(describe(state))
continue
state, message = step(state, command)
print(message)
print("Mission ended.")
if __name__ == "__main__":
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–22
-
Line 1
from dataclasses import dataclass, replace - Bring dataclass, replace into this file from dataclasses. These names can now be used directly.
-
Lines 3–8
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 9
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 10
REQUIRED = {"Coil", "Cell"} - Work out the value on the right, then store it in REQUIRED.
-
Line 13
@dataclass(frozen=True) - Ask Python to create the usual data-handling methods from the listed fields.
-
Line 14
class State: - Define State, a class that groups related data or behaviour.
-
Line 15
room: str = "Habitat" - Describe the expected type of room as str and provide its starting value.
-
Line 16
parts: tuple = () - Describe the expected type of parts as tuple and provide its starting value. Commas group these values into an ordered tuple.
-
Line 17
rescued: bool = False - Describe the expected type of rescued as bool and provide its starting value.
-
Line 19
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 20
if state.rescued: - Run the indented block only if this check is true.
-
Line 21
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 22
if command.startswith("go "): - Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Lines 23–35
-
Line 23
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 24
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 25
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 26
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 27
return replace(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. Make a new state with the named changes. The old state stays available. Python fills the braces with values before it uses the text.
-
Line 28
if command == "take": - Run the indented block only if this check is true.
-
Line 29
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 30
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 31
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 32
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 33
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 34
return replace(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. Make a new state with the named changes. The old state stays available. Python fills the braces with values before it uses the text.
-
Line 35
if command == "repair": - Run the indented block only if this check is true.
Lines 36–50
-
Line 36
if state.room != "Beacon": - Run the indented block only if this check is true.
-
Line 37
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 38
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 39
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 40
return replace(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. Make a new state with the named changes. The old state stays available.
-
Line 41
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 43
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 44
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.
-
Line 45
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 46
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 47
return message - Leave this function now and hand the result back to the line that called it.
-
Line 49
def play(): - Define play, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
-
Line 50
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.
Lines 51–63
-
Line 51
print('Moonbase Rescue. Type go east, take, repair, status or quit.') - Show the message or value in the output.
-
Line 52
while True: - Repeat the indented work until a break, return or error ends this path.
-
Line 53
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 54
command = input("> ").strip().lower() - Work out the value on the right, then store it in command. Show the prompt and wait for the player to type a line. The answer starts as text. Return a copy with whitespace removed from the beginning and end. Return a lowercase copy so capital letters do not change a command.
-
Line 55
except EOFError: - Run this part only when the try block raises EOFError.
-
Line 56
break - Leave the nearest loop immediately and continue after it.
-
Line 57
if command == "quit": - Run the indented block only if this check is true.
-
Line 58
break - Leave the nearest loop immediately and continue after it.
-
Line 59
if command == "status": - Run the indented block only if this check is true.
-
Line 60
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 61
continue - Skip the rest of this pass and start the next loop check.
-
Line 62
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 63
print(message) - Show the message or value in the output.
Lines 64–67
-
Line 64
print("Mission ended.") - Show the message or value in the output.
-
Line 66
if __name__ == "__main__": - Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
-
Line 67
play() - Run play with the supplied inputs and come back here when it returns.
Test the mission
- Type status, then go east and take. Compare what status reports now.
- Try take twice in Workshop. The second attempt should report that the part is already packed.
- Complete the rescue. Try a move after restoring the beacon and read the reply.
If something goes wrong
- FrozenInstanceError appears.
- Use replace(state, room=target). Assign the returned State to the loop’s state variable.
- Pip seems to forget the move.
- Use state, message = step(state, command) each time you apply a game command.
Mission extension
Add a callsign field to State with a default of Pip, then show the callsign in describe.