Escape the Glitching Space Station

Build a replayable Python terminal game and escape a failing space station.

Introduction

30 Second Summary

Choice-based stories feel tense when every decision changes what happens next. A typo can ruin that tension if the story accepts it as a real choice.

In this project, you will build a replayable terminal space adventure with Python. Your commands will steer an astronaut through a failing station while a limited oxygen supply decides the ending.

What You'll Build

When you run station_escape.py, you will watch each command steer your astronaut toward escape or defeat.

By the end of this project, you'll have:

  • Choices that matter as every route or escape decision reduces your oxygen supply.
  • Clear command feedback that rejects invalid entries before the story continues.
  • A replayable astronaut adventure with a newly selected station hazard on every attempt.
  • Secret Mission: Award successful astronauts a survivor rank based on the oxygen they preserve.

Are there any prerequisites?

Your Linux coding setup already has every required tool installed. A small amount of coding exposure is enough to start.

Before We Start

Before you enter the station, take a moment to connect the replayable escape game with the Python skills you want to build. This gives your mission a clear purpose before you start coding.

Confirm the Cockpit

A terminal game only works when the editor sends your code to the Python version you expect. Before you build any game logic, you need proof that Visual Studio Code is connected to Python 3.14.7.

The Microsoft Python extension connects the editor to that interpreter. A one-line startup check proves the whole path works.

In this step, get ready to:
  • Open python-space-escape as your Visual Studio Code workspace.
  • Confirm Visual Studio Code uses Python 3.14.7.
  • Run station_escape.py to display the station startup message.
Prepare the game workspace

A workspace gives every file in your game one clear home. You will keep this entire project inside python-space-escape on your Desktop.

  • Open your Linux applications menu.
  • Search for Visual Studio Code.
  • Select Visual Studio Code from the search results.

You will see Visual Studio Code's welcome screen. Your editor is ready for a dedicated game workspace.

  • Click File in the top menu.
  • Select Open Folder.
  • Choose your Desktop in the folder picker.
  • Use the folder-creation control to create python-space-escape.
  • Select python-space-escape.
  • Confirm the selection to open the folder as your workspace.

Your file sidebar now shows python-space-escape as the active workspace. Your game has a clear home.

Match VS Code to Python

The integrated terminal checks the Python installation available on your Linux device. The interpreter setting controls which installation Visual Studio Code uses to run your file.

  • Select Terminal in the top menu.
  • Choose the option that creates a new integrated terminal.
  • Check the installed Python version by running this command:
python3 --version

What does this command check?

  • The python3 command targets your installed Python 3 interpreter.
  • The --version flag asks the interpreter to report its installed version.

You should see Python 3.14.7. That confirms the required Python installation is available.

The interpreter setting is easy to miss because Visual Studio Code shows it in the bottom status bar. Selecting it now keeps every later run consistent.

  • Open Visual Studio Code's command search from the top menu.
  • Enter Python: Select Interpreter.
  • Choose the interpreter that reports Python 3.14.7.
  • Check the bottom status bar to confirm the selected interpreter uses Python 3.14.7.

Visual Studio Code now points to the same Python version confirmed in your terminal. Your editor is ready to run the game.

Version does not match?

  • Rerun the version command above to confirm the terminal still reports the expected installation.
  • Confirm the Microsoft Python extension is available.
  • Run Python: Select Interpreter again.

Help me diagnose why Visual Studio Code is using the wrong Python interpreter. You can also share a screenshot of the terminal with the NextWork community.

Produce the first station signal

A startup message gives you immediate proof that your file reaches the selected interpreter. The built-in print function sends that message to the terminal.

  • Create a new file named station_escape.py from Visual Studio Code's file sidebar.

You will see station_escape.py in the file sidebar. Visual Studio Code also opens it in the editor.

  • Make the file produce a visible system check by entering this code:
print("SPACE STATION SYSTEM ONLINE")

What does this startup check do?

  • The print function writes the startup string to the terminal.
  • The SPACE STATION SYSTEM ONLINE string acts as your first visible station status signal.
  • Save station_escape.py.

