Python 33 · Draw an accessible moonbase map

Python lesson 33 of 50 · Advanced · About 35 minutes

Give Pip a map anyone can read in the terminal. Use room names and named exits so the map works without colour.

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

Mission Render the base layout from WORLD and identify Pip’s current room with words.

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

Read rooms. Visit every room in the map dictionary.. → Describe exits. Use words for direction and destination.. → Mark Pip. Label the current room in the output..
Read rooms → Describe exits → Mark Pip

Understand the Python in this lesson

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

Open the map dictionary one pair at a time

WORLD.items() supplies each room key with its exit dictionary. for room, exits in WORLD.items(): gives the two pieces separate names on each pass. Inside that loop, exits.items() supplies another pair for each exit, a direction and an end room.

Choose the current-room label

" [Pip is here]" if room == state.room else "" is a conditional expression. It chooses one text value. Only the room that matches Pip’s location gets the label. The empty string has no characters, so adding it leaves an ordinary room name.

Build each exit label as needed

f"{direction} to {end}" for direction, end in exits.items() is a generator expression inside join. It produces one formatted string for each exit. The braces inside an f-string insert the current direction and destination. The separator ", " puts a comma and a space between labels.

Assemble the finished lines

rooms.append(...) adds a string to the end of a list. Once every room has a line, "\n".join(rooms) makes one map string. \n stands for a line break. render_map returns the whole string for print to display.

How the pieces fit Movement and the map both read WORLD. Building the text from the same data keeps the instructions in step with the playable exits.

Follow one run, step by step
  1. Type map from Habitat.
    The first line is Habitat [Pip is here]: east to Workshop, south to Greenhouse. Why The Habitat key matches the current room, and its two exits are joined on one line.
  2. Read the rest of the map.
    Workshop, Greenhouse and Beacon each appear on their own line. Why The outer loop visits all four rooms, and a newline separates each line.
  3. Go south, then ask for map again.
    Greenhouse [Pip is here]: north to Habitat, east to Beacon. Why The state changed to Greenhouse while WORLD kept the same exits.

Predict before you run What would happen if you returned rooms from the helper instead of "\n".join(rooms)?

Reveal the explanation

The caller would get a list of separate room strings. Printing that list displays Python list notation. Joining first gives the player a line-by-line map.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills rendering, dict.items, join, accessible output.

1. Read the world data

A map helps when Pip is planning which part to pick up next. The program already knows every room and exit in WORLD, so it can build the map from that data. Start by looping over the room keys and their exit dictionaries with WORLD.items(). For each room, compare its name with state.room. Attach the words [Pip is here] only when the names match. Use the output of map from Habitat and Workshop to check that exactly one room has that label.

for room, exits in WORLD.items():
        current = " [Pip is here]" if room == state.room else ""

2. Spell out the exits

An arrow diagram could be useful, but a text description also works when the terminal uses a narrow screen or a reader speaks the output aloud. For each exit, the generator expression builds a short label such as east to Workshop. The first join combines labels on one line. The second join combines room lines into the complete map. Keeping the data separate makes changes dependable. If you later connect two new rooms in WORLD, the map will include those paths automatically when they are added to the data.

links = ", ".join(f"{direction} to {end}" for direction, end in exits.items())

3. Choose when to render

The map is an inspection command, so its condition belongs beside status. It returns to the top of the loop after printing and leaves the mission state untouched. Try map, go south, then map again. Destination names should remain stable while Pip’s label moves. Play without looking at the code and use the map to plan a path from Greenhouse to Workshop. Check each step against the listed exits. If you find an unlabeled or one-way route, inspect WORLD to work out whether it was deliberate.

if command == "map":
            print(render_map(state))
            continue
Complete Python checkpoint · moonbase_33.py
from dataclasses import dataclass, replace

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"}


@dataclass(frozen=True)
class State:
    room: str = "Habitat"
    parts: tuple = ()
    rescued: bool = False

