处理用户输入
本课属于 Coddy Lua 学习旅程的“逻辑与流程”单元。第 28 课,共 54 课。
挑战
简单扩展游戏循环,使用 io.read() 读取并显示用户命令。
你已获得上一道挑战中的 startingRoom、gardenRoom 和 player 变量。
修改游戏循环,使其执行以下操作:
- 打印玩家当前所在房间的描述
- 打印提示符
"> "(大于号后跟一个空格),且不换行:使用io.write()而不是print(),因为io.write()输出文本时不会在末尾添加换行符 - 使用
io.read()读取用户的命令 - 打印
"You entered: ",后面跟上用户输入的命令 - 检查命令是否为
"quit",如果是,则将gameRunning设置为false,以退出循环
循环应持续运行,直到用户输入 "quit"。
预期输出格式:
You find yourself in a dusty library filled with ancient books and scrolls.
> You entered: look
You find yourself in a dusty library filled with ancient books and scrolls.
> You entered: east
You find yourself in a dusty library filled with ancient books and scrolls.
> You entered: quit亲手试试
-- 游戏房间
local startingRoom = {
description = "You find yourself in a dusty library filled with ancient books and scrolls."
}
local gardenRoom = {
description = "You step into a beautiful garden with blooming flowers and a gentle breeze."
}
-- 玩家
local player = {
currentRoom = startingRoom
}
-- 游戏循环
local gameRunning = true
-- TODO: 在这里编写 while 循环
逻辑与流程中的所有课
自己练习: Lua 在线编译器