显示出口
本课属于 Coddy Lua 学习旅程的“逻辑与流程”单元。第 31 课,共 54 课。
挑战
简单显示房间描述后,向玩家展示所有可用出口,提升游戏体验。
你可以使用上一关中的 startingRoom、gardenRoom 和 player 变量。
修改游戏循环,显示可用出口:
- 打印玩家当前所在房间的描述
- 在新的一行打印
"Exits:" - 使用
pairs()遍历当前房间的exits表 - 对于每个出口,先打印
" - "(两个空格、一个短横线和一个空格),再打印方向名称 - 打印提示符
"> "(大于号后跟一个空格),不换行 - 使用
io.read()读取用户的命令 - 检查该命令是否与当前房间
exits表中的某个键匹配 - 如果匹配,将
player.currentRoom更新为该出口对应的房间 - 如果该命令与任何出口都不匹配,且不是
"quit",则打印"You can't go that way." - 如果命令是
"quit",则将gameRunning设置为false,以退出循环
循环应持续运行,直到用户输入 "quit"。
预期输出格式:
You find yourself in a dusty library filled with ancient books and scrolls.
Exits:
- east
>
A hidden garden with overgrown plants and a small fountain.
Exits:
- west
>
You can't go that way.
A hidden garden with overgrown plants and a small fountain.
Exits:
- west
>
You find yourself in a dusty library filled with ancient books and scrolls.
Exits:
- east
> 亲手试试
-- Room definitions
local startingRoom = {
description = "You find yourself in a dusty library filled with ancient books and scrolls.",
exits = {}
}
local gardenRoom = {
description = "A hidden garden with overgrown plants and a small fountain.",
exits = {}
}
-- Connect rooms
startingRoom.exits["north"] = gardenRoom
gardenRoom.exits["south"] = startingRoom
-- Player
local player = {
currentRoom = startingRoom
}
-- Game loop
local gameRunning = true
while gameRunning do
print(player.currentRoom.description)
io.write("> ")
local command = io.read()
if command == "quit" then
gameRunning = false
elseif player.currentRoom.exits[command] then
player.currentRoom = player.currentRoom.exits[command]
else
print("You can't go that way.")
end
end逻辑与流程中的所有课
自己练习: Lua 在线编译器