Skip to content

Text adventure

Explore an old house by typing commands, pick things up, and find the treasure.

Start here: open pygwide. On the home page, choose Tutorials, then Python Toolkit, then Lesson 6: Text adventure.

This lesson takes about an hour. The extensions take about 30 minutes more.

What you will learn

  • How to plan a bigger program, made from functions.
  • How to understand commands the player types, with .startswith(), .replace() and .strip().
  • How to use dictionaries, lists, functions and loops together.

What you need from before

Step 1: The map

The starter project already has the house written out for you, in a dictionary called rooms. Each room has:

  • a "description", which the player reads,
  • its "exits", a dictionary of which room each direction leads to, and
  • an "item" to pick up, or "" if there is nothing.

Draw a map of the house on paper, with a box for each room and arrows for the exits. Where is the treasure?

Step 2: Describe a room

After the rooms, make a variable for the room the player is in, a list for what they carry, and a function that describes a room:

room = "hall"
inventory = []
playing = True


def describe(room):
    print()
    print(rooms[room]["description"])
    item = rooms[room]["item"]
    if item != "":
        print(f"You can see a {item}.")

Step 3: The game loop

The game repeats while playing is True. Each time, it asks for a command. .lower() makes it small letters, and .strip() takes away any spaces at either end:

print("THE OLD HOUSE")
print("Find the treasure!")
print("Type go and a direction, take, inventory or quit.")
describe(room)

while playing:
    command = input("> ").lower().strip()
    if command == "inventory":
        print(f"You are carrying: {inventory}")
    elif command == "quit":
        playing = False
    else:
        print("I don't understand. Try go north, take, inventory or quit.")

Run it, and try inventory and quit.

Step 4: Moving

Add a function, before the game loop, that works out which room a direction leads to. If there's no exit that way, the player stays where they are:

def go(direction):
    exits = rooms[room]["exits"]
    if direction not in exits:
        print("You can't go that way.")
        return room
    return exits[direction]

Then, in the loop, check for commands that start with go. .replace("go ", "") takes go off the front, leaving the direction:

    if command.startswith("go "):
        new_room = go(command.replace("go ", ""))
        if new_room != room:
            room = new_room
            describe(room)
    elif command == "inventory":
        print(f"You are carrying: {inventory}")

Explore the house!

Step 5: Picking things up

Add a function that takes the item in the room, if there is one, and adds it to the inventory. Then set the room's item to "", so it's gone:

def take():
    item = rooms[room]["item"]
    if item == "":
        print("There is nothing here to take.")
    else:
        inventory.append(item)
        rooms[room]["item"] = ""
        print(f"You take the {item}.")

Add an elif command == "take": to the loop that calls take().

Step 6: The locked cellar and the treasure

The cellar should be locked until you have the key. In go(), replace the last line, return exits[direction], with these lines:

    next_room = exits[direction]
    if next_room == "cellar" and "key" not in inventory:
        print("The cellar door is locked. You need a key.")
        return room
    return next_room

Last of all, at the end of the loop, indented inside it, end the game when the player has the treasure:

    if "treasure" in inventory:
        print("You found the treasure! You win!")
        playing = False

Check your code

# Text adventure

rooms = {
    "hall": {
        "description": "You are in a dusty hall. Doors lead north and east.",
        "exits": {"north": "library", "east": "kitchen"},
        "item": "",
    },
    "library": {
        "description": "Old books cover every wall. A door leads south.",
        "exits": {"south": "hall"},
        "item": "key",
    },
    "kitchen": {
        "description": "Pans hang from the ceiling. Doors lead west and down to the cellar.",
        "exits": {"west": "hall", "down": "cellar"},
        "item": "torch",
    },
    "cellar": {
        "description": "It is cold and damp down here. Stairs lead up.",
        "exits": {"up": "kitchen"},
        "item": "treasure",
    },
}

room = "hall"
inventory = []
playing = True


def describe(room):
    print()
    print(rooms[room]["description"])
    item = rooms[room]["item"]
    if item != "":
        print(f"You can see a {item}.")


def go(direction):
    exits = rooms[room]["exits"]
    if direction not in exits:
        print("You can't go that way.")
        return room
    next_room = exits[direction]
    if next_room == "cellar" and "key" not in inventory:
        print("The cellar door is locked. You need a key.")
        return room
    return next_room


