Python 40 · Refactor and release the moonbase engine

Python lesson 40 of 50 · Advanced · About 55 minutes

Prepare Pip’s mission for bigger projects by separating inspection commands from terminal input and output, while keeping the tested game rules steady.

Pip follows a trail of orange lights past deep craters towards a radio tower.

Mission Refactor the interactive wrapper, test the complete rescue and explain what each part of the engine owns.

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

Describe. One view function prepares information for the player.. → Apply. The engine continues to own the game rules.. → Verify. Rerun tests, replay and one live rescue..
Describe → Apply → Verify

Understand the Python in this lesson

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

Store ways to build a view

views is a dictionary from command strings to small functions. lambda: describe(state) makes a function with no parameters. Its expression runs when called, so preparing this dictionary does not build every message. Its function can read the state and history values in the surrounding helper.

Look up a function, then call it

In views[command](), the square brackets select the function and the parentheses run it. For example, the map entry executes render_map(state). A hint has a destination after its name, so the helper checks its prefix separately and gives back a route message.

Use None as the signal to call the engine

If view_command recognises no view, it returns None. if view is not None: prints any view text and skips the action block. A normal command such as go east falls through to step, where rules can change the state and add to history.

Supply the reader and writer

def play(read=input, write=print): uses callable defaults. The names input and print are passed as functions, so no parentheses are used there. Inside, read("> ") and write(message) call them when needed. A test can supply its own command reader and a writer that stores each message.

How the pieces fit The completed engine has four jobs you can point to. State remembers progress, step enforces rules, view_command prepares text, and play controls the conversation. The same tests still apply after the jobs are separated.

Follow one run, step by step
  1. Type map at the start.
    The map appears with Pip in Habitat. Why The table selects a view. The loop writes it and never sends map to step.
  2. Type go east.
    Arrived at Workshop. Why view_command returns None, so the engine moves Pip, charges the cost and logs the action.
  3. Type history.
    History: go east Why The history function is called only for that view. Map and history themselves do not enter the log.
  4. Type quit.
    Mission ended. Why The loop breaks before calling either a view or the engine.

Predict before you run If you write "status": describe(state) in the table and leave views[command]() alone, what happens on status?

Reveal the explanation

The new table stores the text returned by describe immediately. The final parentheses then try to call that text as a function and raise a TypeError. Keep the small lambda so the stored entry is callable.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills refactoring, dependency injection, view commands, release checklist.

1. Give inspections their own function

The complete game can now display a map, status, a command history, a route hint and a JSON log. Instead of searching a long input loop for every inspection, view_command groups them together. The table stores functions that build the relevant text when called, so asking for status does not also build a map or a log. For a normal game action it returns None. The terminal can use that answer to decide whether to display text immediately or send the command to the game engine. Trace map and take to see the difference.

if command in views:
        return views[command]()

2. Supply how the terminal runs

The signature of the refactored play function takes a reading function and a writing function. Defaults use the usual keyboard and screen functions, so launching the program works in the familiar way. For a test or a future game window, you can supply different functions that deliver predefined commands and store the resulting messages. This is a practical example of dependency injection: provide the behaviour the game needs instead of making it search for a particular terminal on its own. The game logic still receives State and commands exactly as before.

def play(read=input, write=print):

3. Run the release checks

Start by running --test to see that the rules from lesson 39 still pass. Run --demo to check the known winning rescue. Then enter a few inspection commands in live play and confirm that map, history and hint work without draining the battery. Finally complete the mission yourself and compare it with the demo. Save a clean copy before experimenting. You now have a clear core to carry into the expert stage: World data describes the base, State records progress, step applies actions, the views explain the situation, and play runs the conversation.

view = view_command(state, history, command)
        if view is not None:
            write(view)
            continue
Complete Python checkpoint · moonbase_40.py
from dataclasses import dataclass, replace
from collections import deque
import json
import sys
import cProfile
import pstats
from functools import lru_cache
import unittest

