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".
출력을 보려면 '실행'을 클릭하세요.