def step(state, command):
    if state.rescued:
        return state, "Beacon already online."
    if command.startswith("go "):
        direction = command[3:]
        target = WORLD[state.room].get(direction)
        if target is None:
            return state, "No exit that way."
        return replace(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 replace(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 replace(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)

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 message

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

def play():
    state = State()
    print('Moonbase Rescue. Type go east, take, repair, status or quit.')
    while True:
        try:
            command = normalise(input("> "))
        except EOFError:
            break
        if command == "quit":
            break
        if command == "status":
            print(describe(state))
            continue
        if command == "map":
            print(render_map(state))
            continue
        state, message = step(state, command)
        print(message)
    print("Mission ended.")

if __name__ == "__main__":
    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–22
Line 1 from dataclasses import dataclass, replace
Bring dataclass, replace into this file from dataclasses. These names can now be used directly.
Lines 3–8 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 9 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 10 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 13 @dataclass(frozen=True)
Ask Python to create the usual data-handling methods from the listed fields.
Line 14 class State:
Define State, a class that groups related data or behaviour.
Line 15 room: str = "Habitat"
Describe the expected type of room as str and provide its starting value.
Line 16 parts: tuple = ()
Describe the expected type of parts as tuple and provide its starting value. Commas group these values into an ordered tuple.
Line 17 rescued: bool = False
Describe the expected type of rescued as bool and provide its starting value.
Line 19 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 20 if state.rescued:
Run the indented block only if this check is true.
Line 21 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 22 if command.startswith("go "):
Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Lines 23–35
Line 23 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 24 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 25 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 26 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 27 return replace(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. 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 28 if command == "take":
Run the indented block only if this check is true.
Line 29 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 30 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.
Line 31 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 32 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 33 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 34 return replace(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. 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 35 if command == "repair":
Run the indented block only if this check is true.
Lines 36–49
Line 36 if state.room != "Beacon":
Run the indented block only if this check is true.
Line 37 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 38 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 39 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 40 return replace(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. Make a new state with the named changes. The old state stays available.
Line 41 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 43 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 44 rooms = []
Work out the value on the right, then store it in rooms.
Line 45 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 46 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 47 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 48 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 49 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.
Lines 51–65
Line 51 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 52 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 53 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 54 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 55 return message
Leave this function now and hand the result back to the line that called it.
Line 57 def normalise(text):
Define normalise, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 58 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 60 def play():
Define play, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 61 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 62 print('Moonbase Rescue. Type go east, take, repair, status or quit.')
Show the message or value in the output.
Line 63 while True:
Repeat the indented work until a break, return or error ends this path.
Line 64 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 65 command = normalise(input("> "))
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. Show the prompt and wait for the player to type a line. The answer starts as text.
Lines 66–78
Line 66 except EOFError:
Run this part only when the try block raises EOFError.
Line 67 break
Leave the nearest loop immediately and continue after it.
Line 68 if command == "quit":
Run the indented block only if this check is true.
Line 69 break
Leave the nearest loop immediately and continue after it.
Line 70 if command == "status":
Run the indented block only if this check is true.
Line 71 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 72 continue
Skip the rest of this pass and start the next loop check.
Line 73 if command == "map":
Run the indented block only if this check is true.
Line 74 print(render_map(state))
Show the message or value in the output. Run render_map with the supplied inputs and come back here when it returns.
Line 75 continue
Skip the rest of this pass and start the next loop check.
Line 76 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 77 print(message)
Show the message or value in the output.
Line 78 print("Mission ended.")
Show the message or value in the output.
Lines 80–81
Line 80 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 81 play()
Run play with the supplied inputs and come back here when it returns.

Test the mission

  • Move from Habitat to Greenhouse and view the map both times.
  • Name two routes from Habitat to Beacon using the map.
  • Compare the full map against status to confirm they agree about Pip’s position.

If something goes wrong

Pip’s label appears beside every room.
Compare each specific room name with state.room inside the loop.
The map prints Python brackets and commas.
Join the prepared room strings with a newline before printing.

Mission extension

Show whether each room still has a part by combining WORLD, PART_AT and state.parts.