Python 20 · Launch the complete Beacon mission

Python lesson 20 of 50 · Early intermediate · About 50 minutes

Finish the first playable Moonbase Rescue mission and run a field test for the win, a mistake and a fresh start.

Pip sits at the crossing of moon tracks near the lit Workshop and Greenhouse, with a beacon on a far ridge.

Mission Give every run a fresh state dictionary and verify the whole mission with repeatable checks.

Get ready

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

Open the browser Python editor (opens in a new tab), replace its example with the complete checkpoint below and choose Run. Use Python 3.10 or newer.

Start fresh. Create one new state and cargo list.. → Play the route. Collect two parts and unlock the Beacon.. → Verify the ending. Check the win, bad code and restart separately..
Start fresh → Play the route → Verify the ending

Understand the Python in this lesson

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

Create a fresh mission on demand

new_state() has empty parentheses because it takes no starting inputs. Its return gives back a new dictionary each time. The [] inside the dictionary makes a separate cargo list for each mission. Collected parts from the old run stay in the old mission record.

Read the main guard

__name__ is a name Python sets while loading a file. When you run this file directly, its value is "__main__". The equality check makes the indented line run for that launch. When a test imports the file, it can use the functions without opening an interactive radio prompt.

Read a nested function call inside out

In play(new_state()), Python calls new_state() first and uses the returned dictionary as the argument for play(). The loop reads commands, chooses a function from ACTIONS, and passes that same mission record to each action.

Try more than one kind of ending

An end-to-end test is a run from the opening to an expected outcome. A successful run checks movement, the two parts, the puzzle and repair in one go. A fresh run with a wrong code checks that the panel stays closed, and another fresh run checks the starting values.

How the pieces fit This chapter connects a fixed map, one fresh record of player progress and a command loop. In the next chapter you’ll practise checking smaller parts of those rules and saving a mission so it can be restored.

Follow one run, step by step
  1. Run the file directly and enter status
    Habitat | Energy: 8 | Cargo: empty Why The main guard has started play with a new mission record.
  2. Enter go north, take coil, go south, go east, take cell, go north
    Pip is at Beacon with both parts and four units of energy. Why Four legal doors cost one unit each. Taking the parts changes cargo.
  3. Enter panel 00 and then repair
    Wrong code. Check the Workshop clue. then Open the panel before fitting the parts. Why The wrong text leaves the panel flag false even with both parts.
  4. Enter panel 42 and repair
    Signal restored. Rescue is on its way! Why The open panel, correct room and full cargo allow a rescue.
  5. Run again and enter status
    Habitat | Energy: 8 | Cargo: empty Why The new state and new cargo list leave the completed mission behind.

Predict before you run If you call new_state() twice and add a Coil to the first mission’s cargo, what will be in the second mission’s cargo?

Reveal the explanation

It will be empty. Each call runs the dictionary expression again, including its empty-list expression. The two mission records have different cargo lists.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills Fresh state factory, Main guard, End-to-end testing.

1. Build a fresh mission on demand

Move the starting dictionary into new_state(). Each call returns a newly created dictionary and a new empty list for the cargo. That matters if you later play two rounds in the same Python session. Find the empty list in the checkpoint and make sure it lives inside the function, where each new mission receives its own cargo hold.

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

2. Choose when the game should start

At the bottom, the main guard checks whether you directly ran this file. If so, it calls play(new_state()). Later lessons can import the file to test a helper without opening the interactive prompt. You can still run the checkpoint now and play with look, status, map and the movement and repair commands.

if __name__ == "__main__":
    play(new_state())

3. Run three field tests

First take the winning route and record the final signal. Next waste energy near the Habitat and record the battery ending. Finally start a fresh run, ask for status and confirm the starter cargo is empty and the battery reads eight. A game can have a correct winning route and still carry a bug in its restart, so record each result separately.

if not state["rescued"] and power_failed(state):
            print("Battery empty. Mission stopped.")
            break
    return state
