Menu
Coddy logo textTech

出口の表示

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

challenge icon

チャレンジ

簡単

部屋の説明を表示した後に、プレイヤーに利用可能なすべての出口を表示することで、ゲームのユーザーエクスペリエンスを向上させましょう。

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

利用可能な出口を表示するようにゲームループを修正してください:

  • プレイヤーの現在の部屋の説明を表示します
  • 新しい行に "Exits:" と表示します
  • pairs() を使用して、現在の部屋の exits テーブルを反復処理します
  • 各出口について、" - " (2つのスペース、ダッシュ、スペース) に続いて方向名を表示します
  • プロンプト "> " (不等号の後にスペース) を改行なしで表示します
  • 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.
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

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