Python 28 · Make a repeatable mission with a seed

Python lesson 28 of 50 · Intermediate · About 26 minutes

Give Pip a small change in starting battery charge. Keep the same mission seed so two players can recreate an identical start.

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

Mission Create a local random generator and pass a numeric seed through the command line.

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

Seed. Start with a chosen number.. → Generator. Make a repeatable starting choice.. → Report. Show the seed and starting charge..
Seed → Generator → Report

Understand the Python in this lesson

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

Give a function a default input

def new_mission(seed=0): gives the parameter a default. new_mission() uses 0. new_mission(17) supplies 17 instead. This lets an ordinary launch work while allowing you to share a repeatable set-up.

Create a private random generator

random.Random(seed) uses the seed to set up an object that produces random-looking choices. Building it inside new_mission starts it afresh on each call. generator.choice([7, 8, 9]) chooses one number from that list. The same seed gives a repeatable choice for the same checkpoint and Python version.

Set up a command-line option

argparse.ArgumentParser(description="Moonbase Rescue") creates the tool that reads the words passed when you launch Python. add_argument("--seed", type=int, default=0) says that --seed is optional, needs an integer when supplied and otherwise uses zero.

Send the chosen number into the game

parser.parse_args() gives back an options object. options.seed reads its seed value. run(options.seed) passes the number into the radio loop, which passes it down again to new_mission(seed). Follow that path to see the number travel from your launch command into the charge calculation.

Keep the save check in step with the rules

A starting charge of nine is possible now. The save validator changes its energy range to 0 <= data["energy"] <= 9 to match. If the validator kept the older upper limit of eight, a legal new mission could fail its own load check.

How the pieces fit The seed comes in before the first radio prompt. Once the game starts, your commands still go through parse_command. This distinction matters when you reproduce a bug using the starting seed and a written route.

Follow one run, step by step
  1. Launch with --seed 17.
    options.seed is the integer 17, and the radio prints Mission seed: 17. Why argparse converts the command-line text using type=int.
  2. Follow run into new_mission.
    A private generator selects the starting charge from 7, 8 and 9. Why The seed passed from run sets the generator’s starting pattern.
  3. Quit and launch the same checkpoint again with --seed 17.
    The opening charge repeats. Why The generator starts over with the same seed and the program makes the same first choice.

Predict before you run Could two different seeds still give Pip the same starting charge?

Reveal the explanation

Yes. A seed sets a sequence, and each sequence’s first pick comes from the same list of three numbers. Different seeds can share that first result.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills random.Random, seeds, argparse, repeatability.

1. Use a private generator for this mission

A seeded generator produces a repeatable sequence of choices when you give it the same seed, use the same code and run it under the same Python version. Set up random.Random(seed) inside the starting function instead of relying on the shared random state. Choose starting energy from 7, 8 and 9 so every roll leaves enough charge for the normal rescue route.

def new_mission(seed=0):
    generator = random.Random(seed)
    charge = generator.choice([7, 8, 9])
    return {"room": "Habitat", "energy": charge, "parts": [], "rescued": False}

2. Read a number from the command line

Use the argparse module to define an optional integer --seed argument. Run python moonbase.py --seed 17 in your local folder. The program prints the seed next to the starting report. If you are pairing with a friend, agree on a seed before comparing energy use or routes.

parser.add_argument("--seed", type=int, default=0)
    options = parser.parse_args()
    run(options.seed)

3. Update the save boundary with the game rule

The greatest legal starting charge is now 9. Update the maximum allowed saved energy as well. This makes a new high-energy run loadable in the same program. Type quit, run again with the same seed and compare the two reports. Two different seeds can still choose the same result because there are only three options.

if type(data["energy"]) is not int or not 0 <= data["energy"] <= 9:
        raise ValueError("bad energy")
    parts = data["parts"]
    if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in parts):
        raise ValueError("unknown part")
    if len(parts) != len(set(parts)):
        raise ValueError("duplicate part")
    if type(data["rescued"]) is not bool:

4. Share one mission

Give someone else your seed and your first three moves. Compare the starting charge and the charge after each move. If the values disagree, check the Python version and the checkpoint first, then check whether one player tried a different route. This is useful when sharing instructions for a difficult mission.

Complete Python checkpoint · moonbase_28.py
import argparse
import random
import json
from pathlib import Path