Complete Python checkpoint · moonbase_20.py
WORLD = {
    "Habitat": {"scene": "Pip wakes in the Habitat.", "exits": {"north": "Workshop", "east": "Greenhouse"}},
    "Workshop": {"scene": "Tools click together in the Workshop.", "exits": {"south": "Habitat", "east": "Beacon"}},
    "Greenhouse": {"scene": "Leaves brush the Greenhouse window.", "exits": {"west": "Habitat", "north": "Beacon"}},
    "Beacon": {"scene": "The Beacon stands quiet.", "exits": {"west": "Workshop", "south": "Greenhouse"}},
}

ROOM_PARTS = {"Workshop": "Coil", "Greenhouse": "Cell"}

CLUES = {"Workshop": "A note reads: Beacon panel code 42."}
PANEL_CODE = "42"

def look(state):
    room = state["room"]
    info = WORLD[room]
    print(info["scene"])
    print("Exits:", ", ".join(info["exits"]))
    part = ROOM_PARTS.get(room)
    if part is not None and part not in state["parts"]:
        print("You can see a", part)
    if room in CLUES:
        print(CLUES[room])

def show_status(state):
    cargo = ", ".join(state["parts"]) or "empty"
    print(f'{state["room"]} | Energy: {state["energy"]} | Cargo: {cargo}')

def read_command(text):
    words = text.strip().lower().split(maxsplit=1)
    if not words:
        return "", ""
    command = words[0]
    argument = words[1].strip() if len(words) == 2 else ""
    return command, argument

def move(state, direction):
    exits = WORLD[state["room"]]["exits"]
    destination = exits.get(direction)
    if destination is None:
        print("That direction has no exit here.")
        return
    if state["energy"] == 0:
        print("Pip has no energy left to move.")
        return
    state["energy"] -= 1
    state["room"] = destination
    print("Pip arrives at the", destination)

def take(state, item):
    part = ROOM_PARTS.get(state["room"])
    if part is None or item != part.lower():
        print("That part is not here.")
    elif part in state["parts"]:
        print("You already collected that part.")
    else:
        state["parts"].append(part)
        print("Collected:", part)

def open_panel(state, code):
    if state["room"] != "Beacon":
        print("The panel is at the Beacon.")
    elif code != PANEL_CODE:
        print("Wrong code. Check the Workshop clue.")
    else:
        state["panel_open"] = True
        print("Beacon panel open.")

def repair(state):
    if state["room"] != "Beacon":
        print("Find the Beacon first.")
    elif not all(part in state["parts"] for part in ROOM_PARTS.values()):
        print("You still need the Coil and Cell.")
    elif not state["panel_open"]:
        print("Open the panel before fitting the parts.")
    else:
        state["rescued"] = True
        print("Signal restored. Rescue is on its way!")


def power_failed(state):
    can_finish = (
        state["room"] == "Beacon"
        and all(part in state["parts"] for part in ROOM_PARTS.values())
    )
    return state["energy"] == 0 and not can_finish

def show_map(state, argument):
    for room, info in WORLD.items():
        doors = ", ".join(f"{way} to {target}" for way, target in info["exits"].items())
        print(f"{room}: {doors}")


def show_help(state, argument):
    print("Try: look, status, map, go north, take coil, panel 42, repair, quit.")


def command_look(state, argument):
    look(state)


def command_status(state, argument):
    show_status(state)


def command_repair(state, argument):
    repair(state)


ACTIONS = {
    "look": command_look,
    "status": command_status,
    "go": move,
    "take": take,
    "panel": open_panel,
    "repair": command_repair,
    "map": show_map,
    "help": show_help,
}

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

def play(state):
    print("Moonbase Rescue")
    look(state)
    show_help(state, "")
    while not state["rescued"]:
        try:
            raw = input("Pip > ")
        except EOFError:
            print("Radio closed.")
            break
        command, argument = read_command(raw)
        if command == "quit":
            print("Mission paused.")
            break

        action = ACTIONS.get(command)
        if action is None:
            print("Unknown command. Try help.")
        else:
            action(state, argument)

        if not state["rescued"] and power_failed(state):
            print("Battery empty. Mission stopped.")
            break
    return state