Before you run it, predict the exact station message that the terminal should show.

  • Select Run Python File in Terminal from the play menu in the top-right corner of the editor.

You will see SPACE STATION SYSTEM ONLINE in the terminal. Your first Python file now runs through the correct interpreter.

Startup message missing?

  • Confirm station_escape.py is saved.
  • Confirm station_escape.py is the active editor tab.
  • Check that the line contains the exact startup string shown above.

Help me diagnose why my Python startup message is missing from the VS Code terminal.

✔️ My cockpit check is complete

Your saved station_escape.py now contains the startup check that produced the terminal message.

ⓧ I'd like to double check the full code

  • Compare your saved station_escape.py with this complete checkpoint file:
print("SPACE STATION SYSTEM ONLINE")

Your cockpit is ready. Next, you will replace the system check with the first player-controlled escape scene.

Make the First Escape Choice

Your station startup message proves that station_escape.py runs with the selected Python interpreter.

A game needs to react to the player. This intentionally simple route choice lets you test whether unrestricted input handles every command safely.

This first version stores player input in variables. A conditional uses those values to decide which scene runs.

In this step, get ready to:
  • Replace the startup message with a title, an astronaut name, and an oxygen supply.
  • Normalize the route command and branch between the lab and tunnel scenes.
  • Test a valid command and an invalid command to expose a flaw in the route logic.
Store the astronaut and oxygen state

The astronaut name and oxygen supply form the game's state. Each variable gives later decisions a value to read or change.

  • In station_escape.py, select the existing print("SPACE STATION SYSTEM ONLINE") line.
  • Replace the selected line with the opening scene by pasting this code:
print("\n=== ESCAPE THE GLITCHING SPACE STATION ===")
name = input("Astronaut, what is your name? ").strip()
oxygen = 50
print(f"\nWelcome, {name}. Oxygen remaining: {oxygen}.")

What Does This Opening Scene Do?

  • The first print call displays the game title.
  • The input() call collects the astronaut name as a string.
  • .strip() removes extra space from the start or end of the name.
  • The oxygen variable starts at 50.
  • The f-string places the current name and oxygen values inside the welcome message.
  • Save station_escape.py.
  • Select Run Python File in Terminal in the editor toolbar.
  • Enter Nova at the astronaut prompt.

You'll see the game title followed by a welcome message that uses Nova and shows 50 oxygen.

Missing the Welcome Message?

  • Confirm that the old startup line has been completely replaced by the four new lines.
  • Check that the final line starts with the letter f before the opening quote.
  • Save station_escape.py before running it again.

Still stuck? Help me find why my Python game does not show the astronaut name or oxygen value.

Branch between station routes

The route command controls which oxygen cost the game applies. Normalizing the command gives the comparison a consistent lowercase value without surrounding spaces.

  • In station_escape.py, place the route scene on a blank line below print(f"\nWelcome, {name}. Oxygen remaining: {oxygen}.") by pasting this code:
route = input("Choose a route: [lab] or [tunnel]: ").strip().lower()

if route == "lab":
    oxygen = oxygen - 10
    print("You cross the frozen lab. It costs 10 oxygen.")
else:
    oxygen = oxygen - 15
    print("You crawl through the maintenance tunnel. It costs 15 oxygen.")

print(f"Oxygen remaining: {oxygen}.")

How Does the Route Decision Work?

  • The route variable stores the player's command.
  • .strip().lower() removes surrounding spaces before converting the command to lowercase.
  • if route == "lab": checks whether the normalized command matches lab.
  • The lab branch subtracts 10 from oxygen.
  • The else branch handles the remaining route in this first version. It subtracts 15 from oxygen.
  • Save station_escape.py.
  • Select Run Python File in Terminal in the editor toolbar.
  • Enter Nova at the astronaut prompt.
  • Enter lab at the route prompt.

You'll see You cross the frozen lab. It costs 10 oxygen. followed by Oxygen remaining: 40..

