Project: Text adventure
Project: Text adventure
- You build the start of a text adventure: rooms, exits, and a player who walks around.
- The map is a dictionary of dictionaries: each room has a text and its exits.
- You use dictionaries,
in, functions and a loop.
What you will build
You are in a dark hall.
> north
A kitchen. It smells of bread.
> south
You are in a dark hall.
> east
Books everywhere. A cat is sleeping.
Step 1: a dictionary inside a dictionary
rooms["hall"]is the hall's own dictionary.- So
rooms["hall"]["text"]is its text, androoms["hall"]["exits"]is its exits.

rooms = {"hall": {"text": "A dark hall.", "exits": {"north": "kitchen"}}}
print(rooms["hall"]["text"])
print(rooms["hall"]["exits"]["north"])
Step 2: is there a door?
key in dictionaryisTruewhen the dictionary has that key.- Check it before you read the key, or Python stops with a
KeyError.
Step 3: follow a list of directions
- Keep the current room in a variable.
- For each direction, replace it with the room
movereturns. - Return the variable after the loop.
Play for real
- Type
north,south,eastorwest, andquitto stop.
rooms = {
"hall": {"text": "You are in a dark hall.", "exits": {"north": "kitchen", "east": "library"}},
"kitchen": {"text": "A kitchen. It smells of bread.", "exits": {"south": "hall"}},
"library": {"text": "Books everywhere. A cat is sleeping.", "exits": {"west": "hall"}},
}
room = "hall"
print(rooms[room]["text"])
command = input("> ")
while command != "quit":
exits = rooms[room]["exits"]
if command in exits:
room = exits[command]
print(rooms[room]["text"])
else:
print("You cannot go that way.")
command = input("> ")
Now build it
- Three steps, each a function. Then add your own rooms to the map and play.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Step 1: rooms is a dictionary of rooms. Write describe(room) that returns the room's text. describe("hall") returns "You are in a dark hall."
Nhấn Chạy để xem kết quả ở đây.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Step 2: write move(room, direction) that returns the room you reach by going that way. If the room has no exit in that direction, return the same room. move("hall", "north") là (is) "kitchen"; move("hall", "west") là (is) "hall".
Nhấn Chạy để xem kết quả ở đây.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Step 3: write walk(start, directions) that starts in the room start, follows every direction in the list with move, and returns the room where you end up. walk("hall", ["north", "south", "east"]) là (is) "library".
Nhấn Chạy để xem kết quả ở đây.