Python 30 · Ship the Moonbase Rescue mission checkpoint

Python lesson 30 of 50 · Intermediate · About 33 minutes

Finish this stage of Moonbase Rescue with helpful radio commands and a test of the full winning route.

Pip presses a control in front of three mint-green mission screens.

Mission Combine data-driven movement, saved progress, a seed, status and an end-to-end rescue test in one checkpoint.

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_30.py in a project folder and run python moonbase_30.py from that folder. Use python3 on systems where that is the Python 3 command. Use Python 3.10 or newer.

Playable mission. Use help, status, and the map to guide Pip.. → Resume. Save, reopen and restore a valid checkpoint.. → Verify. Run the known winning route in the test suite..
Playable mission → Resume → Verify

Understand the Python in this lesson

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

Give a new radio command a complete path

A command needs a recognised word in parse_command and a branch that does its work. The parser returns ("status", ""). The loop calls progress_report(state), prints its result and uses continue to reach the next prompt. The help branch follows the same pattern and calls help_message().

Work out what is still missing

REQUIRED.difference(state["parts"]) makes a set of the required parts that are absent from Pip’s cargo. sorted(...) orders them so the report reads consistently. ", ".join(...) joins them into text. When the set is empty, the joined string is "", so or "nothing" supplies a useful word.

Store a winning route as a tuple

The tuple in test_full_rescue lists seven commands in a fixed order. for command in (...): gives the loop one string at a time. On each turn, verb, argument = parse_command(command) splits the command into its action and input. apply(state, verb, argument) runs the action against the same mission dictionary.

Check the outcome after the whole route

self.assertTrue(state["rescued"]) sits after the loop. It checks that the final repair actually switched the flag on. The test covers several functions working together. This kind of check is called an integration test. The smaller tests from the previous lesson still make it easier to pinpoint a specific rule.

Walk through the real radio as well

Run the game normally and try status, a move, a pickup, save and load. The integration test calls the parser and game actions, while this manual run also checks the input loop, the radio messages and the local file. Notice how the same game rules support both ways of checking the program.

How the pieces fit The checkpoint now has a map, a command parser, action functions, a save file and a test suite. Follow one command from input through the parser to an action or a radio handler. Then see how the full rescue test follows the same parser-to-action path using a stored list of instructions.

Follow one run, step by step
  1. Enter status in a new mission.
    Still needed: Cell, Coil. Why The inventory is empty and sorted puts the part names in alphabetical order.
  2. Enter east, then take, then status.
    Still needed: Cell. Why Pip has the Coil from Workshop, so only Cell is missing.
  3. Enter west, north, take, then status.
    Still needed: nothing. Why Both parts are now in the inventory, so the joined missing-parts string is empty.
  4. Enter east, then repair.
    Beacon restored! Pip has sent the rescue signal. Why The move leads to Beacon, and the repair rule finds both parts.

Predict before you run What happens if the last repair command is removed from test_full_rescue?

Reveal the explanation

Pip can arrive at Beacon carrying both parts, but the rescued flag is still False. The final assertion fails because the repair action is what turns that flag on.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills integration testing, status messages, command help, release checklist.

1. Tell the player what is possible

Add a help message that lists the available verbs. Adding the parser entry alone does not make a command work. Add a handler for help and use it at the start of the mission too. The status command turns the missing-parts rule into a short report, which helps the player know where to search next.

def help_message():
    return "Commands: look, north/south/east/west, take, repair, save, load, help, quit."

2. Test the same route a real player can use

Create a new test with a seed, then pass seven commands through the parser and game action function. The test covers movement, collection, returning along the world map and sending the signal. It checks that the rescued flag is True. If you change any exit or starting energy later, this test will tell you whether the known path still works.

def test_full_rescue(self):
        state = new_mission(17)
        for command in ("east", "take", "west", "north", "take", "east", "repair"):
            verb, argument = parse_command(command)
            apply(state, verb, argument)
        self.assertTrue(state["rescued"])

3. Run your release checks

First run python moonbase.py --test and check that all six tests pass. Then start the normal game, type status, collect a part, save, and quit. Resume in a new run, load, and complete the path. Finish by noting the seed, the route and the expected win message. Keep a copy of this checkpoint before moving on to the next module.

if verb == "status":
            print(progress_report(state))
            continue
        print(apply(state, verb, argument))

4. Check the two ways to play

Complete one fresh run all the way through. Then split the same route across two launches, saving after the Coil and resuming before the Cell. The result should be the same. Keep the final test report and one working copy of the Python file for the next module.

