Python 43 · Find the shortest rescue route

Python lesson 43 of 50 · Expert projects · About 65 minutes

Let Pip’s planner search possible rescue actions and give one useful hint.

Pip works at the glowing Beacon above the moonbase, with Earth and ribbons of colour overhead.

Mission Build a breadth-first search that finds a shortest sequence of legal actions or reports that no route remains.

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

Enqueue. Start the search from Pip’s current state.. → Expand. Try one engine action for each possible next move.. → Hint. Return the first command on a shortest rescue route..
Enqueue → Expand → Hint

Understand the Python in this lesson

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

Plan with full snapshots

plan_route searches sequences of actions. Each snapshot stores room, energy, parts and rescue status. After a pickup, a visit to an earlier room can now lead to a useful new action.

Put the oldest guess first

deque([(start, ())]) sets up a queue with one pair: the starting snapshot and empty history. popleft() removes the oldest pair and append adds a pair at the other end. This checks shorter histories first, which is called breadth-first search.

Read sets and comprehensions in place

{start} creates a set containing one snapshot. The set remembers which snapshots the search has already reached. The brackets around f"go {room}" for room in LINKS[current.room] build a list of valid exit commands. The code joins that list to ["take", "repair"] to make the actions to try.

Try an action and store its history

following, _ = step(...) unpacks the new state and assigns the unused message to _. If following not in seen, seen.add remembers it and the queue gets the new state and path. history + (action,) adds one command to a fresh tuple.

Choose what the hint prints

A successful search returns the history. If the queue runs out, it returns None. route[0] reads the first action. The conditional expression prints it when a route has an entry and gives a fallback otherwise.

How the pieces fit The seed sets up the mission. The queue finds a path. The same step function moves Pip in both the planner’s trial snapshots and the live game.

Follow one run, step by step
  1. Start with --seed 0.
    The first queue entry holds Habitat and an empty history. Why No action has been tried yet.
  2. Expand the starting snapshot.
    Workshop and Greenhouse moves are added to the queue. Why Both exits change the state. Trying take in the empty Habitat leaves the state unchanged, so it is already in seen.
  3. Type hint at the opening prompt.
    Try: go greenhouse. Why The first complete rescue path found starts there. The hint reports its first action without moving Pip.
  4. Try go greenhouse, take, go beacon, take and repair.
    Rescue complete! Radio online. Why Each action changes the real snapshot in play until the win rule is reached.

Predict before you run Why would storing only the room name in seen lose some useful paths?

Reveal the explanation

The search could skip a return to a room after a pickup. The full snapshot distinguishes a room visit with a part from the same room visit without it.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills Breadth-first search, Deque, Visited states.

1. Search the whole mission state

A shortest walk to Beacon may arrive before Pip has the parts. Treat a search position as the whole State, with room, energy, parts and rescue status. Begin with the actual state, not a fresh record, because a hint should respect the moves and pickups the player has already made. The frozen dataclass can be stored in a set to remember which records have already been reached.

frontier = deque([(start, ())])
    seen = {start}

2. Explore one action at a time

The queue holds a state and the sequence that reached it. Use popleft() to pull the oldest entry. Ask step() what each legal-looking move, pickup or repair attempt would do. A rejected action returns the same state, which the set has already seen, so it cannot make the search repeat forever. Put new states on the back of the queue with append(). The first rescue found uses the fewest actions under those rules.

frontier.append((following, history + (action,)))

3. Offer a hint without driving for the player

The terminal calls the planner when you type hint. It prints the first suggested command and leaves Pip exactly where she is. An exhausted rover can sometimes repair from Beacon without moving. Another stranded rover has no possible route, in which case the queue empties and the function returns None. Try following the hint three times, then make a deliberate detour and ask for another suggestion to see the plan change.

route = plan_route(state, locations)
Complete Python checkpoint · moonbase_43.py
"""Moonbase Rescue. Guide Pip and repair the radio beacon."""
import argparse
from dataclasses import dataclass, replace
import random
from collections import deque


LINKS = {
    "habitat": ("workshop", "greenhouse"),
    "workshop": ("habitat", "beacon"),
    "greenhouse": ("habitat", "beacon"),
    "beacon": ("workshop", "greenhouse"),
}
PARTS = ("Coil", "Cell")


def make_locations(seed):
    rng = random.Random(seed)
    rooms = ("workshop", "greenhouse", "habitat", "beacon")
    return dict(zip(PARTS, rng.sample(rooms, k=len(PARTS))))


