Menu
Coddy logo textTech

無効な移動の処理

CoddyのLuaジャーニー「Logic & Flow」セクションの一部 — レッスン 30/54。

challenge icon

チャレンジ

簡単

プレイヤーが無効な方向を入力したときにフィードバックを提供するために、移動システムにエラーハンドリングを追加してください。

前のチャレンジで使用した startingRoomgardenRoom、および player 変数が提供されています。

無効な移動コマンドを処理するようにゲームループを修正してください:

  • north/south の出口を使用して部屋を接続します:startingRoom.exits["north"]gardenRoom に、gardenRoom.exits["south"]startingRoom に設定します。
  • プレイヤーの現在の部屋の説明を表示します。
  • プロンプト "> "(不等号の後にスペースが続くもの)を改行なしで表示します。
  • io.read() を使用してユーザーのコマンドを読み取ります。
  • コマンドが現在の部屋の exits テーブルのキーと一致するかどうかを確認します。
  • 一致する場合は、player.currentRoom をその出口に保存されている部屋に更新します。
  • コマンドがいずれの出口とも一致せず、かつ "quit" でもない場合は、"You can't go that way." と表示します。
  • コマンドが "quit" の場合は、gameRunningfalse に設定してループを終了します。

ループはユーザーが "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.
> 

自分で試してみよう

-- 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 = {}
}

-- Set exits using east / west
startingRoom.exits = {
  east = gardenRoom
}

gardenRoom.exits = {
  west = 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]
  end
end

Logic & Flowのすべてのレッスン