Complete Python checkpoint · moonbase_30.py
import argparse
import random
import json
from pathlib import Path
import sys
import unittest


WORLD = {
    "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None},
    "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"},
    "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"},
    "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None},
}
REQUIRED = {"Coil", "Cell"}
SAVE_FILE = Path("moonbase-save.json")


def new_mission(seed=0):
    generator = random.Random(seed)
    charge = generator.choice([7, 8, 9])
    return {"room": "Habitat", "energy": charge, "parts": [], "rescued": False}


def can_repair(room, parts):
    return room == "Beacon" and REQUIRED.issubset(parts)


def describe(state):
    room, energy, cargo, _ = mission_snapshot(state)
    exits = ", ".join(WORLD[room]["exits"])
    parts = ", ".join(cargo) or "none"
    return f"{room} | energy {energy} | parts {parts} | exits {exits}"


def collect(state):
    item = WORLD[state["room"]]["part"]
    if item is None:
        return "There is no repair part here."
    if item in state["parts"]:
        return f"You already have the {item}."
    state["parts"].append(item)
    return f"Collected the {item}."


def repair(state):
    if can_repair(state["room"], state["parts"]):
        state["rescued"] = True
        return "Beacon restored! Pip has sent the rescue signal."
    return "Bring the Coil and the Cell to the Beacon."


def move(state, direction):
    destination = WORLD[state["room"]]["exits"].get(direction)
    if destination is None:
        return "That route is blocked."
    if state["energy"] == 0:
        return "Pip is out of energy."
    state["room"] = destination
    state["energy"] -= 1
    return f"Moved to {destination}."


def parse_command(text):
    words = text.lower().split()
    if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
        return "go", words[0]
    if len(words) == 2 and words[0] == "go":
        return "go", words[1]
    if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save", "load", "help", "status"}:
        return words[0], ""
    return "", ""


def save_game(state):
    temporary = SAVE_FILE.with_suffix(".tmp")
    try:
        temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
        temporary.replace(SAVE_FILE)
    except OSError:
        return "Could not save progress. Check that this folder is writable."
    return "Progress saved to moonbase-save.json."


def validate_save(data):
    if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}:
        raise ValueError("expected four state fields")
    if type(data["room"]) is not str or data["room"] not in WORLD:
        raise ValueError("unknown room")
    if type(data["energy"]) is not int or not 0 <= data["energy"] <= 9:
        raise ValueError("bad energy")
    parts = data["parts"]
    if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in parts):
        raise ValueError("unknown part")
    if len(parts) != len(set(parts)):
        raise ValueError("duplicate part")
    if type(data["rescued"]) is not bool:
        raise ValueError("bad rescue flag")
    if data["rescued"] and not can_repair(data["room"], parts):
        raise ValueError("inconsistent rescue")
    return data


def load_game(current):
    try:
        data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
        return validate_save(data), "Saved progress loaded."
    except FileNotFoundError:
        return current, "No save yet; current progress kept."
    except (UnicodeError, json.JSONDecodeError):
        return current, "Save is unreadable; current progress kept."
    except ValueError:
        return current, "Save has invalid data; current progress kept."
    except OSError:
        return current, "Could not open save; current progress kept."


def help_message():
    return "Commands: look, north/south/east/west, take, repair, save, load, help, quit."


def progress_report(state):
    missing = ", ".join(sorted(REQUIRED.difference(state["parts"]))) or "nothing"
    return f"Still needed: {missing}."


def mission_snapshot(state):
    return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]


def apply(state, verb, argument):
    if verb == "look":
        return describe(state)
    if verb == "go":
        return move(state, argument)
    if verb == "take":
        return collect(state)
    if verb == "repair":
        return repair(state)
    return "Unknown command."


def run(seed=0):
    state = new_mission(seed)
    print("Moonbase Rescue | Pip on duty")
    print(f"Mission seed: {seed}")
    print(describe(state))
    print(help_message())
    while not state["rescued"]:
        try:
            raw = input("Pip> ")
        except EOFError:
            print("Radio closed.")
            break
        verb, argument = parse_command(raw)
        if verb == "quit":
            print("Pip is on standby.")
            break
        if verb == "save":
            print(save_game(state))
            continue
        if verb == "load":
            state, message = load_game(state)
            print(message)
            continue
        if verb == "help":
            print(help_message())
            continue
        if verb == "status":
            print(progress_report(state))
            continue
        print(apply(state, verb, argument))


