Python 32 · Separate the game engine from the terminal

Python lesson 32 of 50 · Advanced · About 30 minutes

Give each piece of the rescue mission one job. Classify commands before calling the game rules, and test actions by inspecting the returned values.

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

Mission Explain why the transition function receives values and returns values, and keep the keyboard and screen work in the command loop.

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

Read. The terminal receives and cleans the words.. → Decide. The engine applies a rule to the state.. → Show. The terminal chooses how to display the result..
Read → Decide → Show

Understand the Python in this lesson

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

Clean the radio message from the inside out

In " ".join(text.lower().split()), lower() runs on the original text first. split() groups the result into words, ignoring runs of spaces at the ends and between words. join puts one space between those words. This one helper gives every game rule a consistent spelling.

Keep the game rules inside step

step(state, command) uses values supplied by the caller. With the map fixed, the same state and command give the same result. This is what makes these rules predictable enough for a test or a replay. return hands the result to the caller and ends that call immediately.

Learn the missing-exit case

WORLD[state.room] selects a room’s dictionary. Its .get(direction) returns None when the direction is missing. The code checks target is None before it tries to replace the room. None is Python’s special value for the missing answer here.

Let the loop manage the conversation

input("> ") shows a prompt and reads text. The loop cleans it, checks for quit and status, and passes action commands to step. continue skips down to the next turn of the loop after status. break leaves the loop when you quit or when EOFError says there is no more input.

How the pieces fit Read a command, clean it, choose a view or apply a rule, then show the result. Keeping those jobs apart lets the next lesson add a map.

Follow one run, step by step
  1. Type GO EAST in capitals with several spaces between the words.
    The command passed to step is go east. Why The chain lower, split and join cleans both letters and whitespace.
  2. step applies go east at Habitat.
    Arrived at Workshop. Why The engine uses the current room together with the direction.
  3. Type go north in Workshop.
    No exit that way. Why The dictionary has west and south but get returns None for north.
  4. Type status.
    Workshop | pack: empty | Beacon: offline Why The view reads state, and continue returns to the prompt before the engine call.

Predict before you run If you call step(State(), "go east") directly, does that call print a line by itself?

Reveal the explanation

It returns a Workshop state and the text Arrived at Workshop.. To display them, let the terminal loop unpack them and give the message to print.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills functions, pure transition, return values, input boundary.

1. Sort commands by what they do

Pip’s keyboard console handles two different jobs. Some commands, such as status, ask what is happening. Others, such as go east, attempt to change the mission. Start by tracing both paths through the loop. For status, the loop displays the result of describe and jumps back to read the next command. The transition function is never called for that request. Keeping inspection outside the engine will make maps, histories and route hints straightforward to add in later checkpoints without adding them to the movement rules.

if command == "status":
            print(describe(state))
            continue

2. Keep game rules predictable

A good check for a small engine is whether the same state and command give the same reply. Examine the path for a missing exit. The transition returns both the original state and a short message. It does not print the message or read a replacement command. That makes it easy to use the function from a terminal, a later graphical screen or a test. Check what happens after the successful route through Workshop and Greenhouse. go east can mean different things in two rooms because the room is an explicit part of the input.

if target is None:
            return state, "No exit that way."

3. Translate typed text before applying rules

The outer loop converts upper-case letters to lower case, breaks input into words and rejoins them with single spaces. So GO EAST becomes go east. Keeping this cleaning in one place helps every rule receive the same spelling. Try an invalid direction and inspect status before and after. If the room or pack changes, investigate the transition instead of the keyboard. Save the checkpoint separately. In the next lesson you will add a fresh way to describe the base while the same movement rules continue to do their job.

def normalise(text):
    return " ".join(text.lower().split())
Complete Python checkpoint · moonbase_32.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 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
        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–50
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 describe(state):
Define describe, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 44 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 45 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 46 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 47 return message
Leave this function now and hand the result back to the line that called it.
Line 49 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 50 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.
Lines 52–64
Line 52 def play():
Define play, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 53 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 54 print('Moonbase Rescue. Type go east, take, repair, status or quit.')
Show the message or value in the output.
Line 55 while True:
Repeat the indented work until a break, return or error ends this path.
Line 56 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 57 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.
Line 58 except EOFError:
Run this part only when the try block raises EOFError.
Line 59 break
Leave the nearest loop immediately and continue after it.
Line 60 if command == "quit":
Run the indented block only if this check is true.
Line 61 break
Leave the nearest loop immediately and continue after it.
Line 62 if command == "status":
Run the indented block only if this check is true.
Line 63 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 64 continue
Skip the rest of this pass and start the next loop check.
Lines 65–70
Line 65 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 66 print(message)
Show the message or value in the output.
Line 67 print("Mission ended.")
Show the message or value in the output.
Line 69 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 70 play()
Run play with the supplied inputs and come back here when it returns.

Test the mission

  • Try typing extra spaces and upper-case letters in GO EAST.
  • Use status before and after go north from Workshop.
  • Read step and find two commands that return the same state when rejected.

If something goes wrong

GO EAST is reported as unknown.
Apply lower, split and join before step receives the command.
The terminal waits after the input is finished.
Keep the EOFError handler so a closed input stream stops the loop.

Mission extension

Add an exits inspection command near status. Use WORLD[state.room] to print valid exit names.