Python 21 · Separate game rules from the radio

Python lesson 21 of 50 · Intermediate · About 22 minutes

Pip can already explore the moonbase. In this checkpoint, move the repair rules away from the part of the program that reads commands and shows messages.

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

Mission Make Pip follow the same repair rule whether the command comes from a player or a future test.

Get ready

This chapter starts with a fresh checkpoint of Pip’s mission. Compare it with your previous version to see how the game is organised for the next set of skills.

Save the complete checkpoint below as moonbase_21.py in a project folder and run python moonbase_21.py from that folder. Use python3 on systems where that is the Python 3 command. Use Python 3.10 or newer.

Command. The radio loop receives repair.. → Rule. Room and parts become a yes or no.. → Result. The action changes state and returns a message..
Command → Rule → Result

Understand the Python in this lesson

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

Reading a function header

In def can_repair(room, parts):, def introduces a function. The parentheses hold its parameters, the names it will use for its inputs. The comma separates the two names. The colon begins the indented body. When another line calls can_repair("Beacon", ["Coil", "Cell"]), those two values become room and parts for this call.

Let a rule return an answer

The expression room == "Beacon" and REQUIRED.issubset(parts) asks two yes-or-no questions. == compares values. issubset checks that every member of the REQUIRED set appears in the parts collection. If the room test is false, and already knows the whole result is false. return sends that boolean back to the caller.

Give changes to the action

can_repair reads its inputs and gives an answer. repair(state) uses the answer in an if. On success, state["rescued"] = True updates one dictionary entry. Then repair returns the success message. When the rule returns False, the assignment is skipped and the function reaches the reminder message instead.

Find the destination before moving

In move, destinations contains the rooms connected to the current room. The expression inside next(..., None) offers only names whose lowercase form matches target. next takes the first offered name, or returns the fallback None if there is no match. The energy and room change only after both guards pass.

Follow the radio loop

The radio reads a line, trims its edges with strip(), changes it to lowercase, then partition(" ") makes a three-item tuple from the first space. The three names receive the verb, the separator and the remaining text. The name _ signals that the separator is unused. apply chooses the action and print displays its return value.

How the pieces fit Read the program in three layers. The radio loop handles input and output, apply picks an action, and can_repair answers one game-rule question. The bottom check, if __name__ == "__main__":, calls run() when you start this file directly, so you can import the rule into another script without switching on the radio.

Follow one run, step by step
  1. Type repair at the first Habitat prompt.
    The verb is repair and the argument is an empty string. Why There is no space or second part in the input line.
  2. Follow apply into repair and then can_repair.
    The rule returns False. Why Habitat does not match Beacon.
  3. Return to the radio loop.
    Bring the Coil and the Cell to the Beacon. Why The action returns a message and the loop prints it.

Predict before you run If you call can_repair at the Beacon with both parts in a script, does the call print a message?

Reveal the explanation

The call returns True. Use print(can_repair("Beacon", ["Coil", "Cell"])) to display that value. The actual mission announcement comes from repair when its caller prints the returned message.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills pure functions, parameters, return values, input and output.

1. Give the rule only the information it needs

The repair rule asks two questions. Is Pip at the Beacon? Does the parts collection contain both Coil and Cell? Pass the room and parts into can_repair. The answer is a boolean, which means either True or False. Add the function above the command loop and leave all printing in the loop.

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

2. Keep a decision and its message separate

Call the rule from repair. A success sets the rescued flag before returning the good news. A rejected repair keeps the current mission going. This split gives two useful layers. The rule knows the condition for success. The repair action uses the answer to change the mission and produce a message.

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

3. Trace a command through the layers

Start in Habitat and type repair. The command handler calls the repair action, that action asks the rule, and the loop prints the returned message. An unsuccessful repair leaves your energy and parts alone. Follow the same chain when you later bring both parts to the Beacon. At this checkpoint, use go workshop with a room name to move.

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

4. Try the rule on its own

In a Python console, call the repair rule with Habitat and both parts, then with Beacon and both parts. Only the second call gives True. When a function returns a value without printing, wrap the call in print if you want to see the answer in a script.

def can_repair(room, parts):
    return room == "Beacon" and REQUIRED.issubset(parts)
Complete Python checkpoint · moonbase_21.py
ROOMS = {
    "Habitat": ("Workshop", "Greenhouse"),
    "Workshop": ("Habitat", "Beacon"),
    "Greenhouse": ("Habitat", "Beacon"),
    "Beacon": ("Workshop", "Greenhouse"),
}
PARTS = {"Workshop": "Coil", "Greenhouse": "Cell"}
REQUIRED = {"Coil", "Cell"}


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


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


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


