Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Projects
  3. Build a Text Adventure in Python

Project 7 · Guided build

Build a Text Adventure in Python

Create a branching story with rooms, inventory, choices, and win conditions using dictionaries and functions.

Open the compilerWarm-up exercises
intermediate90–120 minutesdictionariesfunctionsstate managementinput loops
On this page
  1. What you will build
  2. State
  3. Movement
  4. Looking around
  5. Taking items
  6. The command loop
  7. Running in ILoveCompiler
  8. Design notes
  9. Stretch goals

A text adventure is a state machine with a story. Each room has a description, exits, and possibly an item. The player moves between rooms, picks up items, and tries to reach a goal.

What you will build#

A small adventure with four rooms:

  • Hall: the starting room, with a key.
  • Library: contains a locked door to the vault.
  • Vault: the goal, reachable only with the key.
  • Cellar: a dead end with a lamp.

Commands: look, go <direction>, take <item>, inventory, help, and quit.

State#

Python
rooms = {
    "hall": {
        "description": "A dusty hall. A key hangs by the door.",
        "exits": {"east": "library", "down": "cellar"},
        "item": "key",
    },
    "library": {
        "description": "Shelves of old books line the walls.",
        "exits": {"west": "hall", "north": "vault"},
        "locked": {"north": "key"},
    },
    "cellar": {
        "description": "A cold cellar with a broken lamp.",
        "exits": {"up": "hall"},
    },
    "vault": {
        "description": "A small vault. A chest sits in the corner.",
        "exits": {"south": "library"},
        "goal": True,
    },
}

current_room = "hall"
inventory = []

The locked mapping means the exit in that direction requires the named item. Keep the rule data-driven so the movement function stays short.

Movement#

Python
def move(direction):
    global current_room

    room = rooms[current_room]
    target = room["exits"].get(direction)

    if target is None:
        print("You cannot go that way.")
        return

    lock = room.get("locked", {}).get(direction)
    if lock and lock not in inventory:
        print(f"The door is locked. You need a {lock}.")
        return

    current_room = target
    look()

Using global is acceptable for a small script, but the cleaner design keeps current_room and inventory in a player dictionary and returns a new state from functions. Try both to compare.

Looking around#

Python
def look():
    room = rooms[current_room]
    print()
    print(room["description"])

    item = room.get("item")
    if item:
        print(f"You see: {item}.")

    directions = ", ".join(room["exits"])
    print(f"Exits: {directions}")

Only describe what is present. Do not reveal the vault's contents before the player enters.

Taking items#

Python
def take(item_name):
    room = rooms[current_room]
    item = room.get("item")

    if item is None:
        print("There is nothing to take.")
        return
    if item_name.lower() != item:
        print(f"You do not see a {item_name}.")
        return

    inventory.append(item)
    del room["item"]
    print(f"You take the {item}.")

Removing the item from the room prevents taking it twice.

The command loop#

Python
def play():
    print("Type 'help' for commands.")
    look()

    while True:
        raw = input("> ").strip()
        if not raw:
            continue

        parts = raw.split()
        command = parts[0].lower()

        if command == "quit":
            print("Goodbye.")
            break
        elif command == "look":
            look()
        elif command == "help":
            print("Commands: look, go <direction>, take <item>, inventory, quit")
        elif command == "inventory":
            print("Inventory:", ", ".join(inventory) if inventory else "empty")
        elif command == "go":
            if len(parts) < 2:
                print("Go where?")
            else:
                move(parts[1].lower())
        elif command == "take":
            if len(parts) < 2:
                print("Take what?")
            else:
                take(" ".join(parts[1:]))
        else:
            print("I do not understand that command.")

        if rooms[current_room].get("goal"):
            print("You found the vault. You win!")
            break

The win check runs after every command. It also triggers after a second look, which is harmless but slightly repetitive. Move the check into move() if you want to announce the win only when entering the room.

Running in ILoveCompiler#

Supply one command per line in the Input panel. For example:

Expected output

help look take key go east go north look quit

If you try go north before taking the key, the program should refuse. Test that branch by changing the order.

Design notes#

  • Keep room descriptions in data, not in long if chains.
  • Validate commands without crashing on missing arguments.
  • Make failure messages specific: "You need a key" is better than "You can't do that".
  • Do not print hidden state or future room contents.

Stretch goals#

  • Add a lantern that reveals a dark basement.
  • Add a monster that blocks an exit until the player has a torch.
  • Add a save format as JSON text.
  • Support drop <item> and a carry limit.
  • Add a scoring system based on rooms visited and items collected.
Previous projectBuild a Password Generator in PythonNext projectBuild a Weather Data Analyzer in Python

On this page

  1. What you will build
  2. State
  3. Movement
  4. Looking around
  5. Taking items
  6. The command loop
  7. Running in ILoveCompiler
  8. Design notes
  9. Stretch goals

Project checklist

  • Read the requirements.
  • Plan the data model.
  • Build one feature at a time.
  • Test invalid input.
  • Refactor after it works.