Menu
CoddyTech

处理无效移动

本课属于 Coddy Lua 学习旅程的“逻辑与流程”单元。第 30 课,共 54 课。

challenge icon

挑战

简单

为移动系统添加错误处理,在玩家输入无效方向时提供反馈。

你会获得上一关中的 startingRoom、gardenRoom 和 player 变量。

修改游戏循环,以处理无效的移动命令:

  • 将上一关中的东/西出口替换为 北/南出口:将 startingRoom.exits["north"] 设为 gardenRoom,并将 gardenRoom.exits["south"] 设为 startingRoom
  • 打印玩家当前所在房间的描述
  • 打印提示符 "> "(大于号后跟一个空格),且不换行
  • 使用 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.
> A hidden garden with overgrown plants and a small fountain.
> You can't go that way.
A hidden garden with overgrown plants and a small fountain.
> You find yourself in a dusty library filled with ancient books and scrolls.
> 

亲手试试

-- 房间定义
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 = {}
}

-- TODO:用南北方向的出口连接房间

-- 玩家
local player = {
    currentRoom = startingRoom
}

-- 游戏循环
local gameRunning = true

-- TODO:在这里编写 while 循环

逻辑与流程中的所有课

自己练习: Lua 在线编译器