Menu
CoddyTech

移动玩家

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

challenge icon

挑战

简单

实现移动系统,让玩家通过将输入与可用出口进行匹配,在房间之间移动。

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

修改游戏循环以处理移动命令:

  • 初始设置会连接房间:从图书馆向 east 走会到达花园,向 west 走会返回
  • 打印玩家当前所在房间的描述
  • 打印提示符 "> "(大于号后跟一个空格),且不换行
  • 使用 io.read() 读取用户的命令
  • 检查命令是否与当前房间 exits 表中的键匹配
  • 如果匹配,将 player.currentRoom 更新为该出口对应的房间
  • 如果命令是 "quit",将 gameRunning 设为 false 以退出循环

循环应持续运行,直到用户输入 "quit"。

注意:由于 io.write("> ") 不会换行,下一行输出(房间描述)会紧接在提示符后面,出现在原始输出流的同一行。每次循环迭代都会先在单独一行输出房间描述,然后输出不换行的 > ,因此接下来的描述会继续出现在同一行。

预期输出格式(输入:先输入 east,再输入 quit):

You find yourself in a dusty library filled with ancient books and scrolls.
> A hidden garden with overgrown plants and a small fountain.
> 

亲手试试

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

-- 使用 east / west 设置出口
startingRoom.exits = {
  east = gardenRoom
}

gardenRoom.exits = {
  west = startingRoom
}

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

-- 游戏循环
local gameRunning = true

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

逻辑与流程中的所有课

自己练习: Lua 在线编译器