def take():
    item = rooms[room]["item"]
    if item == "":
        print("There is nothing here to take.")
    else:
        inventory.append(item)
        rooms[room]["item"] = ""
        print(f"You take the {item}.")


print("THE OLD HOUSE")
print("Find the treasure!")
print("Type go and a direction, take, inventory or quit.")
describe(room)

while playing:
    command = input("> ").lower().strip()
    if command.startswith("go "):
        new_room = go(command.replace("go ", ""))
        if new_room != room:
            room = new_room
            describe(room)
    elif command == "take":
        take()
    elif command == "inventory":
        print(f"You are carrying: {inventory}")
    elif command == "quit":
        playing = False
    else:
        print("I don't understand. Try go north, take, inventory or quit.")

    if "treasure" in inventory:
        print("You found the treasure! You win!")
        playing = False

Extensions

Save and load

Add save and load commands, so a player can stop and carry on later. Use json from Lesson 5 to save the room, the inventory and the rooms, which change as items are taken, in one dictionary.

One way to do it
# Text adventure, with save and load
import json

SAVE_FILE = "save.json"

rooms = {
    "hall": {
        "description": "You are in a dusty hall. Doors lead north and east.",
        "exits": {"north": "library", "east": "kitchen"},
        "item": "",
    },
    "library": {
        "description": "Old books cover every wall. A door leads south.",
        "exits": {"south": "hall"},
        "item": "key",
    },
    "kitchen": {
        "description": "Pans hang from the ceiling. Doors lead west and down to the cellar.",
        "exits": {"west": "hall", "down": "cellar"},
        "item": "torch",
    },
    "cellar": {
        "description": "It is cold and damp down here. Stairs lead up.",
        "exits": {"up": "kitchen"},
        "item": "treasure",
    },
}

room = "hall"
inventory = []
playing = True


def describe(room):
    print()
    print(rooms[room]["description"])
    item = rooms[room]["item"]
    if item != "":
        print(f"You can see a {item}.")


def go(direction):
    exits = rooms[room]["exits"]
    if direction not in exits:
        print("You can't go that way.")
        return room
    next_room = exits[direction]
    if next_room == "cellar" and "key" not in inventory:
        print("The cellar door is locked. You need a key.")
        return room
    return next_room


def take():
    item = rooms[room]["item"]
    if item == "":
        print("There is nothing here to take.")
    else:
        inventory.append(item)
        rooms[room]["item"] = ""
        print(f"You take the {item}.")


def save():
    game = {"room": room, "inventory": inventory, "rooms": rooms}
    with open(SAVE_FILE, "w") as file:
        json.dump(game, file)
    print("Game saved.")


def load():
    try:
        with open(SAVE_FILE) as file:
            return json.load(file)
    except FileNotFoundError:
        return {}


print("THE OLD HOUSE")
print("Find the treasure!")
print("Type go and a direction, take, inventory, save, load or quit.")
describe(room)

while playing:
    command = input("> ").lower().strip()
    if command.startswith("go "):
        new_room = go(command.replace("go ", ""))
        if new_room != room:
            room = new_room
            describe(room)
    elif command == "take":
        take()
    elif command == "inventory":
        print(f"You are carrying: {inventory}")
    elif command == "save":
        save()
    elif command == "load":
        game = load()
        if len(game) == 0:
            print("There is no saved game yet.")
        else:
            room = game["room"]
            inventory = game["inventory"]
            rooms = game["rooms"]
            print("Game loaded.")
            describe(room)
    elif command == "quit":
        playing = False
    else:
        print("I don't understand. Try go north, take, inventory, save, load or quit.")

    if "treasure" in inventory:
        print("You found the treasure! You win!")
        playing = False

Make it bigger

Add more rooms of your own, with exits that join them to the house. Can you add a room that is too dark to see in without the torch?

Extra bits

You've finished Python Toolkit!

You can now use lists, functions, strings, dictionaries and files. These are the tools real programmers use every day. Next, you'll use them to make games and apps with Pygame Zero.

Export your project

pygwide keeps your work in this web browser, but club computers can forget it. Press ⇩ Export to save your project as a zip file. Keep it somewhere safe, such as a USB stick or your school drive.

Next time, choose ⇪ Import a project on the home page to carry on with it.