项目:文字冒险游戏
此页面需较新浏览器(支持 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("> ")
开始动手
- 一共三步,每一步写一个函数。然后给地图加上你自己的房间,玩一玩。
难度 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"。
点击“运行”查看此处输出。