Python lesson 41 of 50 · Expert projects · About 55 minutes
Build one rules function that Pip’s controls, tests and future interfaces can all use.

Mission Move Pip, collect the Coil and Cell, and repair the Beacon using an engine that returns a new state after each successful command.
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_41.py in a project folder and run python moonbase_41.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.
A class describes a state snapshot
class State: names a type of object with four labelled values. In energy: int = 7, the colon introduces a type hint and = 7 sets the default. State(energy=5) sets a different starting battery.
The decorator gives the class tools
The @ line applies dataclass to the class below. It builds the field-setting code and lets Python compare snapshots by their values. With frozen=True, the snapshot’s fields are protected from reassignment. replace makes a fresh snapshot and copies across the fields you leave out.
The rules decide what changes
step takes the state, command and part locations. startswith recognises movement. command[3:] reads from position three to the end, skipping the letters and space in go . LINKS[state.room] looks up the exits from the current room.
Collect, check and return two values
locations.items() gives part-and-room pairs. The expression passed to next supplies matching names one at a time. None is the fallback when no room matches. (part,) is a tuple holding one item, so adding it makes a new parts tuple. For repair, all checks that every required part is carried.
The controls apply the returned result
new_state, message = step(...) assigns the two returned values to two names. play tidies input, prints the message and saves a changed state and its command. The bottom __name__ check calls main() when this file runs directly.
How the pieces fit The map lists exits, State holds the facts, step applies the rules and play shows the result. The next lesson uses the same pieces with a new part layout.
-
Start the file.
Pip begins at Habitat with 7 energy and no parts. Why State supplies the default room and empty tuple. play supplies the energy. -
Type go workshop.
Pip enters Workshop. Why Workshop is a legal exit. replace creates a snapshot with the new room and 6 energy. -
Type take and then take again.
Pip takes the Coil. Then the game says there is no new repair part here. Why The first command adds the Coil. The second finds the same item already in state.parts. -
Type look.
The status shows Workshop, 6 energy and Coil. Why The display reads the current snapshot without changing or recording it.
Predict before you run If you call replace(state, energy=6), what is state.energy immediately afterwards?
Reveal the explanation
It is still the old value. replace returns a fresh snapshot. Assign that result to a name, as the game does with state = new_state.
Build the checkpoint
Python skills Frozen dataclasses, Pure rule functions, State transitions.
1. Give the rover a state card
Imagine a mission controller handing Pip a new status card after every move. The State dataclass records Pip’s room, remaining energy, collected parts and rescue outcome. A tuple keeps the collection simple and immutable. Put these values together so that passages, inventory and endings never depend on separate global variables. The default record starts in Habitat with seven energy and empty pockets.
@dataclass(frozen=True)
class State:
2. Put all rules in one function
The engine takes a state, a command and the locations of the two repair parts. Its result is a pair made up of the next state and a short message. Movement uses LINKS before spending energy. Taking an item adds it once. Repair succeeds at Beacon when both items are present. replace() copies the current record and changes only named fields. Failed commands return the original record, so testing a move costs no energy.
return replace(state, room=target, energy=state.energy - 1), f"Pip enters {target.title()}."
3. Let the controls do the talking
The play() function reads text, passes it to step() and prints the returned message. It handles look and quit without changing mission state. The engine stays free of input() and print(). That lets a second script call exactly the same rules without anyone typing. Try the listed win path, then add an invalid move before it and compare the outcome.
new_state, message = step(state, command, locations)
Complete Python checkpoint · moonbase_41.py
"""Moonbase Rescue. Guide Pip and repair the radio beacon."""
import argparse
from dataclasses import dataclass, replace
LINKS = {
"habitat": ("workshop", "greenhouse"),
"workshop": ("habitat", "beacon"),
"greenhouse": ("habitat", "beacon"),
"beacon": ("workshop", "greenhouse"),
}
PARTS = ("Coil", "Cell")
def make_locations(seed):
return {"Coil": "workshop", "Cell": "greenhouse"}
@dataclass(frozen=True)
class State:
room: str = "habitat"
energy: int = 7
parts: tuple = ()
rescued: bool = False
def step(state, command, locations):
if state.rescued:
return state, "Radio already online."
if command.startswith("go "):
target = command[3:]
if target not in LINKS[state.room]:
return state, "That hatch is not connected."
if state.energy == 0:
return state, "Pip has no energy for another move."
return replace(state, room=target, energy=state.energy - 1), f"Pip enters {target.title()}."
if command == "take":
part = next((name for name, room in locations.items() if room == state.room), None)
if part is None or part in state.parts:
return state, "There is no new repair part here."
return replace(state, parts=state.parts + (part,)), f"Pip takes the {part}."
if command == "repair":
if state.room != "beacon" or not all(part in state.parts for part in PARTS):
return state, "Repair needs both parts at the Beacon."
return replace(state, rescued=True), "Rescue complete! Radio online."
return state, "Command not understood."
def show_state(state, locations, plain=False):
print(f"Location: {state.room.title()} | Energy: {state.energy} | Parts: {', '.join(state.parts) or 'none'}")
print("Exits: " + ", ".join(LINKS[state.room]))
def play(seed, energy, plain=False):
locations = make_locations(seed)
state, actions = State(energy=energy), []
print(f"Moonbase Rescue | Seed {seed}")
print("Commands: look, go ROOM, take, repair, quit.")
for _ in range(150):
if state.rescued:
return
try:
command = input("> ").strip().lower()
except EOFError:
return
if command == "quit":
return
if command == "look":
show_state(state, locations, plain)
continue
new_state, message = step(state, command, locations)
print(message)
if new_state != state:
actions.append(command)
state = new_state
print("Radio shift ended. Start a new mission to continue.")
def main():
parser = argparse.ArgumentParser(description="Guide Pip through four rooms and repair the Beacon.")
args = parser.parse_args()
play(0, 7, False)
if __name__ == "__main__":
main()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–24
-
Line 1
"""Moonbase Rescue. Guide Pip and repair the radio beacon.""" - This is a description for readers. Python does not print it automatically.
-
Line 2
import argparse - Bring in argparse. Its module name gives you access to the tools it contains.
-
Line 3
from dataclasses import dataclass, replace - Bring dataclass, replace into this file from dataclasses. These names can now be used directly.
-
Lines 6–11
LINKS = { "habitat": ("workshop", "greenhouse"), "workshop": ("habitat", "beacon"), "greenhouse": ("habitat", "beacon"), "beacon": ("workshop", "greenhouse"), } - Work out the value on the right, then store it in LINKS. Each colon pairs a key with its value. Commas group these values into an ordered tuple.
-
Line 12
PARTS = ("Coil", "Cell") - Work out the value on the right, then store it in PARTS. Commas group these values into an ordered tuple.
-
Line 15
def make_locations(seed): - Define make_locations, a reusable piece of the program. Its input names are seed. The indented body runs when something calls it.
-
Line 16
return {"Coil": "workshop", "Cell": "greenhouse"} - 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
@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
energy: int = 7 - Describe the expected type of energy as int and provide its starting value.
-
Line 23
parts: tuple = () - Describe the expected type of parts as tuple and provide its starting value. Commas group these values into an ordered tuple.
-
Line 24
rescued: bool = False - Describe the expected type of rescued as bool and provide its starting value.
Lines 27–39
-
Line 27
def step(state, command, locations): - Define step, a reusable piece of the program. Its input names are state, command, locations. The indented body runs when something calls it.
-
Line 28
if state.rescued: - Run the indented block only if this check is true.
-
Line 29
return state, "Radio 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 30
if command.startswith("go "): - Run the indented block only if this check is true. Check whether this text begins with the given prefix.
-
Line 31
target = command[3:] - Work out the value on the right, then store it in target. The slice copies a portion, stopping before the end index if one is given.
-
Line 32
if target not in LINKS[state.room]: - 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 33
return state, "That hatch is not connected." - 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 state.energy == 0: - Run the indented block only if this check is true.
-
Line 35
return state, "Pip has no energy for another move." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 36
return replace(state, room=target, energy=state.energy - 1), f"Pip enters {target.title()}." - 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 37
if command == "take": - Run the indented block only if this check is true.
-
Line 38
part = next((name for name, room in locations.items() if room == state.room), None) - Work out the value on the right, then store it in part. Take the first available result, or the given fallback if there is no result. The expression supplies matching values one at a time to the operation using it. Commas group these values into an ordered tuple.
-
Line 39
if part is None or part in state.parts: - Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Membership checks ask whether an item or key is in a collection.
Lines 40–56
-
Line 40
return state, "There is no new repair 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 41
return replace(state, parts=state.parts + (part,)), f"Pip takes the {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 42
if command == "repair": - Run the indented block only if this check is true.
-
Line 43
if state.room != "beacon" or not all(part in state.parts for part in PARTS): - Run the indented block only if this check is true. With or, the first true result can settle the check. The word not reverses which result counts as true. Check that every result is true.
-
Line 44
return state, "Repair needs both parts 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 45
return replace(state, rescued=True), "Rescue complete! Radio 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 46
return state, "Command not understood." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 49
def show_state(state, locations, plain=False): - Define show_state, a reusable piece of the program. Its input names are state, locations, plain. The indented body runs when something calls it.
-
Line 50
print(f"Location: {state.room.title()} | Energy: {state.energy} | Parts: {', '.join(state.parts) or 'none'}") - Show the message or value in the output. Python fills the braces with values before it uses the text. Return words with title-style capital letters for display.
-
Line 51
print("Exits: " + ", ".join(LINKS[state.room])) - Show the message or value in the output. 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 54
def play(seed, energy, plain=False): - Define play, a reusable piece of the program. Its input names are seed, energy, plain. The indented body runs when something calls it.
-
Line 55
locations = make_locations(seed) - Work out the value on the right, then store it in locations. Run make_locations with the supplied inputs and come back here when it returns.
-
Line 56
state, actions = State(energy=energy), [] - Give each returned value to the matching name, from left to right. Commas group these values into an ordered tuple. Create a mission state using the supplied field values and any defaults.
Lines 57–69
-
Line 57
print(f"Moonbase Rescue | Seed {seed}") - Show the message or value in the output. Python fills the braces with values before it uses the text.
-
Line 58
print("Commands: look, go ROOM, take, repair, quit.") - Show the message or value in the output.
-
Line 59
for _ in range(150): - Take one item at a time and give it to _, then run the indented block. Generate a sequence of integers that stops before the final limit.
-
Line 60
if state.rescued: - Run the indented block only if this check is true.
-
Line 61
return - Leave this function now.
-
Line 62
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 63
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 64
except EOFError: - Run this part only when the try block raises EOFError.
-
Line 65
return - Leave this function now.
-
Line 66
if command == "quit": - Run the indented block only if this check is true.
-
Line 67
return - Leave this function now.
-
Line 68
if command == "look": - Run the indented block only if this check is true.
-
Line 69
show_state(state, locations, plain) - Run show_state with the supplied inputs and come back here when it returns.
Lines 70–87
-
Line 70
continue - Skip the rest of this pass and start the next loop check.
-
Line 72
new_state, message = step(state, command, locations) - 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 73
print(message) - Show the message or value in the output.
-
Line 74
if new_state != state: - Run the indented block only if this check is true.
-
Line 75
actions.append(command) - Add the value to the end without replacing the earlier entries.
-
Line 76
state = new_state - Work out the value on the right, then store it in state.
-
Line 77
print("Radio shift ended. Start a new mission to continue.") - Show the message or value in the output.
-
Line 80
def main(): - Define main, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
-
Line 81
parser = argparse.ArgumentParser(description="Guide Pip through four rooms and repair the Beacon.") - Work out the value on the right, then store it in parser. Create the object that reads launch options and explains how to use them.
-
Line 82
args = parser.parse_args() - Work out the value on the right, then store it in args. Read the launch options and put the chosen values into an object.
-
Line 83
play(0, 7, False) - Run play with the supplied inputs and come back here when it returns.
-
Line 86
if __name__ == "__main__": - Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
-
Line 87
main() - Run main with the supplied inputs and come back here when it returns.
Test the mission
- From Habitat try go beacon. Then look to check that energy is still 7.
- Go to Workshop and take the Coil. Return via Habitat, collect the Cell in Greenhouse, then repair at Beacon.
If something goes wrong
- Pip starts in the wrong room.
- Check the defaults in State and make a fresh State at the start of each run.
- A failed move spends energy.
- Return the original state before calling replace, and subtract energy only on legal movement.
Mission extension
Add a message for an unknown command. Keep the fallback inside step and make sure it returns the same state.