Python lesson 50 of 50 · Expert projects · About 90 minutes
Ship the complete four-room game with repeatable missions, fair clues and a playable rescue you can share.

Mission Complete a mission from launch to successful radio repair, then verify the save, replay and automated checks.
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_50.py in a project folder and run python moonbase_50.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.
Find the entry point and the settings
Python calls main() at the bottom when you run this file directly. The parser reads seed, energy and mode switches. A special mode runs its branch and returns. Otherwise main calls play.
Find the map, seed and snapshots
LINKS maps rooms to exits. make_locations(seed) places the parts. State holds the room, remaining energy, parts and rescue status.
Follow a real command from input to result
play tidies input and handles look, hint, save, load and quit. It sends other commands to step for movement, pickup or repair. step returns a state and a message. play shows the message and records commands that changed the state.
Trace the two jobs of a save file
save_game writes a local JSON recipe. read_save and decode_record validate and replay it. Load uses the resulting state. --replay prints the commands and messages.
Connect the route finder to the demo
plan_route uses a queue and the same rules to find a shortest working sequence. run_demo starts a fresh state and applies and prints each command. It reports a problem if the route is None.
Find the supporting modes
--plain changes status formatting. --self-test checks 12 seeded missions. --audit checks 100 low-energy starts and three malformed saves.
How the pieces fit Follow one command through play, step and the resulting state and message. The planner, demo, tests, saves and audit all depend on those same rules.
-
Run moonbase_50.py with --demo --seed 0 --energy 5.
main selects the demo branch. Why The parser recognised --demo and the valid integer settings. -
Read the first two printed commands.
go greenhouse moves Pip and take picks up the Cell. Why The route planner can reach this part from the starting Habitat. -
Read the next two commands.
go beacon moves Pip and take collects the Coil. Why The seed puts the other required part in Beacon. -
Read the last command.
repair -> Rescue complete! Radio online. Why At Beacon, the rule sees both parts and returns a snapshot with rescued set to true.
Predict before you run Which part would you change to allow a new hatch from Habitat to Beacon?
Reveal the explanation
Change LINKS. Add a return exit too if travel should work both ways. run_tests expects that first move to fail, so update that test for the new map. Run the demo, self-test and audit afterwards.
Build the checkpoint
Python skills Release testing, CLI modes, Project documentation, Extension design.
1. Run the finished rescue
Save the final checkpoint as moonbase_50.py and open a terminal in its directory. Start normal play with python moonbase_50.py --seed 0 --energy 7 --plain. Use look for exits and nearby parts, go ROOM to move, take to collect the Coil or Cell and repair once both are at the Beacon. Type hint if you get stuck. The engine checks every action and ends play when the radio comes online.
def step(state, command, locations):
2. Show a complete example rescue
The final checkpoint adds --demo. It uses the planner to find a rescue route from a fresh start, then prints each command and the engine’s response as it plays that route. Unlike a save replay, the demonstration starts from the fresh seed you pass in. This mode makes it easy for another learner to discover the available controls and compare a successful run with their own. Run python moonbase_50.py --demo --seed 0 and read the commands before trying them yourself.
route = plan_route(state, locations)
3. Check the release and plan a new feature
Run three checks before calling the build finished. Use --self-test for the end-to-end campaign, then --audit for the low-energy sweep and malformed records. Finally start normal play, save midway and restore, then use --replay to inspect that saved action trace. Write a short release note with the seed that worked, the commands needed and the filename created by save. For your next project, sketch one feature, predict how it changes the state, and add a check for the old behaviour before editing the engine.
run_demo(args.seed, args.energy)
Complete Python checkpoint · moonbase_50.py
"""Moonbase Rescue. Guide Pip and repair the radio beacon."""
import argparse
from dataclasses import dataclass, replace
import random
from collections import deque
import json
from pathlib import Path
LINKS = {
"habitat": ("workshop", "greenhouse"),
"workshop": ("habitat", "beacon"),
"greenhouse": ("habitat", "beacon"),
"beacon": ("workshop", "greenhouse"),
}
PARTS = ("Coil", "Cell")
def make_locations(seed):
rng = random.Random(seed)
rooms = ("workshop", "greenhouse", "habitat", "beacon")
return dict(zip(PARTS, rng.sample(rooms, k=len(PARTS))))
@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 plan_route(start, locations):
frontier = deque([(start, ())])
seen = {start}
while frontier:
current, history = frontier.popleft()
if current.rescued:
return history
actions = [f"go {room}" for room in LINKS[current.room]] + ["take", "repair"]
for action in actions:
following, _ = step(current, action, locations)
if following not in seen:
seen.add(following)
frontier.append((following, history + (action,)))
return None
SAVE_FILE = Path("moonbase-rescue.json")
SIZE_LIMIT = 8192
MAX_ACTIONS = 32
def decode_record(data):
if not isinstance(data, dict) or type(data.get("version")) is not int or data["version"] != 1:
raise ValueError("Unknown save format.")
seed, actions = data.get("seed"), data.get("actions")
if type(seed) is not int or not 0 <= seed <= 9999:
raise ValueError("Seed must be an integer from 0 to 9999.")
energy = data.get("energy", 7)
if type(energy) is not int or not 5 <= energy <= 15:
raise ValueError("Energy must be an integer from 5 to 15.")
if not isinstance(actions, list) or len(actions) > MAX_ACTIONS:
raise ValueError("Invalid action list.")
locations, state, log = make_locations(seed), State(energy=energy), []
for command in actions:
if not isinstance(command, str) or len(command) > 24:
raise ValueError("Invalid action text.")
following, message = step(state, command, locations)
if following == state:
raise ValueError(f"Illegal saved action: {command}")
log.append((command, message))
state = following
return seed, energy, actions, state, log
def save_game(seed, energy, actions):
data = {"version": 1, "seed": seed, "energy": energy, "actions": actions}
temporary = SAVE_FILE.with_suffix(".tmp")
temporary.write_text(json.dumps(data, indent=2), encoding="utf-8")
temporary.replace(SAVE_FILE)
def read_save():
with SAVE_FILE.open("rb") as stream:
payload = stream.read(SIZE_LIMIT + 1)
if len(payload) > SIZE_LIMIT:
raise ValueError("The save file is too large.")
try:
data = json.loads(payload)
except RecursionError as error:
raise ValueError("The save is nested too deeply.") from error
return decode_record(data)
def run_tests():
count = 0
for seed in range(12):
locations = make_locations(seed)
start = State()
assert step(start, "go beacon", locations)[0] == start
route = plan_route(start, locations)
assert route is not None, seed
_, _, _, end, trace = decode_record({"version": 1, "seed": seed, "actions": list(route)})
assert end.rescued and end.energy >= 0 and len(trace) == len(route)
count += 1
print(f"Self-test passed: {count} seeded rescue missions.")
def audit_scenarios():
worst = 0
for seed in range(100):
locations = make_locations(seed)
route = plan_route(State(energy=5), locations)
assert route is not None, f"No low-energy route for seed {seed}"
movement = sum(command.startswith("go ") for command in route)
assert movement <= 5
worst = max(worst, movement)
for broken in (
{"version": True, "seed": 0, "actions": []},
{"version": 1, "seed": -1, "actions": []},
{"version": 1, "seed": 0, "actions": ["go beacon"]},
):
try:
decode_record(broken)
except ValueError:
continue
raise AssertionError(f"Unexpectedly accepted {broken!r}")
print(f"Audit passed: 100 seeds, 3 malformed saves; worst route {worst} moves.")
def run_demo(seed, energy):
locations = make_locations(seed)
state = State(energy=energy)
route = plan_route(state, locations)
if route is None:
print("No demo route for this mission.")
return
for command in route:
state, message = step(state, command, locations)
print(f"{command} -> {message}")
def show_state(state, locations, plain=False):
parts = ", ".join(state.parts) or "none"
if plain:
print(f"Location: {state.room.title()}. Energy: {state.energy}. Parts: {parts}.")
else:
print(f"[{state.room.upper()}] Energy {state.energy} | Parts: {parts}")
print("Exits: " + ", ".join(room.title() for room in LINKS[state.room]))
available = [part for part, room in locations.items() if room == state.room and part not in state.parts]
print("Here: " + (", ".join(available) if available else "no new repair parts"))
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, hint, save, load, 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
if command == "hint":
route = plan_route(state, locations)
print(f"Try: {route[0]}" if route else "No rescue route from here. Restart and try another route.")
continue
if command == "save":
try:
save_game(seed, energy, actions)
print("Mission saved.")
except OSError:
print("Could not write the local save.")
continue
if command == "load":
try:
seed, energy, actions, state, _ = read_save()
locations = make_locations(seed)
print("Mission loaded.")
except (OSError, ValueError):
print("Could not load a valid local save.")
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.")
parser.add_argument("--seed", type=int, metavar="0..9999", default=0, help="choose a repeatable part layout")
parser.add_argument("--replay", action="store_true", help="replay the latest local save")
parser.add_argument("--self-test", action="store_true", help="verify 12 complete seeded missions")
parser.add_argument("--plain", action="store_true", help="use spoken-style status labels")
parser.add_argument("--energy", type=int, choices=range(5, 16), metavar="5..15", default=7)
parser.add_argument("--audit", action="store_true", help="verify 100 low-energy starts and bad saves")
parser.add_argument("--demo", action="store_true", help="print an example rescue route")
args = parser.parse_args()
if not 0 <= args.seed <= 9999:
parser.error("--seed must be from 0 to 9999")
if args.replay:
try:
_, _, _, _, log = read_save()
except (OSError, ValueError):
print("No valid replay file.")
return
for command, message in log:
print(f"{command} -> {message}")
return
if args.self_test:
run_tests()
return
if args.audit:
audit_scenarios()
return
if args.demo:
run_demo(args.seed, args.energy)
return
play(args.seed, args.energy, args.plain)
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–22
-
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.
-
Line 4
import random - Bring in random. Its module name gives you access to the tools it contains.
-
Line 5
from collections import deque - Bring deque into this file from collections. These names can now be used directly.
-
Line 6
import json - Bring in json. Its module name gives you access to the tools it contains.
-
Line 7
from pathlib import Path - Bring Path into this file from pathlib. These names can now be used directly.
-
Lines 10–15
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 16
PARTS = ("Coil", "Cell") - Work out the value on the right, then store it in PARTS. Commas group these values into an ordered tuple.
-
Line 19
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 20
rng = random.Random(seed) - Work out the value on the right, then store it in rng. Make an independent random generator. Reusing its seed repeats the sequence.
-
Line 21
rooms = ("workshop", "greenhouse", "habitat", "beacon") - Work out the value on the right, then store it in rooms. Commas group these values into an ordered tuple.
-
Line 22
return dict(zip(PARTS, rng.sample(rooms, k=len(PARTS)))) - Leave this function now and hand the result back to the line that called it. Make a dictionary that connects keys to their values. Pair the first items together, then the second items, and so on. Pick several different entries without using any entry twice.
Lines 25–39
-
Line 25
@dataclass(frozen=True) - Ask Python to create the usual data-handling methods from the listed fields.
-
Line 26
class State: - Define State, a class that groups related data or behaviour.
-
Line 27
room: str = "habitat" - Describe the expected type of room as str and provide its starting value.
-
Line 28
energy: int = 7 - Describe the expected type of energy as int and provide its starting value.
-
Line 29
parts: tuple = () - Describe the expected type of parts as tuple and provide its starting value. Commas group these values into an ordered tuple.
-
Line 30
rescued: bool = False - Describe the expected type of rescued as bool and provide its starting value.
-
Line 33
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 34
if state.rescued: - Run the indented block only if this check is true.
-
Line 35
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 36
if command.startswith("go "): - Run the indented block only if this check is true. Check whether this text begins with the given prefix.
-
Line 37
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 38
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 39
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.
Lines 40–52
-
Line 40
if state.energy == 0: - Run the indented block only if this check is true.
-
Line 41
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 42
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 43
if command == "take": - Run the indented block only if this check is true.
-
Line 44
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 45
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.
-
Line 46
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 47
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 48
if command == "repair": - Run the indented block only if this check is true.
-
Line 49
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 50
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 51
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 52
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.
Lines 55–67
-
Line 55
def plan_route(start, locations): - Define plan_route, a reusable piece of the program. Its input names are start, locations. The indented body runs when something calls it.
-
Line 56
frontier = deque([(start, ())]) - Work out the value on the right, then store it in frontier. Create a queue that can efficiently take items from either end. Commas group these values into an ordered tuple.
-
Line 57
seen = {start} - Work out the value on the right, then store it in seen.
-
Line 58
while frontier: - Check frontier before each pass. Repeat the indented work while it is true.
-
Line 59
current, history = frontier.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 60
if current.rescued: - Run the indented block only if this check is true.
-
Line 61
return history - Leave this function now and hand the result back to the line that called it.
-
Line 62
actions = [f"go {room}" for room in LINKS[current.room]] + ["take", "repair"] - Work out the value on the right, then store it in actions. The brackets build a new list by looping through eligible values. Python fills the braces with values before it uses the text. The brackets look up a dictionary key or a position that starts at zero.
-
Line 63
for action in actions: - Take one item at a time and give it to action, then run the indented block.
-
Line 64
following, _ = step(current, action, 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 65
if following 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 66
seen.add(following) - Add the value to the set. A set keeps at most one copy.
-
Line 67
frontier.append((following, history + (action,))) - Add the value to the end without replacing the earlier entries. Commas group these values into an ordered tuple.
Lines 68–84
-
Line 68
return None - Leave this function now and hand the result back to the line that called it.
-
Line 71
SAVE_FILE = Path("moonbase-rescue.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 72
SIZE_LIMIT = 8192 - Work out the value on the right, then store it in SIZE_LIMIT.
-
Line 73
MAX_ACTIONS = 32 - Work out the value on the right, then store it in MAX_ACTIONS.
-
Line 76
def decode_record(data): - Define decode_record, a reusable piece of the program. Its input names are data. The indented body runs when something calls it.
-
Line 77
if not isinstance(data, dict) or type(data.get("version")) is not int or data["version"] != 1: - 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 whether the value is of the requested type or a type based on it.
-
Line 78
raise ValueError("Unknown save format.") - Stop this path and report ValueError("Unknown save format.") to whoever called this code.
-
Line 79
seed, actions = data.get("seed"), data.get("actions") - Give each returned value to the matching name, from left to right. Commas group these values into an ordered tuple. Look up a key. Use the given fallback, or None, if the key is missing.
-
Line 80
if type(seed) is not int or not 0 <= seed <= 9999: - 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. Find the exact type of this value.
-
Line 81
raise ValueError("Seed must be an integer from 0 to 9999.") - Stop this path and report ValueError("Seed must be an integer from 0 to 9999.") to whoever called this code.
-
Line 82
energy = data.get("energy", 7) - Work out the value on the right, then store it in energy. Look up a key. Use the given fallback, or None, if the key is missing.
-
Line 83
if type(energy) is not int or not 5 <= energy <= 15: - 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. Find the exact type of this value.
-
Line 84
raise ValueError("Energy must be an integer from 5 to 15.") - Stop this path and report ValueError("Energy must be an integer from 5 to 15.") to whoever called this code.
Lines 85–99
-
Line 85
if not isinstance(actions, list) or len(actions) > MAX_ACTIONS: - 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 whether the value is of the requested type or a type based on it.
-
Line 86
raise ValueError("Invalid action list.") - Stop this path and report ValueError("Invalid action list.") to whoever called this code.
-
Line 87
locations, state, log = make_locations(seed), State(energy=energy), [] - Give each returned value to the matching name, from left to right. Commas group these values into an ordered tuple. Run make_locations with the supplied inputs and come back here when it returns. Create a mission state using the supplied field values and any defaults.
-
Line 88
for command in actions: - Take one item at a time and give it to command, then run the indented block.
-
Line 89
if not isinstance(command, str) or len(command) > 24: - 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 whether the value is of the requested type or a type based on it.
-
Line 90
raise ValueError("Invalid action text.") - Stop this path and report ValueError("Invalid action text.") to whoever called this code.
-
Line 91
following, 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 92
if following == state: - Run the indented block only if this check is true.
-
Line 93
raise ValueError(f"Illegal saved action: {command}") - Stop this path and report ValueError(f"Illegal saved action: {command}") to whoever called this code.
-
Line 94
log.append((command, message)) - Add the value to the end without replacing the earlier entries. Commas group these values into an ordered tuple.
-
Line 95
state = following - Work out the value on the right, then store it in state.
-
Line 96
return seed, energy, actions, state, log - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 99
def save_game(seed, energy, actions): - Define save_game, a reusable piece of the program. Its input names are seed, energy, actions. The indented body runs when something calls it.
Lines 100–114
-
Line 100
data = {"version": 1, "seed": seed, "energy": energy, "actions": actions} - Work out the value on the right, then store it in data. Each colon pairs a key with its value.
-
Line 101
temporary = SAVE_FILE.with_suffix(".tmp") - Work out the value on the right, then store it in temporary. Build a path with a different ending. This does not rename any file yet.
-
Line 102
temporary.write_text(json.dumps(data, indent=2), 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 103
temporary.replace(SAVE_FILE) - Move the temporary file into the final save location.
-
Line 106
def read_save(): - Define read_save, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
-
Line 107
with SAVE_FILE.open("rb") as stream: - Open the file in the stated mode and use it for the indented instructions. Python closes it automatically when the block ends. Give the opened file the name stream inside this block.
-
Line 108
payload = stream.read(SIZE_LIMIT + 1) - Work out the value on the right, then store it in payload. Read the requested amount from the open file.
-
Line 109
if len(payload) > SIZE_LIMIT: - Run the indented block only if this check is true. Count the characters or items.
-
Line 110
raise ValueError("The save file is too large.") - Stop this path and report ValueError("The save file is too large.") to whoever called this code.
-
Line 111
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 112
data = json.loads(payload) - Work out the value on the right, then store it in data. Read JSON text or bytes and turn it back into Python data.
-
Line 113
except RecursionError as error: - Run this part only when the try block raises RecursionError. Use error to refer to that error here.
-
Line 114
raise ValueError("The save is nested too deeply.") from error - Stop this path and report ValueError("The save is nested too deeply.") to whoever called this code. Keep the original problem linked with from.
Lines 115–129
-
Line 115
return decode_record(data) - Leave this function now and hand the result back to the line that called it. Run decode_record with the supplied inputs and come back here when it returns.
-
Line 118
def run_tests(): - Define run_tests, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
-
Line 119
count = 0 - Work out the value on the right, then store it in count.
-
Line 120
for seed in range(12): - Take one item at a time and give it to seed, then run the indented block. Generate a sequence of integers that stops before the final limit.
-
Line 121
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 122
start = State() - Work out the value on the right, then store it in start. Create a mission state using the supplied field values and any defaults.
-
Line 123
assert step(start, "go beacon", locations)[0] == start - Check this expected result. If it is false while assertions are enabled, Python raises AssertionError.
-
Line 124
route = plan_route(start, locations) - Work out the value on the right, then store it in route. Run plan_route with the supplied inputs and come back here when it returns.
-
Line 125
assert route is not None, seed - Check this expected result. If it is false while assertions are enabled, Python raises AssertionError.
-
Line 126
_, _, _, end, trace = decode_record({"version": 1, "seed": seed, "actions": list(route)}) - Give each returned value to the matching name, from left to right. Run decode_record with the supplied inputs and come back here when it returns. Each colon pairs a key with its value. Build an ordered list from these values.
-
Line 127
assert end.rescued and end.energy >= 0 and len(trace) == len(route) - Check this expected result. If it is false while assertions are enabled, Python raises AssertionError.
-
Line 128
count += 1 - Update count in place in the program’s flow: add using the value on the right.
-
Line 129
print(f"Self-test passed: {count} seeded rescue missions.") - Show the message or value in the output. Python fills the braces with values before it uses the text.
Lines 132–148
-
Line 132
def audit_scenarios(): - Define audit_scenarios, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
-
Line 133
worst = 0 - Work out the value on the right, then store it in worst.
-
Line 134
for seed in range(100): - Take one item at a time and give it to seed, then run the indented block. Generate a sequence of integers that stops before the final limit.
-
Line 135
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 136
route = plan_route(State(energy=5), locations) - Work out the value on the right, then store it in route. Run plan_route with the supplied inputs and come back here when it returns. Create a mission state using the supplied field values and any defaults.
-
Line 137
assert route is not None, f"No low-energy route for seed {seed}" - Check this expected result. If it is false while assertions are enabled, Python raises AssertionError.
-
Line 138
movement = sum(command.startswith("go ") for command in route) - Work out the value on the right, then store it in movement. Add all the values. The expression supplies matching values one at a time to the operation using it. Check whether this text begins with the given prefix.
-
Line 139
assert movement <= 5 - Check this expected result. If it is false while assertions are enabled, Python raises AssertionError.
-
Line 140
worst = max(worst, movement) - Work out the value on the right, then store it in worst. Choose the largest value.
-
Lines 141–145
for broken in ( {"version": True, "seed": 0, "actions": []}, {"version": 1, "seed": -1, "actions": []}, {"version": 1, "seed": 0, "actions": ["go beacon"]}, ): - Take one item at a time and give it to broken, then run the indented block. Commas group these values into an ordered tuple. Each colon pairs a key with its value.
-
Line 146
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 147
decode_record(broken) - Run decode_record with the supplied inputs and come back here when it returns.
-
Line 148
except ValueError: - Run this part only when the try block raises ValueError.
Lines 149–163
-
Line 149
continue - Skip the rest of this pass and start the next loop check.
-
Line 150
raise AssertionError(f"Unexpectedly accepted {broken!r}") - Stop this path and report AssertionError(f"Unexpectedly accepted {broken!r}") to whoever called this code.
-
Line 151
print(f"Audit passed: 100 seeds, 3 malformed saves; worst route {worst} moves.") - Show the message or value in the output. Python fills the braces with values before it uses the text.
-
Line 154
def run_demo(seed, energy): - Define run_demo, a reusable piece of the program. Its input names are seed, energy. The indented body runs when something calls it.
-
Line 155
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 156
state = State(energy=energy) - 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 157
route = plan_route(state, locations) - Work out the value on the right, then store it in route. Run plan_route with the supplied inputs and come back here when it returns.
-
Line 158
if route 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 159
print("No demo route for this mission.") - Show the message or value in the output.
-
Line 160
return - Leave this function now.
-
Line 161
for command in route: - Take one item at a time and give it to command, then run the indented block.
-
Line 162
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 163
print(f"{command} -> {message}") - Show the message or value in the output. Python fills the braces with values before it uses the text.
Lines 166–180
-
Line 166
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 167
parts = ", ".join(state.parts) 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.
-
Line 168
if plain: - Run the indented block only if this check is true.
-
Line 169
print(f"Location: {state.room.title()}. Energy: {state.energy}. Parts: {parts}.") - 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 170
else: - Take this branch if the earlier checks for this decision were false.
-
Line 171
print(f"[{state.room.upper()}] Energy {state.energy} | Parts: {parts}") - Show the message or value in the output. Python fills the braces with values before it uses the text. Return an uppercase copy for display.
-
Line 172
print("Exits: " + ", ".join(room.title() for room in LINKS[state.room])) - Show the message or value in the output. Put strings together with the text before .join separating them. The expression supplies matching values one at a time to the operation using it.
-
Line 173
available = [part for part, room in locations.items() if room == state.room and part not in state.parts] - Work out the value on the right, then store it in available. The brackets build a new list by looping through eligible values. Commas group these values into an ordered tuple. Make the dictionary's key and value pairs available to loop over.
-
Line 174
print("Here: " + (", ".join(available) if available else "no new repair parts")) - 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 177
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 178
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 179
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.
-
Line 180
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.
Lines 181–193
-
Line 181
print("Commands: look, go ROOM, take, repair, hint, save, load, quit.") - Show the message or value in the output.
-
Line 182
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 183
if state.rescued: - Run the indented block only if this check is true.
-
Line 184
return - Leave this function now.
-
Line 185
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 186
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 187
except EOFError: - Run this part only when the try block raises EOFError.
-
Line 188
return - Leave this function now.
-
Line 189
if command == "quit": - Run the indented block only if this check is true.
-
Line 190
return - Leave this function now.
-
Line 191
if command == "look": - Run the indented block only if this check is true.
-
Line 192
show_state(state, locations, plain) - Run show_state with the supplied inputs and come back here when it returns.
-
Line 193
continue - Skip the rest of this pass and start the next loop check.
Lines 194–206
-
Line 194
if command == "hint": - Run the indented block only if this check is true.
-
Line 195
route = plan_route(state, locations) - Work out the value on the right, then store it in route. Run plan_route with the supplied inputs and come back here when it returns.
-
Line 196
print(f"Try: {route[0]}" if route else "No rescue route from here. Restart and try another route.") - Show the message or value in the output. Choose the first value if the condition is true, otherwise choose the value after else. Python fills the braces with values before it uses the text.
-
Line 197
continue - Skip the rest of this pass and start the next loop check.
-
Line 198
if command == "save": - Run the indented block only if this check is true.
-
Line 199
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 200
save_game(seed, energy, actions) - Run save_game with the supplied inputs and come back here when it returns.
-
Line 201
print("Mission saved.") - Show the message or value in the output.
-
Line 202
except OSError: - Run this part only when the try block raises OSError.
-
Line 203
print("Could not write the local save.") - Show the message or value in the output.
-
Line 204
continue - Skip the rest of this pass and start the next loop check.
-
Line 205
if command == "load": - Run the indented block only if this check is true.
-
Line 206
try: - Attempt the indented instructions. A matching except below can deal with a problem.
Lines 207–221
-
Line 207
seed, energy, actions, state, _ = read_save() - Give each returned value to the matching name, from left to right. Run read_save with the supplied inputs and come back here when it returns.
-
Line 208
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 209
print("Mission loaded.") - Show the message or value in the output.
-
Line 210
except (OSError, ValueError): - Run this part only when the try block raises (OSError, ValueError).
-
Line 211
print("Could not load a valid local save.") - Show the message or value in the output.
-
Line 212
continue - Skip the rest of this pass and start the next loop check.
-
Line 213
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 214
print(message) - Show the message or value in the output.
-
Line 215
if new_state != state: - Run the indented block only if this check is true.
-
Line 216
actions.append(command) - Add the value to the end without replacing the earlier entries.
-
Line 217
state = new_state - Work out the value on the right, then store it in state.
-
Line 218
print("Radio shift ended. Start a new mission to continue.") - Show the message or value in the output.
-
Line 221
def main(): - Define main, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Lines 222–234
-
Line 222
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 223
parser.add_argument("--seed", type=int, metavar="0..9999", default=0, help="choose a repeatable part layout") - Register an option that someone can use when starting the program.
-
Line 224
parser.add_argument("--replay", action="store_true", help="replay the latest local save") - Register an option that someone can use when starting the program.
-
Line 225
parser.add_argument("--self-test", action="store_true", help="verify 12 complete seeded missions") - Register an option that someone can use when starting the program.
-
Line 226
parser.add_argument("--plain", action="store_true", help="use spoken-style status labels") - Register an option that someone can use when starting the program.
-
Line 227
parser.add_argument("--energy", type=int, choices=range(5, 16), metavar="5..15", default=7) - Register an option that someone can use when starting the program. Generate a sequence of integers that stops before the final limit.
-
Line 228
parser.add_argument("--audit", action="store_true", help="verify 100 low-energy starts and bad saves") - Register an option that someone can use when starting the program.
-
Line 229
parser.add_argument("--demo", action="store_true", help="print an example rescue route") - Register an option that someone can use when starting the program.
-
Line 230
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 231
if not 0 <= args.seed <= 9999: - Run the indented block only if this check is true. The word not reverses which result counts as true. Every comparison in the range must be true.
-
Line 232
parser.error("--seed must be from 0 to 9999") - Show the command-line problem and stop with an error status.
-
Line 233
if args.replay: - Run the indented block only if this check is true.
-
Line 234
try: - Attempt the indented instructions. A matching except below can deal with a problem.
Lines 235–247
-
Line 235
_, _, _, _, log = read_save() - Give each returned value to the matching name, from left to right. Run read_save with the supplied inputs and come back here when it returns.
-
Line 236
except (OSError, ValueError): - Run this part only when the try block raises (OSError, ValueError).
-
Line 237
print("No valid replay file.") - Show the message or value in the output.
-
Line 238
return - Leave this function now.
-
Line 239
for command, message in log: - Take one item at a time and give it to command, message, then run the indented block.
-
Line 240
print(f"{command} -> {message}") - Show the message or value in the output. Python fills the braces with values before it uses the text.
-
Line 241
return - Leave this function now.
-
Line 242
if args.self_test: - Run the indented block only if this check is true.
-
Line 243
run_tests() - Run run_tests with the supplied inputs and come back here when it returns.
-
Line 244
return - Leave this function now.
-
Line 245
if args.audit: - Run the indented block only if this check is true.
-
Line 246
audit_scenarios() - Run audit_scenarios with the supplied inputs and come back here when it returns.
-
Line 247
return - Leave this function now.
Lines 248–255
-
Line 248
if args.demo: - Run the indented block only if this check is true.
-
Line 249
run_demo(args.seed, args.energy) - Run run_demo with the supplied inputs and come back here when it returns.
-
Line 250
return - Leave this function now.
-
Line 251
play(args.seed, args.energy, args.plain) - Run play with the supplied inputs and come back here when it returns.
-
Line 254
if __name__ == "__main__": - Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
-
Line 255
main() - Run main with the supplied inputs and come back here when it returns.
Test the mission
- Play seed 0 without the demo. Try an impossible move before repairing, then check how many moves you actually spent.
- Save halfway and quit. Run --replay, check what it recorded and launch again to finish the mission.
- Run --help and write three lines that would help a friend start a mission, ask for a hint and save progress.
If something goes wrong
- My command-line option has no effect.
- Put options after the Python filename and verify their spellings using --help.
- Adding a feature makes an old save fail.
- First check if the existing format can express the change. Introduce a new version and a clear migration rule if the format must change.
Mission extension
Design an extra room for the moon base. Draw both directions of its hatch, decide whether it can contain a part, and extend the route audit before changing difficulty.