ユーザー入力の処理
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オンラインコンパイラ