WORLD = {
    "Habitat": {"east": "Workshop", "south": "Greenhouse"},
    "Workshop": {"west": "Habitat", "south": "Beacon"},
    "Greenhouse": {"north": "Habitat", "east": "Beacon"},
    "Beacon": {"north": "Workshop", "west": "Greenhouse"},
}
PART_AT = {"Workshop": "Coil", "Greenhouse": "Cell"}
REQUIRED = {"Coil", "Cell"}


MAX_ENERGY = 8


@dataclass(frozen=True)
class State:
    room: str = "Habitat"
    parts: tuple = ()
    rescued: bool = False
    energy: int = MAX_ENERGY
    turns: int = 0

def spend(state, **changes):
    return replace(state, energy=state.energy - 1,
                   turns=state.turns + 1, **changes)

def step(state, command):
    if state.rescued:
        return state, "Beacon already online."
    if command == "charge":
        if state.energy == MAX_ENERGY:
            return state, "The battery is already full."
        return replace(state, energy=MAX_ENERGY, turns=state.turns + 1), "Charged to 8."
    if state.energy == 0:
        return state, "Battery empty. Use charge to continue."
    if command.startswith("go "):
        direction = command[3:]
        target = WORLD[state.room].get(direction)
        if target is None:
            return state, "No exit that way."
        return spend(state, room=target), f"Arrived at {target}."
    if command == "take":
        part = PART_AT.get(state.room)
        if part is None:
            return state, "There is no part here."
        if part in state.parts:
            return state, "You already have that part."
        return spend(state, parts=(*state.parts, part)), f"Packed {part}."
    if command == "repair":
        if state.room != "Beacon":
            return state, "Repair at the Beacon."
        if not REQUIRED.issubset(state.parts):
            return state, "Find both the Coil and the Cell."
        return spend(state, rescued=True), "Beacon online!"
    return state, "Unknown command."

def render_map(state):
    rooms = []
    for room, exits in WORLD.items():
        current = " [Pip is here]" if room == state.room else ""
        links = ", ".join(f"{direction} to {end}" for direction, end in exits.items())
        rooms.append(f"{room}{current}: {links}.")
    return "\n".join(rooms)

@lru_cache(maxsize=16)
def route(start, target):
    queue = deque([(start, ())])
    seen = {start}
    while queue:
        room, moves = queue.popleft()
        if room == target:
            return moves
        for direction, neighbour in WORLD[room].items():
            if neighbour not in seen:
                seen.add(neighbour)
                queue.append((neighbour, (*moves, direction)))
    return None

DEMO = ('go east', 'take', 'go west', 'go south', 'take', 'go east', 'repair')


def replay(commands):
    state = State()
    for command in commands:
        state, _ = step(state, command)
    return state


def run_demo():
    copied_log = json.dumps(DEMO)
    print(copied_log)
    state = replay(json.loads(copied_log))
    print(f"Replay: room={state.room}, turns={state.turns}, rescued={state.rescued}.")

def profile_routes():
    route.cache_clear()
    with cProfile.Profile() as profiler:
        for _ in range(40):
            route("Habitat", "Beacon")
    print("Profiled 40 route queries.")
    print(route.cache_info())
    pstats.Stats(profiler).sort_stats("cumulative").print_stats(5)

class MissionTests(unittest.TestCase):
    def test_invalid_move_costs_nothing(self):
        state = State()
        self.assertEqual(step(state, "go north")[0], state)

    def test_part_can_be_collected_once(self):
        state = replay(["go east", "take"])
        self.assertEqual(step(state, "take")[0], state)
        self.assertEqual(state.parts, ("Coil",))

    def test_early_repair_fails(self):
        state = replay(["go east", "go south"])
        self.assertFalse(step(state, "repair")[0].rescued)

    def test_demo_restores_beacon(self):
        state = replay(DEMO)
        self.assertTrue(state.rescued)
        self.assertEqual(state.turns, 7)
        self.assertEqual(state.energy, 1)

    def test_charge_prevents_a_dead_end(self):
        empty = replace(State(), energy=0)
        self.assertEqual(step(empty, "go east")[0], empty)
        self.assertEqual(step(empty, "charge")[0].energy, MAX_ENERGY)

    def test_shortest_route(self):
        self.assertEqual(route("Habitat", "Beacon"), ("east", "south"))