if __name__ == "__main__":
    play(new_state())

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–21
Lines 1–6 WORLD = { "Habitat": {"scene": "Pip wakes in the Habitat.", "exits": {"north": "Workshop", "east": "Greenhouse"}}, "Workshop": {"scene": "Tools click together in the Workshop.", "exits": {"south": "Habitat", "east": "Beacon"}}, "Greenhouse": {"scene": "Leaves brush the Greenhouse window.", "exits": {"west": "Habitat", "north": "Beacon"}}, "Beacon": {"scene": "The Beacon stands quiet.", "exits": {"west": "Workshop", "south": "Greenhouse"}}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 8 ROOM_PARTS = {"Workshop": "Coil", "Greenhouse": "Cell"}
Work out the value on the right, then store it in ROOM_PARTS. Each colon pairs a key with its value.
Line 10 CLUES = {"Workshop": "A note reads: Beacon panel code 42."}
Work out the value on the right, then store it in CLUES. Each colon pairs a key with its value.
Line 11 PANEL_CODE = "42"
Work out the value on the right, then store it in PANEL_CODE.
Line 13 def look(state):
Define look, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 14 room = state["room"]
Work out the value on the right, then store it in room. The brackets look up a dictionary key or a position that starts at zero.
Line 15 info = WORLD[room]
Work out the value on the right, then store it in info. The brackets look up a dictionary key or a position that starts at zero.
Line 16 print(info["scene"])
Show the message or value in the output. The brackets look up a dictionary key or a position that starts at zero.
Line 17 print("Exits:", ", ".join(info["exits"]))
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 18 part = ROOM_PARTS.get(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 19 if part is not None and part not in state["parts"]:
Run the indented block only if this check is true. With and, every check must be true. 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 20 print("You can see a", part)
Show the message or value in the output.
Line 21 if room in CLUES:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Lines 22–37
Line 22 print(CLUES[room])
Show the message or value in the output. The brackets look up a dictionary key or a position that starts at zero.
Line 24 def show_status(state):
Define show_status, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 25 cargo = ", ".join(state["parts"]) or "empty"
Work out the value on the right, then store it in cargo. With or, the first true result can settle the check. Put strings together with the text before .join separating them. The brackets look up a dictionary key or a position that starts at zero.
Line 26 print(f'{state["room"]} | Energy: {state["energy"]} | Cargo: {cargo}')
Show the message or value in the output. 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 28 def read_command(text):
Define read_command, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 29 words = text.strip().lower().split(maxsplit=1)
Work out the value on the right, then store it in words. Return a copy with whitespace removed from the beginning and end. Return a lowercase copy so capital letters do not change a command. Separate the string into a list of pieces.
Line 30 if not words:
Run the indented block only if this check is true. The word not reverses which result counts as true.
Line 31 return "", ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 32 command = words[0]
Work out the value on the right, then store it in command. The brackets look up a dictionary key or a position that starts at zero.
Line 33 argument = words[1].strip() if len(words) == 2 else ""
Work out the value on the right, then store it in argument. Choose the first value if the condition is true, otherwise choose the value after else. Count the characters or items. Return a copy with whitespace removed from the beginning and end.
Line 34 return command, argument
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 def move(state, direction):
Define move, a reusable piece of the program. Its input names are state, direction. The indented body runs when something calls it.
Line 37 exits = WORLD[state["room"]]["exits"]
Work out the value on the right, then store it in exits. The brackets look up a dictionary key or a position that starts at zero.
Lines 38–51
Line 38 destination = exits.get(direction)
Work out the value on the right, then store it in destination. Look up a key. Use the given fallback, or None, if the key is missing.
Line 39 if destination is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 40 print("That direction has no exit here.")
Show the message or value in the output.
Line 41 return
Leave this function now.
Line 42 if state["energy"] == 0:
Run the indented block only if this check is true. The brackets look up a dictionary key or a position that starts at zero.
Line 43 print("Pip has no energy left to move.")
Show the message or value in the output.
Line 44 return
Leave this function now.
Line 45 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Line 46 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 47 print("Pip arrives at the", destination)
Show the message or value in the output.
Line 49 def take(state, item):
Define take, a reusable piece of the program. Its input names are state, item. The indented body runs when something calls it.
Line 50 part = ROOM_PARTS.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. The brackets look up a dictionary key or a position that starts at zero.
Line 51 if part is None or item != part.lower():
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. Return a lowercase copy so capital letters do not change a command.
Lines 52–65
Line 52 print("That part is not here.")
Show the message or value in the output.
Line 53 elif 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. The brackets look up a dictionary key or a position that starts at zero.
Line 54 print("You already collected that part.")
Show the message or value in the output.
Line 55 else:
Take this branch if the earlier checks for this decision were false.
Line 56 state["parts"].append(part)
Add the value to the end without replacing the earlier entries.
Line 57 print("Collected:", part)
Show the message or value in the output.
Line 59 def open_panel(state, code):
Define open_panel, a reusable piece of the program. Its input names are state, code. The indented body runs when something calls it.
Line 60 if state["room"] != "Beacon":
Run the indented block only if this check is true. The brackets look up a dictionary key or a position that starts at zero.
Line 61 print("The panel is at the Beacon.")
Show the message or value in the output.
Line 62 elif code != PANEL_CODE:
Run the indented block only if this check is true.
Line 63 print("Wrong code. Check the Workshop clue.")
Show the message or value in the output.
Line 64 else:
Take this branch if the earlier checks for this decision were false.
Line 65 state["panel_open"] = True
Work out the value on the right, then store it in state["panel_open"].
Lines 66–84
Line 66 print("Beacon panel open.")
Show the message or value in the output.
Line 68 def repair(state):
Define repair, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 69 if state["room"] != "Beacon":
Run the indented block only if this check is true. The brackets look up a dictionary key or a position that starts at zero.
Line 70 print("Find the Beacon first.")
Show the message or value in the output.
Line 71 elif not all(part in state["parts"] for part in ROOM_PARTS.values()):
Run the indented block only if this check is true. The word not reverses which result counts as true. Check that every result is true. The expression supplies matching values one at a time to the operation using it.
Line 72 print("You still need the Coil and Cell.")
Show the message or value in the output.
Line 73 elif not state["panel_open"]:
Run the indented block only if this check is true. The word not reverses which result counts as true. The brackets look up a dictionary key or a position that starts at zero.
Line 74 print("Open the panel before fitting the parts.")
Show the message or value in the output.
Line 75 else:
Take this branch if the earlier checks for this decision were false.
Line 76 state["rescued"] = True
Work out the value on the right, then store it in state["rescued"].
Line 77 print("Signal restored. Rescue is on its way!")
Show the message or value in the output.
Line 80 def power_failed(state):
Define power_failed, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Lines 81–84 can_finish = ( state["room"] == "Beacon" and all(part in state["parts"] for part in ROOM_PARTS.values()) )
Work out the value on the right, then store it in can_finish. With and, every check must be true. The brackets look up a dictionary key or a position that starts at zero. Check that every result is true.
Lines 85–106
Line 85 return state["energy"] == 0 and not can_finish
Leave this function now and hand the result back to the line that called it. With and, every check must be true. The brackets look up a dictionary key or a position that starts at zero. The word not reverses which result counts as true.
Line 87 def show_map(state, argument):
Define show_map, a reusable piece of the program. Its input names are state, argument. The indented body runs when something calls it.
Line 88 for room, info in WORLD.items():
Take one item at a time and give it to room, info, then run the indented block. Make the dictionary's key and value pairs available to loop over.
Line 89 doors = ", ".join(f"{way} to {target}" for way, target in info["exits"].items())
Work out the value on the right, then store it in doors. 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 90 print(f"{room}: {doors}")
Show the message or value in the output. Python fills the braces with values before it uses the text.
Line 93 def show_help(state, argument):
Define show_help, a reusable piece of the program. Its input names are state, argument. The indented body runs when something calls it.
Line 94 print("Try: look, status, map, go north, take coil, panel 42, repair, quit.")
Show the message or value in the output.
Line 97 def command_look(state, argument):
Define command_look, a reusable piece of the program. Its input names are state, argument. The indented body runs when something calls it.
Line 98 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 101 def command_status(state, argument):
Define command_status, a reusable piece of the program. Its input names are state, argument. The indented body runs when something calls it.
Line 102 show_status(state)
Run show_status with the supplied inputs and come back here when it returns.
Line 105 def command_repair(state, argument):
Define command_repair, a reusable piece of the program. Its input names are state, argument. The indented body runs when something calls it.
Line 106 repair(state)
Run repair with the supplied inputs and come back here when it returns.
Lines 109–138
Lines 109–118 ACTIONS = { "look": command_look, "status": command_status, "go": move, "take": take, "panel": open_panel, "repair": command_repair, "map": show_map, "help": show_help, }
Work out the value on the right, then store it in ACTIONS. Each colon pairs a key with its value.
Line 120 def new_state():
Define new_state, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Lines 121–127 return { "room": "Habitat", "energy": 8, "parts": [], "panel_open": False, "rescued": False, }
Leave this function now and hand the result back to the line that called it. Each colon pairs a key with its value.
Line 129 def play(state):
Define play, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 130 print("Moonbase Rescue")
Show the message or value in the output.
Line 131 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 132 show_help(state, "")
Run show_help with the supplied inputs and come back here when it returns.
Line 133 while not state["rescued"]:
Check not state["rescued"] before each pass. Repeat the indented work while it is true.
Line 134 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 135 raw = input("Pip > ")
Work out the value on the right, then store it in raw. Show the prompt and wait for the player to type a line. The answer starts as text.
Line 136 except EOFError:
Run this part only when the try block raises EOFError.
Line 137 print("Radio closed.")
Show the message or value in the output.
Line 138 break
Leave the nearest loop immediately and continue after it.
Lines 139–153
Line 139 command, argument = read_command(raw)
Give each returned value to the matching name, from left to right. Run read_command with the supplied inputs and come back here when it returns.
Line 140 if command == "quit":
Run the indented block only if this check is true.
Line 141 print("Mission paused.")
Show the message or value in the output.
Line 142 break
Leave the nearest loop immediately and continue after it.
Line 144 action = ACTIONS.get(command)
Work out the value on the right, then store it in action. Look up a key. Use the given fallback, or None, if the key is missing.
Line 145 if action 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 146 print("Unknown command. Try help.")
Show the message or value in the output.
Line 147 else:
Take this branch if the earlier checks for this decision were false.
Line 148 action(state, argument)
Run action with the supplied inputs and come back here when it returns.
Line 150 if not state["rescued"] and power_failed(state):
Run the indented block only if this check is true. With and, every check must be true. The word not reverses which result counts as true. The brackets look up a dictionary key or a position that starts at zero.
Line 151 print("Battery empty. Mission stopped.")
Show the message or value in the output.
Line 152 break
Leave the nearest loop immediately and continue after it.
Line 153 return state
Leave this function now and hand the result back to the line that called it.
Lines 155–156
Line 155 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 156 play(new_state())
Run play with the supplied inputs and come back here when it returns. Run new_state with the supplied inputs and come back here when it returns.

Test the mission

  • Test the win with this route: go north, take coil, go south, go east, take cell, go north, panel 42, repair.
  • Test the bad code and watch the repair remain locked. Start again and check the cargo resets.

If something goes wrong

The new game starts with old cargo.
Call new_state for each new round. Keep the empty list in the function’s dictionary literal.

Mission extension

Write a three-row mission report. For each test, note what you tried, what you expected, and exactly what the program printed.