def collect(state):
    item = PARTS.get(state["room"])
    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, target):
    destinations = ROOMS[state["room"]]
    place = next((room for room in destinations if room.lower() == target), None)
    if place is None:
        return "That room is not connected."
    if state["energy"] == 0:
        return "Pip is out of energy."
    state["room"] = place
    state["energy"] -= 1
    return f"Moved to {place}."


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():
    state = new_mission()
    print("Moonbase Rescue | Pip on duty")
    print(describe(state))
    print("Try look, go, take, repair or quit.")
    while not state["rescued"]:
        try:
            raw = input("Pip> ")
        except EOFError:
            print("Radio closed.")
            break
        verb, _, argument = raw.strip().lower().partition(" ")
        if verb == "quit":
            print("Pip is on standby.")
            break
        print(apply(state, verb, argument))


if __name__ == "__main__":
    run()

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–26
Lines 1–6 ROOMS = { "Habitat": ("Workshop", "Greenhouse"), "Workshop": ("Habitat", "Beacon"), "Greenhouse": ("Habitat", "Beacon"), "Beacon": ("Workshop", "Greenhouse"), }
Work out the value on the right, then store it in ROOMS. Each colon pairs a key with its value. Commas group these values into an ordered tuple.
Line 7 PARTS = {"Workshop": "Coil", "Greenhouse": "Cell"}
Work out the value on the right, then store it in PARTS. Each colon pairs a key with its value.
Line 8 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 11 def new_mission():
Define new_mission, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 12 return {"room": "Habitat", "energy": 8, "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.
Line 15 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 16 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 19 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 20 room = state["room"]
Work out the value on the right, then store it in room. The brackets look up a dictionary key or a position that starts at zero.
Line 21 exits = ", ".join(ROOMS[room])
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 22 parts = ", ".join(state["parts"]) 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. The brackets look up a dictionary key or a position that starts at zero.
Line 23 return f"{room} | energy {state['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. The brackets look up a dictionary key or a position that starts at zero.
Line 26 def collect(state):
Define collect, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Lines 27–43
Line 27 item = PARTS.get(state["room"])
Work out the value on the right, then store it in item. Look up a key. Use the given fallback, or None, if the key is missing. The brackets look up a dictionary key or a position that starts at zero.
Line 28 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 29 return "There is no repair part here."
Leave this function now and hand the result back to the line that called it.
Line 30 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 31 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.
Line 32 state["parts"].append(item)
Add the value to the end without replacing the earlier entries.
Line 33 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 36 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 37 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 38 state["rescued"] = True
Work out the value on the right, then store it in state["rescued"].
Line 39 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 40 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 43 def move(state, target):
Define move, a reusable piece of the program. Its input names are state, target. The indented body runs when something calls it.
Lines 44–58
Line 44 destinations = ROOMS[state["room"]]
Work out the value on the right, then store it in destinations. The brackets look up a dictionary key or a position that starts at zero.
Line 45 place = next((room for room in destinations if room.lower() == target), None)
Work out the value on the right, then store it in place. 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. Return a lowercase copy so capital letters do not change a command.
Line 46 if place 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 47 return "That room is not connected."
Leave this function now and hand the result back to the line that called it.
Line 48 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 49 return "Pip is out of energy."
Leave this function now and hand the result back to the line that called it.
Line 50 state["room"] = place
Work out the value on the right, then store it in state["room"].
Line 51 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Line 52 return f"Moved to {place}."
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 55 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 56 if verb == "look":
Run the indented block only if this check is true.
Line 57 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 58 if verb == "go":
Run the indented block only if this check is true.
Lines 59–73
Line 59 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 60 if verb == "take":
Run the indented block only if this check is true.
Line 61 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 62 if verb == "repair":
Run the indented block only if this check is true.
Line 63 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.
Line 64 return "Unknown command."
Leave this function now and hand the result back to the line that called it.
Line 67 def run():
Define run, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 68 state = new_mission()
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 69 print("Moonbase Rescue | Pip on duty")
Show the message or value in the output.
Line 70 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 71 print("Try look, go, take, repair or quit.")
Show the message or value in the output.
Line 72 while not state["rescued"]:
Check not state["rescued"] before each pass. Repeat the indented work while it is true.
Line 73 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Lines 74–86
Line 74 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 75 except EOFError:
Run this part only when the try block raises EOFError.
Line 76 print("Radio closed.")
Show the message or value in the output.
Line 77 break
Leave the nearest loop immediately and continue after it.
Line 78 verb, _, argument = raw.strip().lower().partition(" ")
Give each returned value to the matching name, from left to right. Return a copy with whitespace removed from the beginning and end. Return a lowercase copy so capital letters do not change a command. Split at the first separator and keep the text on both sides and the separator itself.
Line 79 if verb == "quit":
Run the indented block only if this check is true.
Line 80 print("Pip is on standby.")
Show the message or value in the output.
Line 81 break
Leave the nearest loop immediately and continue after it.
Line 82 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 85 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 86 run()
Run run with the supplied inputs and come back here when it returns.

Test the mission

  • Type repair at Habitat and check that you still get another prompt.
  • Use go workshop, take, go beacon and repair. Check one part is insufficient.
  • Run again and find both parts before repairing the Beacon.

If something goes wrong

Pip rescues too early.
Call can_repair with the current room and parts. Keep both conditions joining with and.

Mission extension

Add a function that returns whether Pip can afford one more step. Test energy values 0 and 1.