def describe(state):
    pack = ", ".join(state.parts) or "empty"
    restored = "online" if state.rescued else "offline"
    message = f"{state.room} | pack: {pack} | Beacon: {restored}"
    return f"{message} | energy: {state.energy} | turns: {state.turns}"

def normalise(text):
    return " ".join(text.lower().split())

def view_command(state, history, command):
    views = {
        "status": lambda: describe(state),
        "map": lambda: render_map(state),
        "history": lambda: "History: " + (" > ".join(history) or "no moves yet"),
        "log": lambda: json.dumps(history),
    }
    if command in views:
        return views[command]()
    if command.startswith("hint "):
        target = command[5:].title()
        if target not in WORLD:
            return "Unknown destination."
        moves = route(state.room, target)
        if moves == ():
            return "Route: already there"
        return "Route: " + (" then ".join(moves) if moves else "unreachable")
    return None


def play(read=input, write=print):
    state, history = State(), []
    write('Pip ready. Type go, take, repair, charge, status, map, history, hint, log or quit.')
    while True:
        try:
            command = normalise(read("> "))
        except EOFError:
            break
        if command == "quit":
            break
        view = view_command(state, history, command)
        if view is not None:
            write(view)
            continue
        next_state, message = step(state, command)
        if next_state != state:
            history.append(command)
        state = next_state
        write(message)
    write("Mission ended.")

if __name__ == "__main__":
    mode = sys.argv[1] if len(sys.argv) > 1 else ""
    if mode == "--demo":
        run_demo()
    elif mode == "--profile":
        profile_routes()
    elif mode == "--test":
        unittest.main(argv=[sys.argv[0]])
    else:
        play()

Read the complete checkpoint line by line

Use this guide beside the checkpoint. Blank lines separate ideas. Indented lines belong to the instruction above them. Lines with brackets still open can carry on below.

