Building a Text Adventure Game
Turn words into worlds: rooms, an inventory, and choices that matter
input, if / elif / else, loops, lists, dictionaries, and functions -- to build one small, complete game.
- store a map of rooms in a dictionary,
- show a room and read the player's move with
input, - move from room to room using
if/elif/else, - keep an inventory in a list,
- run the game with a
whileloop and end it with win / lose conditions, - tidy the code into small functions.
1. What is a text adventure?
Think of a choose-your-own-adventure book. You read a page, then it says "to open the door, turn to page 12; to run away, turn to page 30." You decide what happens next. A text adventure game is the same idea, but the computer keeps the pages and turns them for you.
Every text adventure has three simple parts:
- Rooms -- the places you can be, each with a description and a set of exits.
- The player -- where you are right now, and what you are carrying.
- The loop -- show the room, ask for a move, react, and repeat until you win or lose.
We will build these one piece at a time. The good news: you already know every tool we need. We are just putting them together.
2. The map: rooms in a dictionary
A dictionary stores things by name. That is perfect for a map: each room has a name, a description, and a list of exits. We can even nest a small dictionary of exits inside each room.
rooms = {
"Hall": {
"desc": "You are in a bright entrance hall.",
"exits": {"north": "Kitchen", "east": "Library"}
},
"Kitchen": {
"desc": "A warm kitchen. Something smells nice.",
"exits": {"south": "Hall"}
},
"Library": {
"desc": "Tall shelves full of dusty books.",
"exits": {"west": "Hall"}
}
}
Read it like a table of contents. rooms["Hall"] gives you the Hall's information. rooms["Hall"]["exits"] gives just its exits: {"north": "Kitchen", "east": "Library"}. So standing in the Hall and going north takes you to the Kitchen.
rooms[0]), which is easy to muddle. With a dictionary you look them up by their real name (rooms["Kitchen"]), which reads like plain English.