The valid lab route now updates the oxygen supply correctly.

Does the Lab Command Reach the Tunnel?

  • Check that the comparison uses route == "lab" with two equals signs.
  • Confirm that the two lines under if route == "lab": use four spaces of indentation.
  • Make sure .strip().lower() remains at the end of the route input line.

Need a hand? Help me debug why entering lab does not run the frozen lab branch.

✔️ Awesome, I've got everything!

Great. Confirm that station_escape.py is saved and the lab route leaves 40 oxygen.

ⓧ I'd like to double check the full code

  • Compare station_escape.py with this full file:
print("\n=== ESCAPE THE GLITCHING SPACE STATION ===")
name = input("Astronaut, what is your name? ").strip()
oxygen = 50
print(f"\nWelcome, {name}. Oxygen remaining: {oxygen}.")

route = input("Choose a route: [lab] or [tunnel]: ").strip().lower()

if route == "lab":
    oxygen = oxygen - 10
    print("You cross the frozen lab. It costs 10 oxygen.")
else:
    oxygen = oxygen - 15
    print("You crawl through the maintenance tunnel. It costs 15 oxygen.")

print(f"Oxygen remaining: {oxygen}.")
Test an invalid command

The route works for the listed lab choice. This final check probes what happens when the player enters a command that the prompt never offered.

Before you run the game, picture which route scene banana is most likely to reach.

  • Select Run Python File in Terminal in the editor toolbar.
  • Enter Nova at the astronaut prompt.
  • Enter banana at the route prompt.

You'll see You crawl through the maintenance tunnel. It costs 15 oxygen. followed by Oxygen remaining: 35..

That incorrect tunnel scene is the intended shortfall. Your test has exposed a real command-handling bug.

  • Compare the 35 oxygen total with the 40 oxygen total from the lab run.

Why Did Banana Reach the Tunnel?

The if route == "lab": condition recognizes only lab.

The else branch receives every other string. That includes tunnel, banana, and any typo.

You caught the command-handling gap with a repeatable test. Next, you'll build a reusable validation loop that stops unrecognized commands before the story continues.

Stop Bad Commands at the Airlock

Your previous run in Visual Studio Code exposed the route bug. The command banana entered the tunnel branch.

A reusable function can protect every command prompt. Its loop checks each answer against an allowed list before the story continues.

In this step, get ready to:
  • Create a reusable get_choice() function that keeps asking for an allowed command.
  • Connect the route prompt to the allowed choices: lab or tunnel.
  • Prove that banana receives a correction before lab continues the story.
Build the reusable choice checker

The checker receives a prompt plus the choices it accepts. while True repeats until return sends an allowed answer back to the game.

  • In station_escape.py, place this code above the first print() call:
def get_choice(prompt, valid_choices):
    """Keep asking until the player enters an allowed command."""
    while True:
        choice = input(prompt).strip().lower()
        if choice in valid_choices:
            return choice

        choices_text = ", ".join(valid_choices)
        print(f"Command not recognized. Choose: {choices_text}.")

What does this function do?

  • The prompt parameter holds the question shown to the player.
  • The valid_choices parameter holds the commands that the game accepts.
  • input(prompt) collects the player's response.
  • .strip() removes surrounding spaces.
  • .lower() converts the response to lowercase.
  • choice in valid_choices checks whether the normalized command belongs to the allowed list.
  • return choice ends the loop when the command is valid.
  • ", ".join(valid_choices) builds readable correction text from the allowed choices.
Connect the route to validation

