Python 34 · Keep a command history

Python lesson 34 of 50 · Advanced · About 35 minutes

Give the rescue crew a reliable log of successful game actions. Separate moves that change the mission from inspections and mistakes.

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

Mission Record accepted state changes and inspect them in order.

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

Capture. Keep a state before and after each action.. → Compare. Detect a genuine change in state.. → Record. Add the successful command to the log..
Capture → Compare → Record

Understand the Python in this lesson

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

Choose a collection that keeps the order

history = [] creates an empty list each time play starts. A list can grow during a mission. history.append(command) changes that list in place by placing the newest accepted action at the end.

Hold on to the old value until the comparison

next_state, message = step(state, command) keeps the earlier state in state. next_state != state asks whether the dataclass field values differ. A new object with the same field values would compare equal. Only a difference adds a command to the list.

Update the loop once the check is done

state = next_state comes after the comparison. The indentation puts only history.append(command) inside the if. The assignment and print run on every engine turn, including a rejected action that returns the original state and an explanation.

Display the history without changing it

" > ".join(history) creates one string using the separator. When there are no entries, the joined string is empty, so or "no moves yet" supplies a useful message. The history inspection calls continue before the game-rule block.

How the pieces fit The history records the actions that explain how Pip got here. The same sequence can later run from a fresh state to recreate the mission.

Follow one run, step by step
  1. Start a mission and type history.
    History: no moves yet Why The list is empty, and joining it gives an empty string.
  2. Type map and then go east.
    The list becomes ['go east']. Why Map only displays data. The east move changes the room to Workshop.
  3. Take the Coil twice.
    The first take is recorded. The second reports that you already have the part. Why Only the first action changes the pack.
  4. Type history again.
    History: go east > take Why The stored actions are displayed from earliest to latest.

Predict before you run If you move state = next_state above the != check, what gets written to the log?

Reveal the explanation

Nothing from that comparison. Both names now refer to the returned state, so their values match on every turn.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills lists, equality, append, command logs.

1. Choose the record you need

Mission Control wants a record that explains how Pip reached the current state. A map command does not move the rover; an impossible move does not change its position either. In this checkpoint the history records only commands that change the mission. It starts as an empty list at the same time as a fresh State. Before building, write a prediction for the sequence map, go east, take, take, history. Your record should include just the move and first successful collection.

history = []

2. Compare before adding a record

The loop keeps the new state in next_state while the old one is still available. Dataclass equality compares the contents of the fields, which means you can tell whether anything useful changed with a normal inequality check. If the values differ, append the command. Then assign the new state for the next turn. The order here matters. Setting state first and comparing afterward would compare the new state with itself. Test the second collection attempt in Workshop and check that the unchanged result does not add another line to the log.

if next_state != state:
            history.append(command)
        state = next_state

3. Read the log as an ordered account

The history inspection joins the recorded commands in the order they happened. You can print it as often as you like without adding anything to the list. Read a sequence aloud and try to reconstruct the current room and contents of the pack. This is more than a convenience for the player. A cleaned sequence of changing commands gives us a simple way to replay a mission later. Make sure the records start with the expedition’s first move each time you restart, and save this checkpoint so you can compare the later replay feature.

print("History:", " > ".join(history) or "no moves yet")
Complete Python checkpoint · moonbase_34.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()
    history = []
    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
        if command == "history":
            print("History:", " > ".join(history) or "no moves yet")
            continue
        next_state, message = step(state, command)
        if next_state != state:
            history.append(command)
        state = next_state
        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 history = []
Work out the value on the right, then store it in history.
Line 63 print('Moonbase Rescue. Type go east, take, repair, status or quit.')
Show the message or value in the output.
Line 64 while True:
Repeat the indented work until a break, return or error ends this path.
Line 65 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Lines 66–78
Line 66 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 67 except EOFError:
Run this part only when the try block raises EOFError.
Line 68 break
Leave the nearest loop immediately and continue after it.
Line 69 if command == "quit":
Run the indented block only if this check is true.
Line 70 break
Leave the nearest loop immediately and continue after it.
Line 71 if command == "status":
Run the indented block only if this check is true.
Line 72 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 73 continue
Skip the rest of this pass and start the next loop check.
Line 74 if command == "map":
Run the indented block only if this check is true.
Line 75 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 76 continue
Skip the rest of this pass and start the next loop check.
Line 77 if command == "history":
Run the indented block only if this check is true.
Line 78 print("History:", " > ".join(history) or "no moves yet")
Show the message or value in the output. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Lines 79–88
Line 79 continue
Skip the rest of this pass and start the next loop check.
Line 80 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 81 if next_state != state:
Run the indented block only if this check is true.
Line 82 history.append(command)
Add the value to the end without replacing the earlier entries.
Line 83 state = next_state
Work out the value on the right, then store it in state.
Line 84 print(message)
Show the message or value in the output.
Line 85 print("Mission ended.")
Show the message or value in the output.
Line 87 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 88 play()
Run play with the supplied inputs and come back here when it returns.

Test the mission

  • Ask for history before any moves and confirm it is empty.
  • Plan a legal and illegal move, then count the successful entries.
  • Restart the script and confirm that the new log has no entries.

If something goes wrong

Commands never appear in history.
Compare next_state with the old state before you assign the new one.
Inspecting history changes history.
Handle that inspection before the block that calls step.

Mission extension

Add an inspection command called last that prints the latest accepted action or a message if the list is empty.