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#
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#
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#
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#
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#
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!")
breakThe 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:
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
ifchains. - 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.