WORLD = {
    "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None},
    "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"},
    "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"},
    "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None},
}
REQUIRED = {"Coil", "Cell"}
SAVE_FILE = Path("moonbase-save.json")


def new_mission(seed=0):
    generator = random.Random(seed)
    charge = generator.choice([7, 8, 9])
    return {"room": "Habitat", "energy": charge, "parts": [], "rescued": False}


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


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


def collect(state):
    item = WORLD[state["room"]]["part"]
    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, direction):
    destination = WORLD[state["room"]]["exits"].get(direction)
    if destination is None:
        return "That route is blocked."
    if state["energy"] == 0:
        return "Pip is out of energy."
    state["room"] = destination
    state["energy"] -= 1
    return f"Moved to {destination}."


def parse_command(text):
    words = text.lower().split()
    if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
        return "go", words[0]
    if len(words) == 2 and words[0] == "go":
        return "go", words[1]
    if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save", "load"}:
        return words[0], ""
    return "", ""


def save_game(state):
    temporary = SAVE_FILE.with_suffix(".tmp")
    try:
        temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
        temporary.replace(SAVE_FILE)
    except OSError:
        return "Could not save progress. Check that this folder is writable."
    return "Progress saved to moonbase-save.json."


def validate_save(data):
    if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}:
        raise ValueError("expected four state fields")
    if type(data["room"]) is not str or data["room"] not in WORLD:
        raise ValueError("unknown room")
    if type(data["energy"]) is not int or not 0 <= data["energy"] <= 9:
        raise ValueError("bad energy")
    parts = data["parts"]
    if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in parts):
        raise ValueError("unknown part")
    if len(parts) != len(set(parts)):
        raise ValueError("duplicate part")
    if type(data["rescued"]) is not bool:
        raise ValueError("bad rescue flag")
    if data["rescued"] and not can_repair(data["room"], parts):
        raise ValueError("inconsistent rescue")
    return data


def load_game(current):
    try:
        data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
        return validate_save(data), "Saved progress loaded."
    except FileNotFoundError:
        return current, "No save yet; current progress kept."
    except (UnicodeError, json.JSONDecodeError):
        return current, "Save is unreadable; current progress kept."
    except ValueError:
        return current, "Save has invalid data; current progress kept."
    except OSError:
        return current, "Could not open save; current progress kept."


