Skip to content
Python project #18Intermediate

Text Adventure: The Lost Library

Explore rooms, collect items, unlock a door, light a dark vault and escape with the treasure in a classic command-driven adventure.

Estimated time
~3 hours to build
Files
4 files · 372 lines
Technologies
Python 3, dataclasses

Introduction

Text adventures are a fun way to practise data modelling: rooms are objects with exits and items, the player has an inventory, and commands change the state of the world. Small rules — a locked door, a dark room — create a puzzle.

Problem statement

Model five connected rooms with descriptions, exits and items. Support look, movement (go north or n/s/e/w/u/d), take, drop, inventory, read, help and quit. The vault is locked until the player carries the brass key and dark until they carry both the candle and matches. Bringing the golden manuscript back to the entrance hall wins the game and reports the number of moves.

Objectives

  • Model a world with dataclasses and dictionaries
  • Parse simple verb-noun commands
  • Implement rules that depend on state
  • Keep game state in a class

Features

  • Five rooms with exits and items
  • Locked door and dark room puzzles
  • Inventory with take, drop and read
  • Direction shortcuts
  • Move counter and win condition

Concepts demonstrated

  • State machines
  • Command parsing
  • Data-driven design
  • Encapsulation

System architecture

build_world returns a dictionary of Room objects, each with exits mapping directions to room keys. Game tracks the current room, inventory, moves and whether the game is finished; lit is a property that is true when both light sources are carried. go checks exits and locks, take respects darkness, and command maps verbs to methods.

Folder structure

TextProject tree
text-adventure-game/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

155 lines
Pythonmain.py
"""The Lost Library: a small text adventure.
Find the brass key, light your way, collect the golden manuscript from the vault and
return to the entrance hall. Commands: look, go <direction> (or n/s/e/w/u/d), take <item>,
drop <item>, inventory, read <item>, help, quit.
"""
import sys
from dataclasses import dataclass, field
DIRECTIONS = {"n": "north", "s": "south", "e": "east", "w": "west", "u": "up", "d": "down"}
@dataclass
class Room:
name: str
description: str
exits: dict[str, str]
items: list[str] = field(default_factory=list)
dark: bool = False
locked_by: str | None = None
def build_world() -> dict[str, Room]:
return {
"hall": Room("Entrance Hall", "Dusty portraits line the walls. A grand staircase leads up.",
{"north": "reading", "east": "kitchen", "up": "gallery"}),
"reading": Room("Reading Room", "Rows of desks face a fireplace. A heavy door stands to the north.",
{"south": "hall", "north": "vault"}, ["candle"]),
"kitchen": Room("Old Kitchen", "Copper pots hang above a cold stove.", {"west": "hall"}, ["matches", "apple"]),
"gallery": Room("Gallery", "Moonlight falls on empty frames. Something glints under a bench.",
{"down": "hall"}, ["brass key", "note"]),
"vault": Room("Vault", "Shelves of locked cases. In the centre, a glass box holds a golden manuscript.",
{"south": "reading"}, ["golden manuscript"], dark=True, locked_by="brass key"),
}
READABLE = {
"note": "The note says: 'The vault opens for brass, but sees only by flame.'",
"golden manuscript": "Gold letters spell out: 'Knowledge is the only treasure that grows when shared.'",
}
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip().lower()
class Game:
def __init__(self):
self.rooms = build_world()
self.here = "hall"
self.inventory: list[str] = []
self.moves = 0
self.finished = False
@property
def lit(self) -> bool:
return "candle" in self.inventory and "matches" in self.inventory
def describe(self) -> None:
room = self.rooms[self.here]
print(f"\n== {room.name} ==")
if room.dark and not self.lit:
print("It is pitch dark. You can't see a thing.")
return
print(room.description)
if room.items:
print(f"You see: {', '.join(room.items)}.")
print(f"Exits: {', '.join(room.exits)}.")
def go(self, direction: str) -> None:
direction = DIRECTIONS.get(direction, direction)
target = self.rooms[self.here].exits.get(direction)
if not target:
print("You can't go that way.")
return
room = self.rooms[target]
if room.locked_by and room.locked_by not in self.inventory:
print("The heavy door is locked.")
return
if room.locked_by:
print(f"You unlock the door with the {room.locked_by}.")
room.locked_by = None
self.here = target
self.moves += 1
self.describe()
if self.here == "hall" and "golden manuscript" in self.inventory:
print(f"\nYou carry the golden manuscript out into the daylight. You win in {self.moves} moves!")
self.finished = True
def take(self, item: str) -> None:
room = self.rooms[self.here]
if room.dark and not self.lit:
print("You fumble around in the dark but find nothing.")
elif item in room.items:
room.items.remove(item)
self.inventory.append(item)
print(f"Taken: {item}.")
else:
print(f"There is no {item} here.")
def drop(self, item: str) -> None:
if item not in self.inventory:
print(f"You don't have {item}.")
return
self.inventory.remove(item)
self.rooms[self.here].items.append(item)
print(f"Dropped: {item}.")
def command(self, line: str) -> bool:
verb, _, rest = line.partition(" ")
if verb in DIRECTIONS or verb in DIRECTIONS.values():
self.go(verb)
elif verb == "go" and rest:
self.go(rest)
elif verb == "look":
self.describe()
elif verb in ("take", "get") and rest:
self.take(rest)
elif verb == "drop" and rest:
self.drop(rest)
elif verb in ("inventory", "i"):
print(f"You carry: {', '.join(self.inventory) or 'nothing'}.")
elif verb == "read" and rest:
print(READABLE.get(rest, "There is nothing to read on that.") if rest in self.inventory else f"You don't have {rest}.")
elif verb == "help":
print("Commands: look, go <dir>, n/s/e/w/u/d, take <item>, drop <item>, inventory, read <item>, quit")
elif verb == "quit":
return False
else:
print("I don't understand that. Type 'help'.")
return not self.finished
def main() -> None:
game = Game()
print("THE LOST LIBRARY")
game.describe()
while True:
line = ask("> ")
if line is None or not game.command(line):
break
if not game.finished:
print(f"You leave the library after {game.moves} moves. The manuscript remains hidden.")
if __name__ == "__main__":
main()

