Python 36 · Balance battery energy and turns

Python lesson 36 of 50 · Advanced · About 40 minutes

Give the rover meaningful battery limits and design a recovery action so learners can always continue playing.

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

Mission Charge one point for successful actions, count turns, and build a safe charge command.

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

Spend. Pay for an action that succeeds.. → Stop. Block actions at zero energy.. → Recover. Make a charge available in every room..
Spend → Stop → Recover

Understand the Python in this lesson

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

Store resource counters with the rest of the mission

MAX_ENERGY = 8 gives the battery limit a shared name. The energy: int and turns: int fields are meant to hold whole numbers. Fresh states start with eight energy units and zero turns.

Collect optional changes with two stars

In def spend(state, **changes):, **changes gathers extra named arguments into a dictionary. For spend(state, room=target) it contains the new room. Inside replace(..., **changes), two stars unpack the entries back into named arguments.

Apply the cost and action together

energy=state.energy - 1 and turns=state.turns + 1 give replace its counter values. Additional fields such as room, parts or rescued arrive through changes. All updates become one new State, so an accepted action is recorded in history as one step.

Check the battery at the right moment

if state.energy == 0: stops ordinary actions before they can spend a point. The earlier charge branch can refill an empty battery. Charge takes a turn when it succeeds. An already full battery returns the old state, as does an invalid move.

How the pieces fit Successful move, take and repair commands share one cost helper. Views read the counters without spending a turn, so learners can plan without a penalty.

Follow one run, step by step
  1. Type status at the start.
    energy: 8 | turns: 0 Why State uses the battery and turn defaults.
  2. Go east.
    Pip reaches Workshop with energy 7 and turns 1. Why The exit is legal, so spend changes the room and applies the cost.
  3. Go north from Workshop.
    The counters stay at 7 and 1. Why The missing exit returns before spend is called.
  4. Charge twice.
    Energy returns to 8 and turns becomes 2. The second charge leaves both values unchanged. Why Only the first charge changes a field.

Predict before you run Why can Pip still charge at zero energy even though a move at zero is blocked?

Reveal the explanation

The code checks charge first and returns the new state from that branch. A move reaches the zero guard, which returns the current state without spending.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills state invariants, boundary values, turn costs, recovery.

1. Pick a simple cost rule

Every successful move, part collection or repair uses one unit of energy and takes one turn. The code stores both numbers in the mission state so you can track how actions affect them. The small spend function handles those two updates alongside whichever field the action needs to change. Passing the field as a named argument lets the same function move Pip, pack a part or turn on the beacon. Write down the cost of the rescue route from earlier lessons. It takes four moves, two collections and one repair, for seven battery units.

return replace(state, energy=state.energy - 1,
                   turns=state.turns + 1, **changes)

2. Design the battery boundary

A legal game state should keep energy between zero and eight. Before trying to move, take or repair, the engine checks for an empty battery. It returns the same state with guidance if there is no energy left. A wall or missing component also returns an unchanged state because the operation did not succeed. Play deliberately inefficiently and count what costs energy. Notice that status and map use no energy because they do not advance the game. Check the exact boundary at zero, which is where many game rules behave unexpectedly.

if state.energy == 0:
        return state, "Battery empty. Use charge to continue."

3. Keep a way to continue

Pip’s emergency solar panel can recharge in any room. The engine checks charge before the zero-energy guard so this action still works when the battery is empty. Charging to eight takes one turn and leaves the room and parts alone. If the battery is full already, the command makes no change. Try it twice in a row and compare the turn count. A reliable recovery rule is part of designing a fair game: the player can make a mistake, learn why it happened and decide how to finish the mission.

return replace(state, energy=MAX_ENERGY, turns=state.turns + 1), "Charged to 8."
Complete Python checkpoint · moonbase_36.py
from dataclasses import dataclass, replace
from collections import deque

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


MAX_ENERGY = 8


@dataclass(frozen=True)
class State:
    room: str = "Habitat"
    parts: tuple = ()
    rescued: bool = False
    energy: int = MAX_ENERGY
    turns: int = 0