def mission_snapshot(state):
    return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]


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(seed=0):
    state = new_mission(seed)
    print("Moonbase Rescue | Pip on duty")
    print(f"Mission seed: {seed}")
    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 = parse_command(raw)
        if verb == "quit":
            print("Pip is on standby.")
            break
        if verb == "save":
            print(save_game(state))
            continue
        if verb == "load":
            state, message = load_game(state)
            print(message)
            continue
        print(apply(state, verb, argument))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Moonbase Rescue")
    parser.add_argument("--seed", type=int, default=0)
    options = parser.parse_args()
    run(options.seed)

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–24
Line 1 import argparse
Bring in argparse. Its module name gives you access to the tools it contains.
Line 2 import random
Bring in random. Its module name gives you access to the tools it contains.
Line 3 import json
Bring in json. Its module name gives you access to the tools it contains.
Line 4 from pathlib import Path
Bring Path into this file from pathlib. These names can now be used directly.
Lines 7–12 WORLD = { "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None}, "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"}, "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"}, "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 13 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 14 SAVE_FILE = Path("moonbase-save.json")
Work out the value on the right, then store it in SAVE_FILE. Represent a file location so the program can work with it.
Line 17 def new_mission(seed=0):
Define new_mission, a reusable piece of the program. Its input names are seed. The indented body runs when something calls it.
Line 18 generator = random.Random(seed)
Work out the value on the right, then store it in generator. Make an independent random generator. Reusing its seed repeats the sequence.
Line 19 charge = generator.choice([7, 8, 9])
Work out the value on the right, then store it in charge. Pick one entry from the sequence using this random generator.
Line 20 return {"room": "Habitat", "energy": charge, "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 23 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 24 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.
Lines 27–41
Line 27 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 28 room, energy, cargo, _ = mission_snapshot(state)
Give each returned value to the matching name, from left to right. Run mission_snapshot with the supplied inputs and come back here when it returns.
Line 29 exits = ", ".join(WORLD[room]["exits"])
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 30 parts = ", ".join(cargo) 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.
Line 31 return f"{room} | energy {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.
Line 34 def collect(state):
Define collect, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 35 item = WORLD[state["room"]]["part"]
Work out the value on the right, then store it in item. The brackets look up a dictionary key or a position that starts at zero.
Line 36 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 37 return "There is no repair part here."
Leave this function now and hand the result back to the line that called it.
Line 38 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 39 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 40 state["parts"].append(item)
Add the value to the end without replacing the earlier entries.
Line 41 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.
Lines 44–58
Line 44 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 45 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 46 state["rescued"] = True
Work out the value on the right, then store it in state["rescued"].
Line 47 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 48 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 51 def move(state, direction):
Define move, a reusable piece of the program. Its input names are state, direction. The indented body runs when something calls it.
Line 52 destination = WORLD[state["room"]]["exits"].get(direction)
Work out the value on the right, then store it in destination. Look up a key. Use the given fallback, or None, if the key is missing.
Line 53 if destination 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 54 return "That route is blocked."
Leave this function now and hand the result back to the line that called it.
Line 55 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 56 return "Pip is out of energy."
Leave this function now and hand the result back to the line that called it.
Line 57 state["room"] = destination
Work out the value on the right, then store it in state["room"].
Line 58 state["energy"] -= 1
Update state["energy"] in place in the program’s flow: subtract using the value on the right.
Lines 59–75
Line 59 return f"Moved to {destination}."
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 62 def parse_command(text):
Define parse_command, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 63 words = text.lower().split()
Work out the value on the right, then store it in words. Return a lowercase copy so capital letters do not change a command. Separate the string into a list of pieces.
Line 64 if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Line 65 return "go", words[0]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 66 if len(words) == 2 and words[0] == "go":
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. The brackets look up a dictionary key or a position that starts at zero.
Line 67 return "go", words[1]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 68 if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save", "load"}:
Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
Line 69 return words[0], ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
Line 70 return "", ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 73 def save_game(state):
Define save_game, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 74 temporary = SAVE_FILE.with_suffix(".tmp")
Work out the value on the right, then store it in temporary. Build a path with a different ending. This does not rename any file yet.
Line 75 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Lines 76–90
Line 76 temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
Write text to the file using the chosen encoding. Turn Python data into JSON text. This step does not write a file.
Line 77 temporary.replace(SAVE_FILE)
Move the temporary file into the final save location.
Line 78 except OSError:
Run this part only when the try block raises OSError.
Line 79 return "Could not save progress. Check that this folder is writable."
Leave this function now and hand the result back to the line that called it.
Line 80 return "Progress saved to moonbase-save.json."
Leave this function now and hand the result back to the line that called it.
Line 83 def validate_save(data):
Define validate_save, a reusable piece of the program. Its input names are data. The indented body runs when something calls it.
Line 84 if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}:
Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
Line 85 raise ValueError("expected four state fields")
Stop this path and report ValueError("expected four state fields") to whoever called this code.
Line 86 if type(data["room"]) is not str or data["room"] not in WORLD:
Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
Line 87 raise ValueError("unknown room")
Stop this path and report ValueError("unknown room") to whoever called this code.
Line 88 if type(data["energy"]) is not int or not 0 <= data["energy"] <= 9:
Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
Line 89 raise ValueError("bad energy")
Stop this path and report ValueError("bad energy") to whoever called this code.
Line 90 parts = data["parts"]
Work out the value on the right, then store it in parts. The brackets look up a dictionary key or a position that starts at zero.
Lines 91–105
Line 91 if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in parts):
Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
Line 92 raise ValueError("unknown part")
Stop this path and report ValueError("unknown part") to whoever called this code.
Line 93 if len(parts) != len(set(parts)):
Run the indented block only if this check is true. Count the characters or items. Collect distinct values, with no duplicate entries.
Line 94 raise ValueError("duplicate part")
Stop this path and report ValueError("duplicate part") to whoever called this code.
Line 95 if type(data["rescued"]) is not bool:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value. The brackets look up a dictionary key or a position that starts at zero.
Line 96 raise ValueError("bad rescue flag")
Stop this path and report ValueError("bad rescue flag") to whoever called this code.
Line 97 if data["rescued"] and not can_repair(data["room"], parts):
Run the indented block only if this check is true. With and, every check must be true. The brackets look up a dictionary key or a position that starts at zero. The word not reverses which result counts as true.
Line 98 raise ValueError("inconsistent rescue")
Stop this path and report ValueError("inconsistent rescue") to whoever called this code.
Line 99 return data
Leave this function now and hand the result back to the line that called it.
Line 102 def load_game(current):
Define load_game, a reusable piece of the program. Its input names are current. The indented body runs when something calls it.
Line 103 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 104 data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
Work out the value on the right, then store it in data. Read JSON text or bytes and turn it back into Python data. Read a file and decode its contents into text.
Line 105 return validate_save(data), "Saved progress loaded."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run validate_save with the supplied inputs and come back here when it returns.
Lines 106–122
Line 106 except FileNotFoundError:
Run this part only when the try block raises FileNotFoundError.
Line 107 return current, "No save yet; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 108 except (UnicodeError, json.JSONDecodeError):
Run this part only when the try block raises (UnicodeError, json.JSONDecodeError).
Line 109 return current, "Save is unreadable; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 110 except ValueError:
Run this part only when the try block raises ValueError.
Line 111 return current, "Save has invalid data; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 112 except OSError:
Run this part only when the try block raises OSError.
Line 113 return current, "Could not open save; current progress kept."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 116 def mission_snapshot(state):
Define mission_snapshot, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 117 return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero. Collect ordered items in a tuple, whose entries cannot be reassigned.
Line 120 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 121 if verb == "look":
Run the indented block only if this check is true.
Line 122 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.
Lines 123–137
Line 123 if verb == "go":
Run the indented block only if this check is true.
Line 124 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 125 if verb == "take":
Run the indented block only if this check is true.
Line 126 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 127 if verb == "repair":
Run the indented block only if this check is true.
Line 128 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 129 return "Unknown command."
Leave this function now and hand the result back to the line that called it.
Line 132 def run(seed=0):
Define run, a reusable piece of the program. Its input names are seed. The indented body runs when something calls it.
Line 133 state = new_mission(seed)
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 134 print("Moonbase Rescue | Pip on duty")
Show the message or value in the output.
Line 135 print(f"Mission seed: {seed}")
Show the message or value in the output. Python fills the braces with values before it uses the text.
Line 136 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 137 print("Try look, go, take, repair or quit.")
Show the message or value in the output.
Lines 138–150
Line 138 while not state["rescued"]:
Check not state["rescued"] before each pass. Repeat the indented work while it is true.
Line 139 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 140 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 141 except EOFError:
Run this part only when the try block raises EOFError.
Line 142 print("Radio closed.")
Show the message or value in the output.
Line 143 break
Leave the nearest loop immediately and continue after it.
Line 144 verb, argument = parse_command(raw)
Give each returned value to the matching name, from left to right. Run parse_command with the supplied inputs and come back here when it returns.
Line 145 if verb == "quit":
Run the indented block only if this check is true.
Line 146 print("Pip is on standby.")
Show the message or value in the output.
Line 147 break
Leave the nearest loop immediately and continue after it.
Line 148 if verb == "save":
Run the indented block only if this check is true.
Line 149 print(save_game(state))
Show the message or value in the output. Run save_game with the supplied inputs and come back here when it returns.
Line 150 continue
Skip the rest of this pass and start the next loop check.
Lines 151–162
Line 151 if verb == "load":
Run the indented block only if this check is true.
Line 152 state, message = load_game(state)
Give each returned value to the matching name, from left to right. Run load_game with the supplied inputs and come back here when it returns.
Line 153 print(message)
Show the message or value in the output.
Line 154 continue
Skip the rest of this pass and start the next loop check.
Line 155 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 158 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 159 parser = argparse.ArgumentParser(description="Moonbase Rescue")
Work out the value on the right, then store it in parser. Create the object that reads launch options and explains how to use them.
Line 160 parser.add_argument("--seed", type=int, default=0)
Register an option that someone can use when starting the program.
Line 161 options = parser.parse_args()
Work out the value on the right, then store it in options. Read the launch options and put the chosen values into an object.
Line 162 run(options.seed)
Run run with the supplied inputs and come back here when it returns.

Test the mission

  • Start twice with --seed 17 and compare the starting energy.
  • Run at least five seed values and note which produce the same battery charge.
  • Collect a Cell, save, relaunch with a different seed, and load your progress.

If something goes wrong

Changing the seed always gives different energy in the test notes.
Different seeds can still choose the same battery value. Compare repeated runs with the same seed first.

Mission extension

Add a second seeded choice for a harmless radio message. Keep at least 7 energy on every route.