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".
実行ボタンをクリックして出力を確認してください。