Intermediate · Console Apps · Packages: standard library only
Project 20: Text Adventure Game
Build a data-driven text adventure with rooms, items, a locked gate, a dark cellar and a command parser. Explore, collect a key and reach the vault.
What you will learn
- Model a game world with nested dictionaries and lists
- Write a command parser that turns typed text into actions
- Use a class to keep game state (room, inventory, moves)
- Read commands with input() and handle EOFError safely
Prerequisites
- Variables, strings and string methods (split, lower)
- Lists and dictionaries
- Functions and if/elif logic
- Classes and methods basics
- while loops and input()
Packages and installation
Packages: standard library only.
Project structure
text_adventure/
main.pyStep-by-step build
- Design the world. Write the ROOMS dictionary. Each room has a description, exits (direction to room name) and a list of items. Data first, logic later.
- Create the Game class. Store the current room, inventory, move counter and the set of opened gates in __init__.
- Write look(). Return the room description, the items and the exits. If the room is dark and you have no lamp, return a dark message instead.
- Add movement. go() checks the exit exists, checks if it is locked, then changes self.room. A key in the inventory opens the gate.
- Add take, drop and eat. Move items between the room list and the inventory. Respect the MAX_CARRY limit.
- Write the parser. handle() splits the line into a verb and an argument and calls the right method. Add short forms like n, s, e, w.
- Write the main loop. Loop until the player wins. Catch EOFError so the game also works with piped input.
- Play it. Run python3 main.py and type commands, or pipe a file of commands into it.
Complete source code
"""Text Adventure Game: a small data-driven adventure you play by typing commands."""
import sys
# World data: every room is a dictionary. Exits map a direction to a room name.
ROOMS = {
"cellar": {
"desc": "A damp stone cellar. Moss covers the walls. A ladder leads up.",
"exits": {"up": "hall"},
"items": ["lamp"],
},
"hall": {
"desc": "A dusty hall with portraits. Doors lead north and east. Stairs go down.",
"exits": {"down": "cellar", "north": "library", "east": "garden"},
"items": [],
},
"library": {
"desc": "Shelves of old books fill this room. A small brass key lies on a desk.",
"exits": {"south": "hall"},
"items": ["key", "book"],
},
"garden": {
"desc": "An overgrown garden. A heavy iron gate to the east is locked.",
"exits": {"west": "hall", "east": "vault"},
"items": ["apple"],
"locked": {"east": "key"}, # direction -> item needed to pass
},
"vault": {
"desc": "A glittering vault full of gold. You found the treasure!",
"exits": {"west": "garden"},
"items": [],
},
}
DARK_ROOMS = {"cellar"} # you need the lamp to see here
MAX_CARRY = 3
class Game:
def __init__(self):
self.room = "cellar"
self.inventory = []
self.moves = 0
self.won = False
self.unlocked = set() # (room, direction) pairs already opened
# ---- helpers -------------------------------------------------------
def is_dark(self):
return self.room in DARK_ROOMS and "lamp" not in self.inventory
def look(self):
if self.is_dark():
return "It is pitch dark. You cannot see anything."
room = ROOMS[self.room]
text = room["desc"]
if room["items"]:
text += "\nYou see: " + ", ".join(room["items"]) + "."
text += "\nExits: " + ", ".join(sorted(room["exits"])) + "."
return text
# ---- commands ------------------------------------------------------
def go(self, direction):
room = ROOMS[self.room]
if direction not in room["exits"]:
return "You can't go that way."
need = room.get("locked", {}).get(direction)
if need and (self.room, direction) not in self.unlocked:
if need in self.inventory:
self.unlocked.add((self.room, direction))
print(f"You unlock the way with the {need}.")
else:
return f"The way {direction} is locked. You need a {need}."
self.room = room["exits"][direction]
self.moves += 1
if self.room == "vault":
self.won = True
return self.look()
def take(self, item):
# You can feel around for the lamp even in the dark.
if self.is_dark() and item != "lamp":
return "It is too dark to find anything."
room = ROOMS[self.room]
if item not in room["items"]:
return f"There is no {item} here."
if len(self.inventory) >= MAX_CARRY:
return "Your hands are full. Drop something first."
room["items"].remove(item)
self.inventory.append(item)
return f"You take the {item}."
def drop(self, item):
if item not in self.inventory:
return f"You don't have a {item}."
self.inventory.remove(item)
ROOMS[self.room]["items"].append(item)
return f"You drop the {item}."
def eat(self, item):
if item != "apple" or item not in self.inventory:
return "You have nothing like that to eat."
self.inventory.remove(item)
return "Crunch! Tasty."
def show_inventory(self):
if not self.inventory:
return "You carry nothing."
return "You carry: " + ", ".join(self.inventory) + "."
def handle(self, line):
"""Turn one typed line into a reply string."""
words = line.lower().split()
if not words:
return "Say something."
verb, arg = words[0], " ".join(words[1:])
# Allow shortcuts such as "n" for "go north".
short = {"n": "north", "s": "south", "e": "east", "w": "west",
"u": "up", "d": "down"}
if verb in short:
verb, arg = "go", short[verb]
if verb == "go" and arg:
return self.go(arg)
if verb == "look":
return self.look()
if verb in ("take", "get") and arg:
return self.take(arg)
if verb == "drop" and arg:
return self.drop(arg)
if verb == "eat" and arg:
return self.eat(arg)
if verb in ("inventory", "i"):
return self.show_inventory()
if verb == "help":
return "Commands: go <dir>, n/s/e/w/u/d, look, take, drop, eat, inventory, quit"
return "I don't understand that. Type 'help'."
def main():
game = Game()
print("=== The Hidden Vault ===")
print("Type 'help' for commands.\n")
print(game.look())
while not game.won:
try:
line = input("> ")
except EOFError:
print("\nThe input ended. Goodbye!")
return
if line.strip().lower() == "quit":
print("You give up. Goodbye!")
return
print(game.handle(line))
print(f"\nYou won in {game.moves} moves with {len(game.inventory)} item(s)!")
if __name__ == "__main__":
main()
Code explanation
ROOMS data
The world is just data. Adding a room means adding a dictionary entry, with no change to the game logic. The optional 'locked' key maps a direction to the item needed.
The Game class
State lives in one object. Methods return strings and main() prints them, which keeps the logic easy to test.
Dark rooms
is_dark() returns True in a room from DARK_ROOMS when the lamp is not carried. look() and take() check it. The lamp is the one thing you can feel for in the dark, so the game can be won.
Parsing commands
line.lower().split() gives words. The first word is the verb and the rest is the argument. A dictionary of shortcuts rewrites 'n' into ('go', 'north').
Locked gate
The set self.unlocked remembers opened gates as (room, direction) pairs, so the key is only needed once.
Expected output
=== The Hidden Vault ===
Type 'help' for commands.
It is pitch dark. You cannot see anything.
> It is pitch dark. You cannot see anything.
> It is too dark to find anything.
> You take the lamp.
> A damp stone cellar. Moss covers the walls. A ladder leads up.
Exits: up.
> I don't understand that. Type 'help'.
> A dusty hall with portraits. Doors lead north and east. Stairs go down.
Exits: down, east, north.
> Shelves of old books fill this room. A small brass key lies on a desk.
You see: key, book.
Exits: south.
> You take the key.
> You take the book.
> There is no apple here.
> There is no gold here.
> There is no lamp here.
> You drop the book.
> You carry: lamp, key.
> A dusty hall with portraits. Doors lead north and east. Stairs go down.
Exits: down, east, north.
> An overgrown garden. A heavy iron gate to the east is locked.
You see: apple.
Exits: east, west.
> You unlock the way with the key.
A glittering vault full of gold. You found the treasure!
Exits: west.
You won in 5 moves with 2 item(s)!
Common errors and solutions
Solution: An exit points to a room name that is not in ROOMS. Check the spelling of each exit.
Solution: Wrap input() in try/except EOFError, as main() does, so piped input does not crash the game.
Solution: Always remove the item from one list before appending to the other.
Solution: Compare lowercase text. Call line.lower() before checking verbs.
Ideas to improve the project
- Save and load the game with the json module
- Add monsters or a simple combat system
- Load rooms from a JSON file
- Add a score and a turn limit
- Support two-word item names like 'brass key'