@dataclass(frozen=True)
class State:
    room: str = "habitat"
    energy: int = 7
    parts: tuple = ()
    rescued: bool = False


def step(state, command, locations):
    if state.rescued:
        return state, "Radio already online."
    if command.startswith("go "):
        target = command[3:]
        if target not in LINKS[state.room]:
            return state, "That hatch is not connected."
        if state.energy == 0:
            return state, "Pip has no energy for another move."
        return replace(state, room=target, energy=state.energy - 1), f"Pip enters {target.title()}."
    if command == "take":
        part = next((name for name, room in locations.items() if room == state.room), None)
        if part is None or part in state.parts:
            return state, "There is no new repair part here."
        return replace(state, parts=state.parts + (part,)), f"Pip takes the {part}."
    if command == "repair":
        if state.room != "beacon" or not all(part in state.parts for part in PARTS):
            return state, "Repair needs both parts at the Beacon."
        return replace(state, rescued=True), "Rescue complete! Radio online."
    return state, "Command not understood."


def plan_route(start, locations):
    frontier = deque([(start, ())])
    seen = {start}
    while frontier:
        current, history = frontier.popleft()
        if current.rescued:
            return history
        actions = [f"go {room}" for room in LINKS[current.room]] + ["take", "repair"]
        for action in actions:
            following, _ = step(current, action, locations)
            if following not in seen:
                seen.add(following)
                frontier.append((following, history + (action,)))
    return None


def show_state(state, locations, plain=False):
    print(f"Location: {state.room.title()} | Energy: {state.energy} | Parts: {', '.join(state.parts) or 'none'}")
    print("Exits: " + ", ".join(LINKS[state.room]))


def play(seed, energy, plain=False):
    locations = make_locations(seed)
    state, actions = State(energy=energy), []
    print(f"Moonbase Rescue | Seed {seed}")
    print("Commands: look, go ROOM, take, repair, hint, quit.")
    for _ in range(150):
        if state.rescued:
            return
        try:
            command = input("> ").strip().lower()
        except EOFError:
            return
        if command == "quit":
            return
        if command == "look":
            show_state(state, locations, plain)
            continue
        if command == "hint":
            route = plan_route(state, locations)
            print(f"Try: {route[0]}" if route else "No rescue route from here. Restart and try another route.")
            continue
        new_state, message = step(state, command, locations)
        print(message)
        if new_state != state:
            actions.append(command)
            state = new_state
    print("Radio shift ended. Start a new mission to continue.")


def main():
    parser = argparse.ArgumentParser(description="Guide Pip through four rooms and repair the Beacon.")
    parser.add_argument("--seed", type=int, metavar="0..9999", default=0, help="choose a repeatable part layout")
    args = parser.parse_args()
    if not 0 <= args.seed <= 9999:
        parser.error("--seed must be from 0 to 9999")
    play(args.seed, 7, False)


if __name__ == "__main__":
    main()

Read the complete checkpoint line by line

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

