Project: Text adventure
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
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.
English
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.
English
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.

English
rooms = {"hall": {"text": "A dark hall.", "exits": {"north": "kitchen"}}}
print(rooms["hall"]["text"])
print(rooms["hall"]["exits"]["north"])
English
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.
English
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.
English
Play for real
- Type
north,south,eastorwest, andquitto stop.
English
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("> ")
English
Now build it
- Three steps, each a function. Then add your own rooms to the map and play.
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Step 1: rooms is a dictionary of rooms. Write describe(room) that 返回值 the room's text. describe("hall") 返回值 "You are in a dark hall."
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Step 2: write move(room, direction) that 返回值 the room you reach by going that way. If the room has no exit in that direction, return the same room. move("hall", "north") is(是) "kitchen"; move("hall", "west") is(是) "hall".
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Step 3: write walk(start, directions) that starts in the room start, follows every direction in the list with move, and 返回值 the room where you end up. walk("hall", ["north", "south", "east"]) is(是) "library".
点击“运行”查看此处输出。