プロジェクト: テキストアドベンチャー
このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
プロジェクト: テキストアドベンチャー
- テキストアドベンチャースタートを作ります: 部屋、出口、そして歩き回るプレイヤー。
- マップは 辞書の辞書 です: 各部屋にはテキストとその出口があります。
- 辞書、
in、関数、そしてループを使います。
作成するもの
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.
ステップ1: 辞書の中の辞書
rooms["hall"]は廊下の自身の辞書です。- つまり
rooms["hall"]["text"]はそのテキストで、rooms["hall"]["exits"]はその出口です。
English
rooms = {"hall": {"text": "A dark hall.", "exits": {"north": "kitchen"}}}
print(rooms["hall"]["text"])
print(rooms["hall"]["exits"]["north"])
ステップ2: 扉があるか?
key in dictionary在字典中存在该键时返回True。- キーを読む 前 に確認しないと、Python は
KeyErrorを発生させて停止します。
ステップ3: 方向のリストに従う
- 現在の部屋を変数に保持します。
- 各方向に対して、
moveが返す部屋に置き換えます。 - ループ後に変数を返します。
本番で遊ぶ
north、south、east、またはwestを入力し、quitで終了します。
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("> ")
今、作ってみましょう
- 3つのステップ、それぞれが関数です。次にマップに自分の部屋を追加して遊びます。
難易度 4/5 · 280 コイン + 今日初回達成時の小ボーナス
ステップ1: roomsは部屋の辞書である。describe(room)を記述して部屋のテキストを返す。describe("hall")は"You are in a dark hall."を返す。
実行ボタンをクリックして出力を確認してください。
難易度 4/5 · 280 コイン + 今日初回達成時の小ボーナス
ステップ 2: その方向に進むことで到達する部屋を返す move(room, direction) を書きます。その方向に出口がない場合は同じ部屋を返します。move("hall", "north") は "kitchen" ;move("hall", "west") は "hall" です。
実行ボタンをクリックして出力を確認してください。
難易度 4/5 · 280 コイン + 今日初回達成時の小ボーナス
ステップ 3:walk(start, directions) を書き、部屋 start に始まり、リスト move に含まれるすべての方向に従って移動し、最終的に到達した部屋の位置を返す。walk("hall", ["north", "south", "east"]) は "library" である。
実行ボタンをクリックして出力を確認してください。