Lines 1–24
Line 1 """Moonbase Rescue. Guide Pip and repair the radio beacon."""
This is a description for readers. Python does not print it automatically.
Line 2 import argparse
Bring in argparse. Its module name gives you access to the tools it contains.
Line 3 from dataclasses import dataclass, replace
Bring dataclass, replace into this file from dataclasses. These names can now be used directly.
Line 4 import random
Bring in random. Its module name gives you access to the tools it contains.
Line 5 from collections import deque
Bring deque into this file from collections. These names can now be used directly.
Lines 8–13 LINKS = { "habitat": ("workshop", "greenhouse"), "workshop": ("habitat", "beacon"), "greenhouse": ("habitat", "beacon"), "beacon": ("workshop", "greenhouse"), }
Work out the value on the right, then store it in LINKS. Each colon pairs a key with its value. Commas group these values into an ordered tuple.
Line 14 PARTS = ("Coil", "Cell")
Work out the value on the right, then store it in PARTS. Commas group these values into an ordered tuple.
Line 17 def make_locations(seed):
Define make_locations, a reusable piece of the program. Its input names are seed. The indented body runs when something calls it.
Line 18 rng = random.Random(seed)
Work out the value on the right, then store it in rng. Make an independent random generator. Reusing its seed repeats the sequence.
Line 19 rooms = ("workshop", "greenhouse", "habitat", "beacon")
Work out the value on the right, then store it in rooms. Commas group these values into an ordered tuple.
Line 20 return dict(zip(PARTS, rng.sample(rooms, k=len(PARTS))))
Leave this function now and hand the result back to the line that called it. Make a dictionary that connects keys to their values. Pair the first items together, then the second items, and so on. Pick several different entries without using any entry twice.
Line 23 @dataclass(frozen=True)
Ask Python to create the usual data-handling methods from the listed fields.
Line 24 class State:
Define State, a class that groups related data or behaviour.
Lines 25–39
Line 25 room: str = "habitat"
Describe the expected type of room as str and provide its starting value.
Line 26 energy: int = 7
Describe the expected type of energy as int and provide its starting value.
Line 27 parts: tuple = ()
Describe the expected type of parts as tuple and provide its starting value. Commas group these values into an ordered tuple.
Line 28 rescued: bool = False
Describe the expected type of rescued as bool and provide its starting value.
Line 31 def step(state, command, locations):
Define step, a reusable piece of the program. Its input names are state, command, locations. The indented body runs when something calls it.
Line 32 if state.rescued:
Run the indented block only if this check is true.
Line 33 return state, "Radio already online."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 34 if command.startswith("go "):
Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Line 35 target = command[3:]
Work out the value on the right, then store it in target. The slice copies a portion, stopping before the end index if one is given.
Line 36 if target not in LINKS[state.room]:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection. The brackets look up a dictionary key or a position that starts at zero.
Line 37 return state, "That hatch is not connected."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 38 if state.energy == 0:
Run the indented block only if this check is true.
Line 39 return state, "Pip has no energy for another move."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Lines 40–54
Line 40 return replace(state, room=target, energy=state.energy - 1), f"Pip enters {target.title()}."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Make a new state with the named changes. The old state stays available. Python fills the braces with values before it uses the text.
Line 41 if command == "take":
Run the indented block only if this check is true.
Line 42 part = next((name for name, room in locations.items() if room == state.room), None)
Work out the value on the right, then store it in part. Take the first available result, or the given fallback if there is no result. The expression supplies matching values one at a time to the operation using it. Commas group these values into an ordered tuple.
Line 43 if part is None or part in state.parts:
Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Membership checks ask whether an item or key is in a collection.
Line 44 return state, "There is no new repair part here."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 45 return replace(state, parts=state.parts + (part,)), f"Pip takes the {part}."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Make a new state with the named changes. The old state stays available. Python fills the braces with values before it uses the text.
Line 46 if command == "repair":
Run the indented block only if this check is true.
Line 47 if state.room != "beacon" or not all(part in state.parts for part in PARTS):
Run the indented block only if this check is true. With or, the first true result can settle the check. The word not reverses which result counts as true. Check that every result is true.
Line 48 return state, "Repair needs both parts at the Beacon."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 49 return replace(state, rescued=True), "Rescue complete! Radio online."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Make a new state with the named changes. The old state stays available.
Line 50 return state, "Command not understood."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 53 def plan_route(start, locations):
Define plan_route, a reusable piece of the program. Its input names are start, locations. The indented body runs when something calls it.
Line 54 frontier = deque([(start, ())])
Work out the value on the right, then store it in frontier. Create a queue that can efficiently take items from either end. Commas group these values into an ordered tuple.
Lines 55–69
Line 55 seen = {start}
Work out the value on the right, then store it in seen.
Line 56 while frontier:
Check frontier before each pass. Repeat the indented work while it is true.
Line 57 current, history = frontier.popleft()
Give each returned value to the matching name, from left to right. Remove and return the oldest entry at the front of the queue.
Line 58 if current.rescued:
Run the indented block only if this check is true.
Line 59 return history
Leave this function now and hand the result back to the line that called it.
Line 60 actions = [f"go {room}" for room in LINKS[current.room]] + ["take", "repair"]
Work out the value on the right, then store it in actions. The brackets build a new list by looping through eligible values. Python fills the braces with values before it uses the text. The brackets look up a dictionary key or a position that starts at zero.
Line 61 for action in actions:
Take one item at a time and give it to action, then run the indented block.
Line 62 following, _ = step(current, action, locations)
Give each returned value to the matching name, from left to right. Run step with the supplied inputs and come back here when it returns.
Line 63 if following not in seen:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 64 seen.add(following)
Add the value to the set. A set keeps at most one copy.
Line 65 frontier.append((following, history + (action,)))
Add the value to the end without replacing the earlier entries. Commas group these values into an ordered tuple.
Line 66 return None
Leave this function now and hand the result back to the line that called it.
Line 69 def show_state(state, locations, plain=False):
Define show_state, a reusable piece of the program. Its input names are state, locations, plain. The indented body runs when something calls it.
Lines 70–84
Line 70 print(f"Location: {state.room.title()} | Energy: {state.energy} | Parts: {', '.join(state.parts) or 'none'}")
Show the message or value in the output. Python fills the braces with values before it uses the text. Return words with title-style capital letters for display.
Line 71 print("Exits: " + ", ".join(LINKS[state.room]))
Show the message or value in the output. Put strings together with the text before .join separating them. The brackets look up a dictionary key or a position that starts at zero.
Line 74 def play(seed, energy, plain=False):
Define play, a reusable piece of the program. Its input names are seed, energy, plain. The indented body runs when something calls it.
Line 75 locations = make_locations(seed)
Work out the value on the right, then store it in locations. Run make_locations with the supplied inputs and come back here when it returns.
Line 76 state, actions = State(energy=energy), []
Give each returned value to the matching name, from left to right. Commas group these values into an ordered tuple. Create a mission state using the supplied field values and any defaults.
Line 77 print(f"Moonbase Rescue | Seed {seed}")
Show the message or value in the output. Python fills the braces with values before it uses the text.
Line 78 print("Commands: look, go ROOM, take, repair, hint, quit.")
Show the message or value in the output.
Line 79 for _ in range(150):
Take one item at a time and give it to _, then run the indented block. Generate a sequence of integers that stops before the final limit.
Line 80 if state.rescued:
Run the indented block only if this check is true.
Line 81 return
Leave this function now.
Line 82 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 83 command = input("> ").strip().lower()
Work out the value on the right, then store it in command. Show the prompt and wait for the player to type a line. The answer starts as text. Return a copy with whitespace removed from the beginning and end. Return a lowercase copy so capital letters do not change a command.
Line 84 except EOFError:
Run this part only when the try block raises EOFError.
Lines 85–97
Line 85 return
Leave this function now.
Line 86 if command == "quit":
Run the indented block only if this check is true.
Line 87 return
Leave this function now.
Line 88 if command == "look":
Run the indented block only if this check is true.
Line 89 show_state(state, locations, plain)
Run show_state with the supplied inputs and come back here when it returns.
Line 90 continue
Skip the rest of this pass and start the next loop check.
Line 91 if command == "hint":
Run the indented block only if this check is true.
Line 92 route = plan_route(state, locations)
Work out the value on the right, then store it in route. Run plan_route with the supplied inputs and come back here when it returns.
Line 93 print(f"Try: {route[0]}" if route else "No rescue route from here. Restart and try another route.")
Show the message or value in the output. Choose the first value if the condition is true, otherwise choose the value after else. Python fills the braces with values before it uses the text.
Line 94 continue
Skip the rest of this pass and start the next loop check.
Line 95 new_state, message = step(state, command, locations)
Give each returned value to the matching name, from left to right. Run step with the supplied inputs and come back here when it returns.
Line 96 print(message)
Show the message or value in the output.
Line 97 if new_state != state:
Run the indented block only if this check is true.
Lines 98–113
Line 98 actions.append(command)
Add the value to the end without replacing the earlier entries.
Line 99 state = new_state
Work out the value on the right, then store it in state.
Line 100 print("Radio shift ended. Start a new mission to continue.")
Show the message or value in the output.
Line 103 def main():
Define main, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 104 parser = argparse.ArgumentParser(description="Guide Pip through four rooms and repair the Beacon.")
Work out the value on the right, then store it in parser. Create the object that reads launch options and explains how to use them.
Line 105 parser.add_argument("--seed", type=int, metavar="0..9999", default=0, help="choose a repeatable part layout")
Register an option that someone can use when starting the program.
Line 106 args = parser.parse_args()
Work out the value on the right, then store it in args. Read the launch options and put the chosen values into an object.
Line 107 if not 0 <= args.seed <= 9999:
Run the indented block only if this check is true. The word not reverses which result counts as true. Every comparison in the range must be true.
Line 108 parser.error("--seed must be from 0 to 9999")
Show the command-line problem and stop with an error status.
Line 109 play(args.seed, 7, False)
Run play with the supplied inputs and come back here when it returns.
Line 112 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 113 main()
Run main with the supplied inputs and come back here when it returns.

Test the mission

  • Ask for a hint from Habitat and check that look still shows 7 energy.
  • On seed 0, follow the hints until the radio is repaired.

If something goes wrong

The search keeps looking at the same rooms.
Put the full state in seen when adding it to the queue.
Hints ignore already collected parts.
Pass the current state as the search start instead of creating a fresh State.

Mission extension

Add a tie-breaker by reversing the order of exit names. Check that the number of actions remains minimal.