The route still calls input() directly. The new checker is currently bypassed.

  • In station_escape.py, find the route assignment directly below the welcome message.
  • Select the full line that starts with route = input(.
  • Replace the selected line with this function call:
route = get_choice(
    "Choose a route: [lab] or [tunnel]: ",
    ["lab", "tunnel"],
)

How does the route use the checker?

  • get_choice() receives the existing route prompt.
  • ["lab", "tunnel"] limits the values that the function can return.
  • The route decision receives a valid command every time.
Test the corrected airlock

The strongest test starts with the command that failed in the previous version. The route prompt must reject that command before accepting a valid one.

Before you run the game, do you expect banana to reach the tunnel branch or make the route prompt repeat?

  • Save station_escape.py.
  • Click Run Python File in Terminal in the top-right corner of the editor.
  • Enter Nova at the astronaut name prompt.
  • Enter banana at the route prompt.
  • Enter lab when the route prompt appears again.

You'll first see Command not recognized. Choose: lab, tunnel. after banana. The route prompt repeats.

After lab, you'll see You cross the frozen lab. It costs 10 oxygen. followed by Oxygen remaining: 40..

You fixed the silent route bug. Invalid commands now stay at the airlock until the player enters an allowed choice.

Still taking the tunnel after banana?

  • Confirm that the route assignment starts with route = get_choice(.
  • Check that def get_choice(prompt, valid_choices): starts at the far-left edge of the editor.
  • Confirm that the lines inside get_choice() use consistent four-space indentation.

Still stuck? Help me debug why banana still reaches the tunnel branch.

✔️ Awesome, I've got everything!

Your file now contains the reusable checker plus the validated route call.

ⓧ I'd like to double check the full code

  • Compare your station_escape.py file with this complete reference:
def get_choice(prompt, valid_choices):
    """Keep asking until the player enters an allowed command."""
    while True:
        choice = input(prompt).strip().lower()
        if choice in valid_choices:
            return choice

        choices_text = ", ".join(valid_choices)
        print(f"Command not recognized. Choose: {choices_text}.")


print("\n=== ESCAPE THE GLITCHING SPACE STATION ===")
name = input("Astronaut, what is your name? ").strip()
oxygen = 50
print(f"\nWelcome, {name}. Oxygen remaining: {oxygen}.")

route = get_choice(
    "Choose a route: [lab] or [tunnel]: ",
    ["lab", "tunnel"],
)

if route == "lab":
    oxygen = oxygen - 10
    print("You cross the frozen lab. It costs 10 oxygen.")
else:
    oxygen = oxygen - 15
    print("You crawl through the maintenance tunnel. It costs 15 oxygen.")

print(f"Oxygen remaining: {oxygen}.")

How is the file organized?

The get_choice() function handles every route response before the game scene begins.

The route scene receives a valid choice. Its existing oxygen calculation can continue unchanged.

Your route prompt now blocks typos before they can change oxygen. Next, you'll add an unpredictable hazard to make each escape attempt feel different.

Add an Unpredictable Hazard

Your route input now rejects invalid commands before the astronaut moves. Every route choice has a clear meaning.

Every valid attempt still follows the same route scene. A predictable station quickly stops feeling dangerous.

In this step, Python's standard-library random module adds random selection to the game. A new function returns the changed oxygen level after one hazard.

In this step, get ready to:
  • Define face_hazard(oxygen) with three description-and-cost pairs.
  • Use random.choice(hazards) to update the astronaut's oxygen.
  • Run repeated attempts to observe one selected hazard each time.
Create the hazard function

A list can hold several candidate events in one place. Each tuple pairs a hazard description with the amount of oxygen it removes.

Why use Python's random module?

The standard-library module already comes with Python. It gives this game unpredictable selection without another package to install.

  • In station_escape.py, locate the blank line after the get_choice(prompt, valid_choices) function.
  • Paste the hazard function into that blank line:
def face_hazard(oxygen):
    """Choose a random hazard and return the updated oxygen level."""
    hazards = [
        ("a coolant pipe bursts beside you", 5),
        ("a security drone mistakes you for an intruder", 15),
        ("the gravity generator throws debris across the corridor", 25),
    ]

    description, oxygen_cost = random.choice(hazards)
    print(f"\nHazard: {description}!")
    oxygen = oxygen - oxygen_cost
    print(f"You lose {oxygen_cost} oxygen. Oxygen remaining: {oxygen}.")
    return oxygen

What does this function do?

  • The hazards list stores three possible events. Each event has its own oxygen cost.
  • random.choice(hazards) selects one tuple. Python unpacks its parts into description and oxygen_cost.
  • The function subtracts the selected cost from oxygen. Its return value carries the updated total back to the game.
  • Save station_escape.py.
  • Run the current game by selecting Run Python File in Terminal in the editor.

You should reach the route result and see the oxygen remaining line. That confirms Python accepted the new function definition.

Seeing a syntax or indentation problem?

  • Make sure def face_hazard(oxygen): starts at the left edge of the file.
  • Use four spaces for every line inside face_hazard(oxygen).
  • Check that every hazard tuple has a description followed by its oxygen cost.

Still stuck? Help me fix the hazard function.

Connect the hazard to each run

The function needs access to the random module when the game calls it. The game also needs to store the oxygen value that the function returns.

  • In station_escape.py, place your cursor above def get_choice(prompt, valid_choices):.
  • Add the import so the top of the file matches this reference:
import random


def get_choice(prompt, valid_choices):

What does the import provide?

import random makes the standard-library module available throughout station_escape.py. The hazard function can now call random.choice(hazards) when it runs.

  • Scroll to the final print(f"Oxygen remaining: {oxygen}.") line.
  • Add the function call below that line so the bottom of the file matches this reference:
print(f"Oxygen remaining: {oxygen}.")
oxygen = face_hazard(oxygen)

Why assign the returned value?

face_hazard(oxygen) receives the current oxygen level. Assigning its result back to oxygen ensures later game decisions use the reduced total.

  • Save station_escape.py.

Before you run the game again, which part of the hazard do you expect to vary between attempts?

  • Select Run Python File in Terminal.
  • Enter an astronaut name at the first prompt.
  • Enter lab at the route prompt.

You'll see exactly one Hazard: line after the route result. The following line reports the oxygen cost and the new total.

Missing the hazard output?

  • Check that import random is the first line in station_escape.py.
  • Check that oxygen = face_hazard(oxygen) appears below the final route oxygen line.
  • Make sure the function call starts at the left edge instead of sitting inside the route condition.

Still stuck? Help me restore the missing hazard output.

Test repeated hazard runs

One successful run proves the function is connected to the route scene. Several attempts reveal how random selection behaves.

Before the next attempts, do you expect Python to cycle through the hazards in a fixed order?

  • Select Run Python File in Terminal for each of three attempts.
  • Enter an astronaut name in each attempt.
  • Enter lab during each route choice.

Each attempt shows one hazard with its oxygen cost. The oxygen remaining line reflects both the route cost and the selected hazard cost.

You may see the same hazard more than once. Random selection can choose the same tuple across separate runs.

✔️ Awesome, I've got everything!

Your game now displays one selected hazard after every valid route. The updated oxygen total appears directly below it.

ⓧ I'd like to double check the full code

import random


def get_choice(prompt, valid_choices):
    """Keep asking until the player enters an allowed command."""
    while True:
        choice = input(prompt).strip().lower()
        if choice in valid_choices:
            return choice

        choices_text = ", ".join(valid_choices)
        print(f"Command not recognized. Choose: {choices_text}.")


def face_hazard(oxygen):
    """Choose a random hazard and return the updated oxygen level."""
    hazards = [
        ("a coolant pipe bursts beside you", 5),
        ("a security drone mistakes you for an intruder", 15),
        ("the gravity generator throws debris across the corridor", 25),
    ]

    description, oxygen_cost = random.choice(hazards)
    print(f"\nHazard: {description}!")
    oxygen = oxygen - oxygen_cost
    print(f"You lose {oxygen_cost} oxygen. Oxygen remaining: {oxygen}.")
    return oxygen


print("\n=== ESCAPE THE GLITCHING SPACE STATION ===")
name = input("Astronaut, what is your name? ").strip()
oxygen = 50
print(f"\nWelcome, {name}. Oxygen remaining: {oxygen}.")

route = get_choice(
    "Choose a route: [lab] or [tunnel]: ",
    ["lab", "tunnel"],
)

if route == "lab":
    oxygen = oxygen - 10
    print("You cross the frozen lab. It costs 10 oxygen.")
else:
    oxygen = oxygen - 15
    print("You crawl through the maintenance tunnel. It costs 15 oxygen.")

print(f"Oxygen remaining: {oxygen}.")
oxygen = face_hazard(oxygen)

What should this file contain?

The import sits at the top of the file. The hazard function follows get_choice(prompt, valid_choices), while its function call sits after the route scene.

Your station now delivers an unpredictable threat on every attempt. Next, you'll turn this scene into a complete replayable escape.

Complete and Replay the Escape

The random hazard now changes every run. However, each attempt stops before your astronaut reaches the escape pod.

A function will own one complete attempt. A replay loop will start a fresh attempt until the player chooses to stop.

In this step, get ready to:
  • Move one complete attempt into play_game().
  • Add the escape choice with its oxygen-based outcome.
  • Build the replay loop for fresh attempts.
Move one attempt into play_game()

The play_game() function gives one attempt its own local variables. That boundary keeps each attempt's changing state together.

  • Locate the top-level print("\n=== ESCAPE THE GLITCHING SPACE STATION ===") line in station_escape.py.
  • Select from that line through oxygen = face_hazard(oxygen).
  • Replace the selection by pasting this code:
def play_game():
    """Run one complete escape attempt."""
    print("\n=== ESCAPE THE GLITCHING SPACE STATION ===")
    name = input("Astronaut, what is your name? ").strip()
    if not name:
        name = "Rookie"

    oxygen = 50
    print(f"\nWelcome, {name}. Oxygen remaining: {oxygen}.")

    route = get_choice(
        "Choose a route: [lab] or [tunnel]: ",
        ["lab", "tunnel"],
    )

    if route == "lab":
        oxygen = oxygen - 10
        print("You cross the frozen lab. It costs 10 oxygen.")
    else:
        oxygen = oxygen - 15
        print("You crawl through the maintenance tunnel. It costs 15 oxygen.")

    print(f"Oxygen remaining: {oxygen}.")
    oxygen = face_hazard(oxygen)


play_game()

What does this function change?

  • The play_game() function creates a local scope for one attempt's state.
  • The empty-name check uses Rookie when the player submits a blank name.
  • The final play_game() call starts the function so you can test the new structure.
  • Save station_escape.py.
  • Click Run Python File in Terminal in the editor toolbar.
  • Press Enter at the astronaut name prompt.
  • Enter lab at the route prompt.

You'll see Welcome, Rookie. Oxygen remaining: 50. before the route choice. One hazard then updates the oxygen total.

Game does not start?

  • Check that def play_game(): starts at the left edge of the editor.
  • Check that every line inside play_game() uses four spaces of indentation.
  • Check that the temporary play_game() call at the bottom is not indented.

Still stuck? Help me fix the structure of my play_game function.

Finish the escape decision

The escape method applies one final oxygen cost. A second conditional converts the remaining oxygen into a win or loss.

  • Locate oxygen = face_hazard(oxygen) inside play_game().
  • Add the escape decision directly below that line by pasting this code:
    escape_method = get_choice(
        "\nEscape pod access: [override] or [vent]: ",
        ["override", "vent"],
    )

    if escape_method == "override":
        oxygen = oxygen - 10
        print("You override the pod controls. It costs 10 oxygen.")
    else:
        oxygen = oxygen - 20
        print("You squeeze through the emergency vent. It costs 20 oxygen.")

How does the escape choice work?

  • The get_choice() call accepts only override or vent.
  • The override branch subtracts 10 oxygen.
  • The vent branch subtracts 20 oxygen.
  • Save station_escape.py.
  • Click Run Python File in Terminal.
  • Enter Nova at the astronaut name prompt.
  • Enter lab at the route prompt.
  • Enter override at the escape pod prompt.

You'll see the escape pod prompt after the hazard. The selected method then prints its oxygen cost.

Escape prompt missing?

  • Check that escape_method remains indented inside play_game().
  • Check that the escape block appears before the temporary play_game() call.

Need another pair of eyes? Help me find why the escape prompt is missing.

  • Place the cursor after print("You squeeze through the emergency vent. It costs 20 oxygen.").
  • Add the final outcome below the escape-cost conditional by pasting this code:
    if oxygen > 0:
        print(f"\nYou escaped, {name}, with {oxygen} oxygen left!")
    else:
        print(f"\nThe pod seals too late, {name}. The station wins this round.")

How is the outcome decided?

  • The condition oxygen > 0 checks whether the astronaut has any oxygen left.
  • A positive total prints the escape message with the astronaut's name.
  • A total of zero or below prints the failed escape message.
  • Save station_escape.py.
  • Click Run Python File in Terminal.
  • Enter Nova at the astronaut name prompt.
  • Enter lab at the route prompt.
  • Enter override at the escape pod prompt.

You'll see the escape message after the final oxygen cost. The exact oxygen total depends on the randomly selected hazard.

That is one full attempt working from the name prompt to the final outcome. The remaining job is to let the player launch again.

Seeing the wrong outcome?

  • Check that the winning condition is exactly if oxygen > 0:.
  • Check that both outcome messages remain inside play_game().
  • Check that the else: line aligns with if oxygen > 0:.

Still unsure? Help me debug my oxygen-based ending.

Add the replay loop

The main() function coordinates complete attempts. Its while True loop repeats until break stops it after a no response.

  • Select the temporary play_game() call at the bottom of station_escape.py.
  • Replace that call by pasting this replay code:
def main():
    """Replay the game until the player chooses to stop."""
    while True:
        play_game()
        again = get_choice(
            "\nPlay again? [yes] or [no]: ",
            ["yes", "no"],
        )
        if again == "no":
            print("Mission ended. See you next launch!")
            break


main()

How does replay work?

  • The while True loop keeps the game ready for another attempt.
  • Each play_game() call creates a new name prompt with oxygen reset to 50.
  • The get_choice() call restricts replay responses to yes or no.
  • The break statement exits the loop when the player chooses no.
  • Save station_escape.py.

Before you run the finished game, do you expect choosing yes to keep the old oxygen total or start a fresh attempt?

  • Click Run Python File in Terminal.
  • Enter Nova at the astronaut name prompt.
  • Enter lab at the route prompt.
  • Enter override at the escape pod prompt.
  • Enter yes at the first replay prompt.

You'll see the game title followed by a new astronaut name prompt. The fresh attempt starts with oxygen reset to 50.

  • Enter Orion at the new astronaut name prompt.
  • Enter tunnel at the route prompt.
  • Enter vent at the escape pod prompt.
  • Enter no at the replay prompt.

You'll see Mission ended. See you next launch! after the second attempt. The terminal then returns to its normal prompt.

Mission complete. Your game now supports full escape attempts with fresh state on every replay.

Replay does not stop?

  • Check that again = get_choice( sits inside the while True loop.
  • Check that if again == "no": compares the response with lowercase no.
  • Check that break remains inside the replay condition.

Need help tracing the loop? Help me debug why my replay loop does not stop.

✔️ Awesome, I've got everything!

Your saved game can complete an attempt, start another round, and stop after a no response.

ⓧ I'd like to double check the full code

  • Compare station_escape.py with this completed version:
import random


def get_choice(prompt, valid_choices):
    """Keep asking until the player enters an allowed command."""
    while True:
        choice = input(prompt).strip().lower()
        if choice in valid_choices:
            return choice

        choices_text = ", ".join(valid_choices)
        print(f"Command not recognized. Choose: {choices_text}.")


def face_hazard(oxygen):
    """Choose a random hazard and return the updated oxygen level."""
    hazards = [
        ("a coolant pipe bursts beside you", 5),
        ("a security drone mistakes you for an intruder", 15),
        ("the gravity generator throws debris across the corridor", 25),
    ]

    description, oxygen_cost = random.choice(hazards)
    print(f"\nHazard: {description}!")
    oxygen = oxygen - oxygen_cost
    print(f"You lose {oxygen_cost} oxygen. Oxygen remaining: {oxygen}.")
    return oxygen


def play_game():
    """Run one complete escape attempt."""
    print("\n=== ESCAPE THE GLITCHING SPACE STATION ===")
    name = input("Astronaut, what is your name? ").strip()
    if not name:
        name = "Rookie"

    oxygen = 50
    print(f"\nWelcome, {name}. Oxygen remaining: {oxygen}.")

    route = get_choice(
        "Choose a route: [lab] or [tunnel]: ",
        ["lab", "tunnel"],
    )

    if route == "lab":
        oxygen = oxygen - 10
        print("You cross the frozen lab. It costs 10 oxygen.")
    else:
        oxygen = oxygen - 15
        print("You crawl through the maintenance tunnel. It costs 15 oxygen.")

    print(f"Oxygen remaining: {oxygen}.")
    oxygen = face_hazard(oxygen)

    escape_method = get_choice(
        "\nEscape pod access: [override] or [vent]: ",
        ["override", "vent"],
    )

    if escape_method == "override":
        oxygen = oxygen - 10
        print("You override the pod controls. It costs 10 oxygen.")
    else:
        oxygen = oxygen - 20
        print("You squeeze through the emergency vent. It costs 20 oxygen.")

    if oxygen > 0:
        print(f"\nYou escaped, {name}, with {oxygen} oxygen left!")
    else:
        print(f"\nThe pod seals too late, {name}. The station wins this round.")


def main():
    """Replay the game until the player chooses to stop."""
    while True:
        play_game()
        again = get_choice(
            "\nPlay again? [yes] or [no]: ",
            ["yes", "no"],
        )
        if again == "no":
            print("Mission ended. See you next launch!")
            break


main()

Secret mission

Secret Mission: Award a Survivor Rank

Escaping the station is only part of the story. Extend the ending so each successful astronaut earns a survivor rank based on the oxygen they preserve.

Clean Up Your Resources

Clean Up Your Resources

Your game runs entirely on your device. Choose whether to keep the files, pause your work, or delete the project with no ongoing cost to consider.

Resources you used:

  • The local python-space-escape folder, including station_escape.py.

Keep everything running

No action needed. Choose this if you want to keep developing or replaying your game.

  • Keep the python-space-escape folder wherever you created it.
  • Return to station_escape.py whenever you want to replay or extend the game.

Pause - I'll come back to this later

Shut down any active game session to free memory. Your code stays ready for your next visit.

  • Enter no when the replay prompt appears if a game attempt is still running.
  • Close Visual Studio Code with your Linux window controls.
  • Leave the python-space-escape folder on your device for later.

Delete - I don't want to use this again

Remove all local project files from your device.

Deleting the folder is permanent. The command below targets only python-space-escape.

  • Switch back to the integrated terminal from earlier.
  • Confirm that the terminal is inside python-space-escape by running this command:
pwd

The pwd command prints the terminal's current folder. Continue when the output ends with /python-space-escape.

  • Move to the parent folder and delete the project by running these commands:
cd ..
rm -rf python-space-escape

The cd .. command moves the terminal to the parent folder. The rm -rf python-space-escape command removes the project folder and everything inside it.

Your Python installation and Visual Studio Code remain unchanged.

  • Confirm that the project folder is gone by running this command:
ls

The ls command lists the contents of the parent folder. You should no longer see python-space-escape.

Nice Work!

Nice Work!

Mission complete! You built a replayable space-station adventure in Python that responds to player decisions through changing oxygen totals.

You've learned how to:

  • Built a replayable terminal game where astronaut choices determine the final oxygen total.
  • Experienced a broken input path before fixing it with an input-validation loop that rejects unknown commands.
  • Organized random hazards inside focused functions. Passed updated oxygen values back with return values.
  • Completed the optional Secret Mission by awarding each successful astronaut an oxygen-based survivor rank.

Ready to quiz yourself?