Lines 1–23
Line 1 from dataclasses import dataclass, replace
Bring dataclass, replace into this file from dataclasses. These names can now be used directly.
Line 2 from collections import deque
Bring deque into this file from collections. These names can now be used directly.
Line 3 import json
Bring in json. Its module name gives you access to the tools it contains.
Line 4 import sys
Bring in sys. Its module name gives you access to the tools it contains.
Line 5 import cProfile
Bring in cProfile. Its module name gives you access to the tools it contains.
Line 6 import pstats
Bring in pstats. Its module name gives you access to the tools it contains.
Line 7 from functools import lru_cache
Bring lru_cache into this file from functools. These names can now be used directly.
Line 8 import unittest
Bring in unittest. Its module name gives you access to the tools it contains.
Lines 10–15 WORLD = { "Habitat": {"east": "Workshop", "south": "Greenhouse"}, "Workshop": {"west": "Habitat", "south": "Beacon"}, "Greenhouse": {"north": "Habitat", "east": "Beacon"}, "Beacon": {"north": "Workshop", "west": "Greenhouse"}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 16 PART_AT = {"Workshop": "Coil", "Greenhouse": "Cell"}
Work out the value on the right, then store it in PART_AT. Each colon pairs a key with its value.
Line 17 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 20 MAX_ENERGY = 8
Work out the value on the right, then store it in MAX_ENERGY.
Line 23 @dataclass(frozen=True)
Ask Python to create the usual data-handling methods from the listed fields.
Lines 24–39
Line 24 class State:
Define State, a class that groups related data or behaviour.
Line 25 room: str = "Habitat"
Describe the expected type of room as str and provide its starting value.
Line 26 parts: tuple = ()
Describe the expected type of parts as tuple and provide its starting value. Commas group these values into an ordered tuple.
Line 27 rescued: bool = False
Describe the expected type of rescued as bool and provide its starting value.
Line 28 energy: int = MAX_ENERGY
Describe the expected type of energy as int and provide its starting value.
Line 29 turns: int = 0
Describe the expected type of turns as int and provide its starting value.
Line 31 def spend(state, **changes):
Define spend, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Lines 32–33 return replace(state, energy=state.energy - 1, turns=state.turns + 1, **changes)
Leave this function now and hand the result back to the line that called it. Make a new state with the named changes. The old state stays available.
Line 35 def step(state, command):
Define step, a reusable piece of the program. Its input names are state, command. The indented body runs when something calls it.
Line 36 if state.rescued:
Run the indented block only if this check is true.
Line 37 return state, "Beacon already online."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 38 if command == "charge":
Run the indented block only if this check is true.
Line 39 if state.energy == MAX_ENERGY:
Run the indented block only if this check is true.
Lines 40–52
Line 40 return state, "The battery is already full."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 41 return replace(state, energy=MAX_ENERGY, turns=state.turns + 1), "Charged to 8."
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 42 if state.energy == 0:
Run the indented block only if this check is true.
Line 43 return state, "Battery empty. Use charge to continue."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 44 if command.startswith("go "):
Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Line 45 direction = command[3:]
Work out the value on the right, then store it in direction. The slice copies a portion, stopping before the end index if one is given.
Line 46 target = WORLD[state.room].get(direction)
Work out the value on the right, then store it in target. Look up a key. Use the given fallback, or None, if the key is missing.
Line 47 if target is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 48 return state, "No exit that way."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 49 return spend(state, room=target), f"Arrived at {target}."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run spend with the supplied inputs and come back here when it returns. Python fills the braces with values before it uses the text.
Line 50 if command == "take":
Run the indented block only if this check is true.
Line 51 part = PART_AT.get(state.room)
Work out the value on the right, then store it in part. Look up a key. Use the given fallback, or None, if the key is missing.
Line 52 if part is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Lines 53–66
Line 53 return state, "There is no part here."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 54 if part in state.parts:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 55 return state, "You already have that part."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 56 return spend(state, parts=(*state.parts, part)), f"Packed {part}."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run spend with the supplied inputs and come back here when it returns. Python fills the braces with values before it uses the text.
Line 57 if command == "repair":
Run the indented block only if this check is true.
Line 58 if state.room != "Beacon":
Run the indented block only if this check is true.
Line 59 return state, "Repair at the Beacon."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 60 if not REQUIRED.issubset(state.parts):
Run the indented block only if this check is true. The word not reverses which result counts as true. Check whether every item in this set appears in the other collection.
Line 61 return state, "Find both the Coil and the Cell."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 62 return spend(state, rescued=True), "Beacon online!"
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run spend with the supplied inputs and come back here when it returns.
Line 63 return state, "Unknown command."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 65 def render_map(state):
Define render_map, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 66 rooms = []
Work out the value on the right, then store it in rooms.
Lines 67–80
Line 67 for room, exits in WORLD.items():
Take one item at a time and give it to room, exits, then run the indented block. Make the dictionary's key and value pairs available to loop over.
Line 68 current = " [Pip is here]" if room == state.room else ""
Work out the value on the right, then store it in current. Choose the first value if the condition is true, otherwise choose the value after else.
Line 69 links = ", ".join(f"{direction} to {end}" for direction, end in exits.items())
Work out the value on the right, then store it in links. 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 70 rooms.append(f"{room}{current}: {links}.")
Add the value to the end without replacing the earlier entries. Python fills the braces with values before it uses the text.
Line 71 return "\n".join(rooms)
Leave this function now and hand the result back to the line that called it. Put strings together with the text before .join separating them.
Line 73 @lru_cache(maxsize=16)
Reuse earlier results for matching inputs instead of doing the same work again.
Line 74 def route(start, target):
Define route, a reusable piece of the program. Its input names are start, target. The indented body runs when something calls it.
Line 75 queue = deque([(start, ())])
Work out the value on the right, then store it in queue. Create a queue that can efficiently take items from either end. Commas group these values into an ordered tuple.
Line 76 seen = {start}
Work out the value on the right, then store it in seen.
Line 77 while queue:
Check queue before each pass. Repeat the indented work while it is true.
Line 78 room, moves = queue.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 79 if room == target:
Run the indented block only if this check is true.
Line 80 return moves
Leave this function now and hand the result back to the line that called it.
Lines 81–98
Line 81 for direction, neighbour in WORLD[room].items():
Take one item at a time and give it to direction, neighbour, then run the indented block. Make the dictionary's key and value pairs available to loop over.
Line 82 if neighbour 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 83 seen.add(neighbour)
Add the value to the set. A set keeps at most one copy.
Line 84 queue.append((neighbour, (*moves, direction)))
Add the value to the end without replacing the earlier entries. Commas group these values into an ordered tuple.
Line 85 return None
Leave this function now and hand the result back to the line that called it.
Line 87 DEMO = ('go east', 'take', 'go west', 'go south', 'take', 'go east', 'repair')
Work out the value on the right, then store it in DEMO. Commas group these values into an ordered tuple.
Line 90 def replay(commands):
Define replay, a reusable piece of the program. Its input names are commands. The indented body runs when something calls it.
Line 91 state = State()
Work out the value on the right, then store it in state. Create a mission state using the supplied field values and any defaults.
Line 92 for command in commands:
Take one item at a time and give it to command, then run the indented block.
Line 93 state, _ = step(state, command)
Give each returned value to the matching name, from left to right. Run step with the supplied inputs and come back here when it returns.
Line 94 return state
Leave this function now and hand the result back to the line that called it.
Line 97 def run_demo():
Define run_demo, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 98 copied_log = json.dumps(DEMO)
Work out the value on the right, then store it in copied_log. Turn Python data into JSON text. This step does not write a file.
Lines 99–113
Line 99 print(copied_log)
Show the message or value in the output.
Line 100 state = replay(json.loads(copied_log))
Work out the value on the right, then store it in state. Run replay with the supplied inputs and come back here when it returns. Read JSON text or bytes and turn it back into Python data.
Line 101 print(f"Replay: room={state.room}, turns={state.turns}, rescued={state.rescued}.")
Show the message or value in the output. Python fills the braces with values before it uses the text.
Line 103 def profile_routes():
Define profile_routes, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 104 route.cache_clear()
Empty the saved results so this measurement starts fresh.
Line 105 with cProfile.Profile() as profiler:
Use the file or helper inside this indented block. Python closes it or finishes that context when the block ends.
Line 106 for _ in range(40):
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 107 route("Habitat", "Beacon")
Run route with the supplied inputs and come back here when it returns.
Line 108 print("Profiled 40 route queries.")
Show the message or value in the output.
Line 109 print(route.cache_info())
Show the message or value in the output. Read statistics on results already saved and requests that needed fresh work.
Line 110 pstats.Stats(profiler).sort_stats("cumulative").print_stats(5)
Prepare the profiler’s recorded measurements for display. Choose the order in which measurements will be shown. Print the measured counts and timings for the selected functions.
Line 112 class MissionTests(unittest.TestCase):
Define MissionTests, a class that groups related data or behaviour. It starts with the behaviour from unittest.TestCase.
Line 113 def test_invalid_move_costs_nothing(self):
Define test_invalid_move_costs_nothing, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Lines 114–129
Line 114 state = State()
Work out the value on the right, then store it in state. Create a mission state using the supplied field values and any defaults.
Line 115 self.assertEqual(step(state, "go north")[0], state)
Fail the test if the actual and expected values differ. The brackets look up a dictionary key or a position that starts at zero. Run step with the supplied inputs and come back here when it returns.
Line 117 def test_part_can_be_collected_once(self):
Define test_part_can_be_collected_once, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Line 118 state = replay(["go east", "take"])
Work out the value on the right, then store it in state. Run replay with the supplied inputs and come back here when it returns.
Line 119 self.assertEqual(step(state, "take")[0], state)
Fail the test if the actual and expected values differ. The brackets look up a dictionary key or a position that starts at zero. Run step with the supplied inputs and come back here when it returns.
Line 120 self.assertEqual(state.parts, ("Coil",))
Fail the test if the actual and expected values differ. Commas group these values into an ordered tuple.
Line 122 def test_early_repair_fails(self):
Define test_early_repair_fails, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Line 123 state = replay(["go east", "go south"])
Work out the value on the right, then store it in state. Run replay with the supplied inputs and come back here when it returns.
Line 124 self.assertFalse(step(state, "repair")[0].rescued)
Fail the test if this value behaves as true.
Line 126 def test_demo_restores_beacon(self):
Define test_demo_restores_beacon, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Line 127 state = replay(DEMO)
Work out the value on the right, then store it in state. Run replay with the supplied inputs and come back here when it returns.
Line 128 self.assertTrue(state.rescued)
Fail the test if this value behaves as false.
Line 129 self.assertEqual(state.turns, 7)
Fail the test if the actual and expected values differ.
Lines 130–146
Line 130 self.assertEqual(state.energy, 1)
Fail the test if the actual and expected values differ.
Line 132 def test_charge_prevents_a_dead_end(self):
Define test_charge_prevents_a_dead_end, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Line 133 empty = replace(State(), energy=0)
Work out the value on the right, then store it in empty. Make a new state with the named changes. The old state stays available. Create a mission state using the supplied field values and any defaults.
Line 134 self.assertEqual(step(empty, "go east")[0], empty)
Fail the test if the actual and expected values differ. The brackets look up a dictionary key or a position that starts at zero. Run step with the supplied inputs and come back here when it returns.
Line 135 self.assertEqual(step(empty, "charge")[0].energy, MAX_ENERGY)
Fail the test if the actual and expected values differ.
Line 137 def test_shortest_route(self):
Define test_shortest_route, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
Line 138 self.assertEqual(route("Habitat", "Beacon"), ("east", "south"))
Fail the test if the actual and expected values differ. Run route with the supplied inputs and come back here when it returns. Commas group these values into an ordered tuple.
Line 140 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 141 pack = ", ".join(state.parts) or "empty"
Work out the value on the right, then store it in pack. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Line 142 restored = "online" if state.rescued else "offline"
Work out the value on the right, then store it in restored. Choose the first value if the condition is true, otherwise choose the value after else.
Line 143 message = f"{state.room} | pack: {pack} | Beacon: {restored}"
Work out the value on the right, then store it in message. Python fills the braces with values before it uses the text.
Line 144 return f"{message} | energy: {state.energy} | turns: {state.turns}"
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 146 def normalise(text):
Define normalise, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Lines 147–165
Line 147 return " ".join(text.lower().split())
Leave this function now and hand the result back to the line that called it. Put strings together with the text before .join separating them. Separate the string into a list of pieces. Return a lowercase copy so capital letters do not change a command.
Line 149 def view_command(state, history, command):
Define view_command, a reusable piece of the program. Its input names are state, history, command. The indented body runs when something calls it.
Lines 150–155 views = { "status": lambda: describe(state), "map": lambda: render_map(state), "history": lambda: "History: " + (" > ".join(history) or "no moves yet"), "log": lambda: json.dumps(history), }
Work out the value on the right, then store it in views. Each colon pairs a key with its value. Run describe with the supplied inputs and come back here when it returns. Run render_map with the supplied inputs and come back here when it returns.
Line 156 if command in views:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 157 return views[command]()
Leave this function now and hand the result back to the line that called it. The brackets look up a dictionary key or a position that starts at zero.
Line 158 if command.startswith("hint "):
Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Line 159 target = command[5:].title()
Work out the value on the right, then store it in target. Return words with title-style capital letters for display.
Line 160 if target not in WORLD:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 161 return "Unknown destination."
Leave this function now and hand the result back to the line that called it.
Line 162 moves = route(state.room, target)
Work out the value on the right, then store it in moves. Run route with the supplied inputs and come back here when it returns.
Line 163 if moves == ():
Run the indented block only if this check is true. Commas group these values into an ordered tuple.
Line 164 return "Route: already there"
Leave this function now and hand the result back to the line that called it.
Line 165 return "Route: " + (" then ".join(moves) if moves else "unreachable")
Leave this function now and hand the result back to the line that called it. 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.
Lines 166–180
Line 166 return None
Leave this function now and hand the result back to the line that called it.
Line 169 def play(read=input, write=print):
Define play, a reusable piece of the program. Its input names are read, write. The indented body runs when something calls it.
Line 170 state, history = State(), []
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 171 write('Pip ready. Type go, take, repair, charge, status, map, history, hint, log or quit.')
Run write with the supplied inputs and come back here when it returns.
Line 172 while True:
Repeat the indented work until a break, return or error ends this path.
Line 173 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 174 command = normalise(read("> "))
Work out the value on the right, then store it in command. Run normalise with the supplied inputs and come back here when it returns. Run read with the supplied inputs and come back here when it returns.
Line 175 except EOFError:
Run this part only when the try block raises EOFError.
Line 176 break
Leave the nearest loop immediately and continue after it.
Line 177 if command == "quit":
Run the indented block only if this check is true.
Line 178 break
Leave the nearest loop immediately and continue after it.
Line 179 view = view_command(state, history, command)
Work out the value on the right, then store it in view. Run view_command with the supplied inputs and come back here when it returns.
Line 180 if view is not None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Lines 181–194
Line 181 write(view)
Run write with the supplied inputs and come back here when it returns.
Line 182 continue
Skip the rest of this pass and start the next loop check.
Line 183 next_state, message = step(state, command)
Give each returned value to the matching name, from left to right. Run step with the supplied inputs and come back here when it returns.
Line 184 if next_state != state:
Run the indented block only if this check is true.
Line 185 history.append(command)
Add the value to the end without replacing the earlier entries.
Line 186 state = next_state
Work out the value on the right, then store it in state.
Line 187 write(message)
Run write with the supplied inputs and come back here when it returns.
Line 188 write("Mission ended.")
Run write with the supplied inputs and come back here when it returns.
Line 190 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 191 mode = sys.argv[1] if len(sys.argv) > 1 else ""
Work out the value on the right, then store it in mode. Choose the first value if the condition is true, otherwise choose the value after else. Count the characters or items. The brackets look up a dictionary key or a position that starts at zero.
Line 192 if mode == "--demo":
Run the indented block only if this check is true.
Line 193 run_demo()
Run run_demo with the supplied inputs and come back here when it returns.
Line 194 elif mode == "--profile":
Run the indented block only if this check is true.
Lines 195–199
Line 195 profile_routes()
Run profile_routes with the supplied inputs and come back here when it returns.
Line 196 elif mode == "--test":
Run the indented block only if this check is true.
Line 197 unittest.main(argv=[sys.argv[0]])
Ask this tool to run its main routine. The brackets look up a dictionary key or a position that starts at zero.
Line 198 else:
Take this branch if the earlier checks for this decision were false.
Line 199 play()
Run play with the supplied inputs and come back here when it returns.

Test the mission

  • Run --test and --demo before playing manually.
  • Read map, status, history and log, then confirm that they have taken no turns.
  • Follow the hint, collect both parts and finish. Compare status with the demo and save a clean copy.

If something goes wrong

An inspection is reported as an unknown action.
Check view_command before sending the command to step.
A testing function is never called.
Pass it into play as read or write and use those parameter names inside the loop.

Mission extension

Write a tiny testing wrapper that supplies commands from a list and collects messages with append. Check that quit stops the sequence.