class MissionTests(unittest.TestCase):
    def test_failed_move_costs_nothing(self):
        state = new_mission(17)
        energy = state["energy"]
        self.assertEqual(move(state, "west"), "That route is blocked.")
        self.assertEqual(state["energy"], energy)

    def test_part_cannot_be_taken_twice(self):
        state = new_mission(17)
        move(state, "east")
        collect(state)
        collect(state)
        self.assertEqual(state["parts"], ["Coil"])

    def test_repair_needs_both_parts(self):
        self.assertFalse(can_repair("Beacon", ["Coil"]))
        self.assertTrue(can_repair("Beacon", ["Coil", "Cell"]))

    def test_invalid_save_rejects_boolean_energy(self):
        state = new_mission(17)
        state["energy"] = True
        with self.assertRaises(ValueError):
            validate_save(state)

    def test_seed_repeats(self):
        self.assertEqual(new_mission(17), new_mission(17))


    def test_full_rescue(self):
        state = new_mission(17)
        for command in ("east", "take", "west", "north", "take", "east", "repair"):
            verb, argument = parse_command(command)
            apply(state, verb, argument)
        self.assertTrue(state["rescued"])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Moonbase Rescue")
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--test", action="store_true")
    options = parser.parse_args()
    if options.test:
        suite = unittest.defaultTestLoader.loadTestsFromTestCase(MissionTests)
        result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite)
        raise SystemExit(0 if result.wasSuccessful() else 1)
    run(options.seed)

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 import argparse
Bring in argparse. Its module name gives you access to the tools it contains.
Line 2 import random
Bring in random. Its module name gives you access to the tools it contains.
Line 3 import json
Bring in json. Its module name gives you access to the tools it contains.
Line 4 from pathlib import Path
Bring Path into this file from pathlib. These names can now be used directly.
Line 5 import sys
Bring in sys. Its module name gives you access to the tools it contains.
Line 6 import unittest
Bring in unittest. Its module name gives you access to the tools it contains.
Lines 9–14 WORLD = { "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None}, "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"}, "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"}, "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 15 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 16 SAVE_FILE = Path("moonbase-save.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 19 def new_mission(seed=0):
Define new_mission, a reusable piece of the program. Its input names are seed. The indented body runs when something calls it.
Line 20 generator = random.Random(seed)
Work out the value on the right, then store it in generator. Make an independent random generator. Reusing its seed repeats the sequence.
Line 21 charge = generator.choice([7, 8, 9])
Work out the value on the right, then store it in charge. Pick one entry from the sequence using this random generator.
Line 22 return {"room": "Habitat", "energy": charge, "parts": [], "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.
Lines 25–41
Line 25 def can_repair(room, parts):
Define can_repair, a reusable piece of the program. Its input names are room, parts. The indented body runs when something calls it.
Line 26 return room == "Beacon" and REQUIRED.issubset(parts)
Leave this function now and hand the result back to the line that called it. With and, every check must be true. Check whether every item in this set appears in the other collection.
Line 29 def describe(state):
Define describe, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 30 room, energy, cargo, _ = mission_snapshot(state)
Give each returned value to the matching name, from left to right. Run mission_snapshot with the supplied inputs and come back here when it returns.
Line 31 exits = ", ".join(WORLD[room]["exits"])
Work out the value on the right, then store it in exits. 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 32 parts = ", ".join(cargo) 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 33 return f"{room} | energy {energy} | parts {parts} | exits {exits}"
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 36 def collect(state):
Define collect, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 37 item = WORLD[state["room"]]["part"]
Work out the value on the right, then store it in item. The brackets look up a dictionary key or a position that starts at zero.
Line 38 if item 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 39 return "There is no repair part here."
Leave this function now and hand the result back to the line that called it.
Line 40 if item 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 41 return f"You already have the {item}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Lines 42–58
Line 42 state["parts"].append(item)
Add the value to the end without replacing the earlier entries.
Line 43 return f"Collected the {item}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 46 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 47 if can_repair(state["room"], state["parts"]):
Run the indented block only if this check is true. Run can_repair with the supplied inputs and come back here when it returns. The brackets look up a dictionary key or a position that starts at zero.
Line 48 state["rescued"] = True
Work out the value on the right, then store it in state["rescued"].
Line 49 return "Beacon restored! Pip has sent the rescue signal."
Leave this function now and hand the result back to the line that called it.
Line 50 return "Bring the Coil and the Cell to the Beacon."
Leave this function now and hand the result back to the line that called it.
Line 53 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 54 destination = WORLD[state["room"]]["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 55 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 56 return "That route is blocked."
Leave this function now and hand the result back to the line that called it.
Line 57 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 58 return "Pip is out of energy."
Leave this function now and hand the result back to the line that called it.
Lines 59–75
Line 59 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 60 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Line 61 return f"Moved to {destination}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 64 def parse_command(text):
Define parse_command, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 65 words = text.lower().split()
Work out the value on the right, then store it in words. Return a lowercase copy so capital letters do not change a command. Separate the string into a list of pieces.
Line 66 if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Line 67 return "go", words[0]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 68 if len(words) == 2 and words[0] == "go":
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. The brackets look up a dictionary key or a position that starts at zero.
Line 69 return "go", words[1]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 70 if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save", "load", "help", "status"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Line 71 return words[0], ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 72 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 75 def save_game(state):
Define save_game, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Lines 76–90
Line 76 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 77 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 78 temporary.write_text(json.dumps(state, indent=2) + "\n", 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 79 temporary.replace(SAVE_FILE)
Move the temporary file into the final save location.
Line 80 except OSError:
Run this part only when the try block raises OSError.
Line 81 return "Could not save progress. Check that this folder is writable."
Leave this function now and hand the result back to the line that called it.
Line 82 return "Progress saved to moonbase-save.json."
Leave this function now and hand the result back to the line that called it.
Line 85 def validate_save(data):
Define validate_save, a reusable piece of the program. Its input names are data. The indented body runs when something calls it.
Line 86 if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}:
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 87 raise ValueError("expected four state fields")
Stop this path and report ValueError("expected four state fields") to whoever called this code.
Line 88 if type(data["room"]) is not str or data["room"] not in WORLD:
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 89 raise ValueError("unknown room")
Stop this path and report ValueError("unknown room") to whoever called this code.
Line 90 if type(data["energy"]) is not int or not 0 <= data["energy"] <= 9:
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.
Lines 91–105
Line 91 raise ValueError("bad energy")
Stop this path and report ValueError("bad energy") to whoever called this code.
Line 92 parts = data["parts"]
Work out the value on the right, then store it in parts. The brackets look up a dictionary key or a position that starts at zero.
Line 93 if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in 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. Find the exact type of this value.
Line 94 raise ValueError("unknown part")
Stop this path and report ValueError("unknown part") to whoever called this code.
Line 95 if len(parts) != len(set(parts)):
Run the indented block only if this check is true. Count the characters or items. Collect distinct values, with no duplicate entries.
Line 96 raise ValueError("duplicate part")
Stop this path and report ValueError("duplicate part") to whoever called this code.
Line 97 if type(data["rescued"]) is not bool:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value. The brackets look up a dictionary key or a position that starts at zero.
Line 98 raise ValueError("bad rescue flag")
Stop this path and report ValueError("bad rescue flag") to whoever called this code.
Line 99 if data["rescued"] and not can_repair(data["room"], parts):
Run the indented block only if this check is true. 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 100 raise ValueError("inconsistent rescue")
Stop this path and report ValueError("inconsistent rescue") to whoever called this code.
Line 101 return data
Leave this function now and hand the result back to the line that called it.
Line 104 def load_game(current):
Define load_game, a reusable piece of the program. Its input names are current. The indented body runs when something calls it.
Line 105 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Lines 106–122
Line 106 data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
Work out the value on the right, then store it in data. Read JSON text or bytes and turn it back into Python data. Read a file and decode its contents into text.
Line 107 return validate_save(data), "Saved progress loaded."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run validate_save with the supplied inputs and come back here when it returns.
Line 108 except FileNotFoundError:
Run this part only when the try block raises FileNotFoundError.
Line 109 return current, "No save yet; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 110 except (UnicodeError, json.JSONDecodeError):
Run this part only when the try block raises (UnicodeError, json.JSONDecodeError).
Line 111 return current, "Save is unreadable; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 112 except ValueError:
Run this part only when the try block raises ValueError.
Line 113 return current, "Save has invalid data; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 114 except OSError:
Run this part only when the try block raises OSError.
Line 115 return current, "Could not open save; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 118 def help_message():
Define help_message, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 119 return "Commands: look, north/south/east/west, take, repair, save, load, help, quit."
Leave this function now and hand the result back to the line that called it.
Line 122 def progress_report(state):
Define progress_report, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Lines 123–139
Line 123 missing = ", ".join(sorted(REQUIRED.difference(state["parts"]))) or "nothing"
Work out the value on the right, then store it in missing. With or, the first true result can settle the check. Put strings together with the text before .join separating them. Build a new list with entries in sorted order.
Line 124 return f"Still needed: {missing}."
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 127 def mission_snapshot(state):
Define mission_snapshot, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 128 return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero. Collect ordered items in a tuple, whose entries cannot be reassigned.
Line 131 def apply(state, verb, argument):
Define apply, a reusable piece of the program. Its input names are state, verb, argument. The indented body runs when something calls it.
Line 132 if verb == "look":
Run the indented block only if this check is true.
Line 133 return describe(state)
Leave this function now and hand the result back to the line that called it. Run describe with the supplied inputs and come back here when it returns.
Line 134 if verb == "go":
Run the indented block only if this check is true.
Line 135 return move(state, argument)
Leave this function now and hand the result back to the line that called it. Run move with the supplied inputs and come back here when it returns.
Line 136 if verb == "take":
Run the indented block only if this check is true.
Line 137 return collect(state)
Leave this function now and hand the result back to the line that called it. Run collect with the supplied inputs and come back here when it returns.
Line 138 if verb == "repair":
Run the indented block only if this check is true.
Line 139 return repair(state)
Leave this function now and hand the result back to the line that called it. Run repair with the supplied inputs and come back here when it returns.
Lines 140–154
Line 140 return "Unknown command."
Leave this function now and hand the result back to the line that called it.
Line 143 def run(seed=0):
Define run, a reusable piece of the program. Its input names are seed. The indented body runs when something calls it.
Line 144 state = new_mission(seed)
Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
Line 145 print("Moonbase Rescue | Pip on duty")
Show the message or value in the output.
Line 146 print(f"Mission seed: {seed}")
Show the message or value in the output. Python fills the braces with values before it uses the text.
Line 147 print(describe(state))
Show the message or value in the output. Run describe with the supplied inputs and come back here when it returns.
Line 148 print(help_message())
Show the message or value in the output. Run help_message with the supplied inputs and come back here when it returns.
Line 149 while not state["rescued"]:
Check not state["rescued"] before each pass. Repeat the indented work while it is true.
Line 150 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 151 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 152 except EOFError:
Run this part only when the try block raises EOFError.
Line 153 print("Radio closed.")
Show the message or value in the output.
Line 154 break
Leave the nearest loop immediately and continue after it.
Lines 155–167
Line 155 verb, argument = parse_command(raw)
Give each returned value to the matching name, from left to right. Run parse_command with the supplied inputs and come back here when it returns.
Line 156 if verb == "quit":
Run the indented block only if this check is true.
Line 157 print("Pip is on standby.")
Show the message or value in the output.
Line 158 break
Leave the nearest loop immediately and continue after it.
Line 159 if verb == "save":
Run the indented block only if this check is true.
Line 160 print(save_game(state))
Show the message or value in the output. Run save_game with the supplied inputs and come back here when it returns.
Line 161 continue
Skip the rest of this pass and start the next loop check.
Line 162 if verb == "load":
Run the indented block only if this check is true.
Line 163 state, message = load_game(state)
Give each returned value to the matching name, from left to right. Run load_game with the supplied inputs and come back here when it returns.
Line 164 print(message)
Show the message or value in the output.
Line 165 continue
Skip the rest of this pass and start the next loop check.
Line 166 if verb == "help":
Run the indented block only if this check is true.
Line 167 print(help_message())
Show the message or value in the output. Run help_message with the supplied inputs and come back here when it returns.
Lines 168–183
Line 168 continue
Skip the rest of this pass and start the next loop check.
Line 169 if verb == "status":
Run the indented block only if this check is true.
Line 170 print(progress_report(state))
Show the message or value in the output. Run progress_report with the supplied inputs and come back here when it returns.
Line 171 continue
Skip the rest of this pass and start the next loop check.
Line 172 print(apply(state, verb, argument))
Show the message or value in the output. Run apply with the supplied inputs and come back here when it returns.
Line 175 class MissionTests(unittest.TestCase):
Define MissionTests, a class that groups related data or behaviour. It starts with the behaviour from unittest.TestCase.
Line 176 def test_failed_move_costs_nothing(self):
Define test_failed_move_costs_nothing, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Line 177 state = new_mission(17)
Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
Line 178 energy = state["energy"]
Work out the value on the right, then store it in energy. The brackets look up a dictionary key or a position that starts at zero.
Line 179 self.assertEqual(move(state, "west"), "That route is blocked.")
Fail the test if the actual and expected values differ. Run move with the supplied inputs and come back here when it returns.
Line 180 self.assertEqual(state["energy"], energy)
Fail the test if the actual and expected values differ. The brackets look up a dictionary key or a position that starts at zero.
Line 182 def test_part_cannot_be_taken_twice(self):
Define test_part_cannot_be_taken_twice, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Line 183 state = new_mission(17)
Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
Lines 184–199
Line 184 move(state, "east")
Run move with the supplied inputs and come back here when it returns.
Line 185 collect(state)
Run collect with the supplied inputs and come back here when it returns.
Line 186 collect(state)
Run collect with the supplied inputs and come back here when it returns.
Line 187 self.assertEqual(state["parts"], ["Coil"])
Fail the test if the actual and expected values differ. The brackets look up a dictionary key or a position that starts at zero.
Line 189 def test_repair_needs_both_parts(self):
Define test_repair_needs_both_parts, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Line 190 self.assertFalse(can_repair("Beacon", ["Coil"]))
Fail the test if this value behaves as true. Run can_repair with the supplied inputs and come back here when it returns.
Line 191 self.assertTrue(can_repair("Beacon", ["Coil", "Cell"]))
Fail the test if this value behaves as false. Run can_repair with the supplied inputs and come back here when it returns.
Line 193 def test_invalid_save_rejects_boolean_energy(self):
Define test_invalid_save_rejects_boolean_energy, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Line 194 state = new_mission(17)
Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
Line 195 state["energy"] = True
Work out the value on the right, then store it in state["energy"].
Line 196 with self.assertRaises(ValueError):
Check that the indented operation raises the expected error. The test fails if a different error appears or the indented operation succeeds.
Line 197 validate_save(state)
Run validate_save with the supplied inputs and come back here when it returns.
Line 199 def test_seed_repeats(self):
Define test_seed_repeats, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Lines 200–216
Line 200 self.assertEqual(new_mission(17), new_mission(17))
Fail the test if the actual and expected values differ. Run new_mission with the supplied inputs and come back here when it returns.
Line 203 def test_full_rescue(self):
Define test_full_rescue, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Line 204 state = new_mission(17)
Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
Line 205 for command in ("east", "take", "west", "north", "take", "east", "repair"):
Take one item at a time and give it to command, then run the indented block. Commas group these values into an ordered tuple.
Line 206 verb, argument = parse_command(command)
Give each returned value to the matching name, from left to right. Run parse_command with the supplied inputs and come back here when it returns.
Line 207 apply(state, verb, argument)
Run apply with the supplied inputs and come back here when it returns.
Line 208 self.assertTrue(state["rescued"])
Fail the test if this value behaves as false. The brackets look up a dictionary key or a position that starts at zero.
Line 211 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 212 parser = argparse.ArgumentParser(description="Moonbase Rescue")
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 213 parser.add_argument("--seed", type=int, default=0)
Register an option that someone can use when starting the program.
Line 214 parser.add_argument("--test", action="store_true")
Register an option that someone can use when starting the program.
Line 215 options = parser.parse_args()
Work out the value on the right, then store it in options. Read the launch options and put the chosen values into an object.
Line 216 if options.test:
Run the indented block only if this check is true.
Lines 217–220
Line 217 suite = unittest.defaultTestLoader.loadTestsFromTestCase(MissionTests)
Work out the value on the right, then store it in suite. Collect the test methods from this test class.
Line 218 result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite)
Work out the value on the right, then store it in result. Create a runner that reports test results as text. Run the selected operation or collection of tests.
Line 219 raise SystemExit(0 if result.wasSuccessful() else 1)
Stop this path and report SystemExit(0 if result.wasSuccessful() else 1) to whoever called this code.
Line 220 run(options.seed)
Run run with the supplied inputs and come back here when it returns.

Test the mission

  • From Habitat, enter east, take, west, north, take, east, repair. Confirm the Beacon is restored.
  • Replay using go east and spaces or uppercase. Compare the result.
  • Run --test to confirm all six regression checks still pass.

If something goes wrong

The full route test fails after changing the map.
Trace the first unexpected room, confirm the exits in WORLD, and update the test route only if the intended layout changed.

Mission extension

Ask someone else to complete a fresh mission with your help command. Improve one message using their feedback.