def spend(state, **changes):
    return replace(state, energy=state.energy - 1,
                   turns=state.turns + 1, **changes)

def step(state, command):
    if state.rescued:
        return state, "Beacon already online."
    if command == "charge":
        if state.energy == MAX_ENERGY:
            return state, "The battery is already full."
        return replace(state, energy=MAX_ENERGY, turns=state.turns + 1), "Charged to 8."
    if state.energy == 0:
        return state, "Battery empty. Use charge to continue."
    if command.startswith("go "):
        direction = command[3:]
        target = WORLD[state.room].get(direction)
        if target is None:
            return state, "No exit that way."
        return spend(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 spend(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 spend(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 route(start, target):
    queue = deque([(start, ())])
    seen = {start}
    while queue:
        room, moves = queue.popleft()
        if room == target:
            return moves
        for direction, neighbour in WORLD[room].items():
            if neighbour not in seen:
                seen.add(neighbour)
                queue.append((neighbour, (*moves, direction)))
    return None

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 f"{message} | energy: {state.energy} | turns: {state.turns}"

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
        if command.startswith("hint "):
            target = command[5:].title()
            if target not in WORLD:
                print("Unknown destination.")
            else:
                moves = route(state.room, target)
                print("Route:", " then ".join(moves) if moves else "already there" if moves == () else "unreachable")
            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–23
Line 1 from dataclasses import dataclass, replace
Bring dataclass, replace into this file from dataclasses. These names can now be used directly.
Line 2 from collections import deque
Bring deque into this file from collections. These names can now be used directly.
Lines 4–9 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 10 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 11 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 14 MAX_ENERGY = 8
Work out the value on the right, then store it in MAX_ENERGY.
Line 17 @dataclass(frozen=True)
Ask Python to create the usual data-handling methods from the listed fields.
Line 18 class State:
Define State, a class that groups related data or behaviour.
Line 19 room: str = "Habitat"
Describe the expected type of room as str and provide its starting value.
Line 20 parts: tuple = ()
Describe the expected type of parts as tuple and provide its starting value. Commas group these values into an ordered tuple.
Line 21 rescued: bool = False
Describe the expected type of rescued as bool and provide its starting value.
Line 22 energy: int = MAX_ENERGY
Describe the expected type of energy as int and provide its starting value.
Line 23 turns: int = 0
Describe the expected type of turns as int and provide its starting value.
Lines 25–39
Line 25 def spend(state, **changes):
Define spend, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Lines 26–27 return replace(state, energy=state.energy - 1, turns=state.turns + 1, **changes)
Leave this function now and hand the result back to the line that called it. Make a new state with the named changes. The old state stays available.
Line 29 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 30 if state.rescued:
Run the indented block only if this check is true.
Line 31 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 32 if command == "charge":
Run the indented block only if this check is true.
Line 33 if state.energy == MAX_ENERGY:
Run the indented block only if this check is true.
Line 34 return state, "The battery is already full."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 35 return replace(state, energy=MAX_ENERGY, turns=state.turns + 1), "Charged to 8."
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 36 if state.energy == 0:
Run the indented block only if this check is true.
Line 37 return state, "Battery empty. Use charge to continue."
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 command.startswith("go "):
Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Line 39 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.
Lines 40–52
Line 40 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 41 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 42 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 43 return spend(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. Run spend with the supplied inputs and come back here when it returns. Python fills the braces with values before it uses the text.
Line 44 if command == "take":
Run the indented block only if this check is true.
Line 45 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 46 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 47 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 48 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 49 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 50 return spend(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. Run spend with the supplied inputs and come back here when it returns. Python fills the braces with values before it uses the text.
Line 51 if command == "repair":
Run the indented block only if this check is true.
Line 52 if state.room != "Beacon":
Run the indented block only if this check is true.
Lines 53–67
Line 53 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 54 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 55 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 56 return spend(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. Run spend with the supplied inputs and come back here when it returns.
Line 57 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 59 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 60 rooms = []
Work out the value on the right, then store it in rooms.
Line 61 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 62 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 63 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 64 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 65 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.
Line 67 def route(start, target):
Define route, a reusable piece of the program. Its input names are start, target. The indented body runs when something calls it.
Lines 68–81
Line 68 queue = deque([(start, ())])
Work out the value on the right, then store it in queue. Create a queue that can efficiently take items from either end. Commas group these values into an ordered tuple.
Line 69 seen = {start}
Work out the value on the right, then store it in seen.
Line 70 while queue:
Check queue before each pass. Repeat the indented work while it is true.
Line 71 room, moves = queue.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 72 if room == target:
Run the indented block only if this check is true.
Line 73 return moves
Leave this function now and hand the result back to the line that called it.
Line 74 for direction, neighbour in WORLD[room].items():
Take one item at a time and give it to direction, neighbour, then run the indented block. Make the dictionary's key and value pairs available to loop over.
Line 75 if neighbour 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 76 seen.add(neighbour)
Add the value to the set. A set keeps at most one copy.
Line 77 queue.append((neighbour, (*moves, direction)))
Add the value to the end without replacing the earlier entries. Commas group these values into an ordered tuple.
Line 78 return None
Leave this function now and hand the result back to the line that called it.
Line 80 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 81 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.
Lines 82–96
Line 82 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 83 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 84 return f"{message} | energy: {state.energy} | turns: {state.turns}"
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 86 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 87 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 89 def play():
Define play, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 90 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 91 history = []
Work out the value on the right, then store it in history.
Line 92 print('Moonbase Rescue. Type go east, take, repair, status or quit.')
Show the message or value in the output.
Line 93 while True:
Repeat the indented work until a break, return or error ends this path.
Line 94 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 95 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 96 except EOFError:
Run this part only when the try block raises EOFError.
Lines 97–109
Line 97 break
Leave the nearest loop immediately and continue after it.
Line 98 if command == "quit":
Run the indented block only if this check is true.
Line 99 break
Leave the nearest loop immediately and continue after it.
Line 100 if command == "status":
Run the indented block only if this check is true.
Line 101 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 102 continue
Skip the rest of this pass and start the next loop check.
Line 103 if command == "map":
Run the indented block only if this check is true.
Line 104 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 105 continue
Skip the rest of this pass and start the next loop check.
Line 106 if command == "history":
Run the indented block only if this check is true.
Line 107 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.
Line 108 continue
Skip the rest of this pass and start the next loop check.
Line 109 if command.startswith("hint "):
Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Lines 110–122
Line 110 target = command[5:].title()
Work out the value on the right, then store it in target. Return words with title-style capital letters for display.
Line 111 if target not in WORLD:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 112 print("Unknown destination.")
Show the message or value in the output.
Line 113 else:
Take this branch if the earlier checks for this decision were false.
Line 114 moves = route(state.room, target)
Work out the value on the right, then store it in moves. Run route with the supplied inputs and come back here when it returns.
Line 115 print("Route:", " then ".join(moves) if moves else "already there" if moves == () else "unreachable")
Show the message or value in the output. Choose the first value if the condition is true, otherwise choose the value after else. Put strings together with the text before .join separating them.
Line 116 continue
Skip the rest of this pass and start the next loop check.
Line 117 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 118 if next_state != state:
Run the indented block only if this check is true.
Line 119 history.append(command)
Add the value to the end without replacing the earlier entries.
Line 120 state = next_state
Work out the value on the right, then store it in state.
Line 121 print(message)
Show the message or value in the output.
Line 122 print("Mission ended.")
Show the message or value in the output.
Lines 124–125
Line 124 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 125 play()
Run play with the supplied inputs and come back here when it returns.

Test the mission

  • Finish the seven-action rescue and compare your final energy with the prediction.
  • Use map twice. The turn and energy totals should remain the same.
  • Use up eight units with valid moves, then check that charge gives Pip a route back into the game.

If something goes wrong

Energy becomes negative.
Put the zero guard before the actions that call spend.
Pip is stranded when energy reaches zero.
Check charge before the guard and provide it as an option in the next message.

Mission extension

Set MAX_ENERGY to 6 and update the charge text to use the constant. Test that a rescue is still achievable using a charge.