What each file does

main.py
The world definition, the Game class with its rules and the command loop.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
THE LOST LIBRARY
== Entrance Hall ==
Dusty portraits line the walls. A grand staircase leads up.
Exits: north, east, up.
> look
== Entrance Hall ==
Dusty portraits line the walls. A grand staircase leads up.
Exits: north, east, up.
> n
== Reading Room ==
Rows of desks face a fireplace. A heavy door stands to the north.
You see: candle.
Exits: south, north.
> take candle
Taken: candle.
> n
The heavy door is locked.
> s
== Entrance Hall ==
Dusty portraits line the walls. A grand staircase leads up.
Exits: north, east, up.
> s
You can't go that way.
> u
== Gallery ==
Moonlight falls on empty frames. Something glints under a bench.
You see: brass key, note.
Exits: down.
> take brass key
Taken: brass key.
> take note
Taken: note.
> read note
The note says: 'The vault opens for brass, but sees only by flame.'
> d
== Entrance Hall ==
Dusty portraits line the walls. A grand staircase leads up.
Exits: north, east, up.
> e
== Old Kitchen ==
Copper pots hang above a cold stove.
You see: matches, apple.
Exits: west.
> take matches
Taken: matches.
> take spoon
There is no spoon here.
> dance
I don't understand that. Type 'help'.
> w
== Entrance Hall ==
Dusty portraits line the walls. A grand staircase leads up.
Exits: north, east, up.
> n
== Reading Room ==
Rows of desks face a fireplace. A heavy door stands to the north.
Exits: south, north.
> n
You unlock the door with the brass key.
== Vault ==
Shelves of locked cases. In the centre, a glass box holds a golden manuscript.
You see: golden manuscript.
Exits: south.
> take golden manuscript
Taken: golden manuscript.
> inventory
You carry: candle, brass key, note, matches, golden manuscript.
> s
== Reading Room ==
Rows of desks face a fireplace. A heavy door stands to the north.
Exits: south, north.
> s
== Entrance Hall ==
Dusty portraits line the walls. A grand staircase leads up.
Exits: north, east, up.
You carry the golden manuscript out into the daylight. You win in 10 moves!
Input
look
n
take candle
n
s
s
u
take brass key
take note
read note
d
e
take matches
take spoon
dance
w
n
n
take golden manuscript
inventory
s
s

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • The first attempt to go north from the reading room finds the door locked.
  • Reading the note gives the clue about brass and flame; 'take spoon' and 'dance' give friendly messages.
  • With the key, candle and matches the vault opens and is lit, and returning with the manuscript wins in 10 moves.

Common errors

Items can be taken in the dark room

Check room.dark and the lit property before allowing take.

Typing 'north' doesn't work but 'n' does

Map shortcuts to full names with the DIRECTIONS dictionary and accept both.

Possible improvements

  • Load the world from a JSON file
  • Add a save/load command
  • Add characters who give hints

Additional challenges

  1. 1Add a time limit: the candle burns out after 15 moves.
  2. 2Add a score for items found.
  3. 3Generate a map of visited rooms.

Built and tested it yourself? Mark it to update your dashboard.