部屋のオブジェクトを移植する
Coddyの「GDScript開発者のためのLuau」コースのレッスン 48/48。
チャレンジ
中級GDScriptのリファレンスを移植してください。最初の入力行は0以上の部屋の定員で、残りの行は符号付き整数の予約リクエストです。定員に収まる正のリクエストのみ受け入れてください。失敗したリクエストでは、使用済み座席数は変わりません。remaining:acceptedを返してください。model.luauにModel.new(capacity)とModel:reserve(seats)を実装してください。reserveはブール値を返します。実行ごとに新しいオブジェクトを使用してください。
GDScriptのリファレンス
extends SceneTree
class Room extends RefCounted:
var capacity: int
var used: int = 0
func _init(limit: int):
capacity = limit
func reserve(seats: int) -> bool:
if seats <= 0 or used + seats > capacity:
return false
used += seats
return true
func _init():
var room = Room.new(int(OS.read_string_from_stdin()))
var accepted = 0
while true:
var line = OS.read_string_from_stdin().strip_edges()
if line == "":
break
if room.reserve(int(line)):
accepted += 1
print(str(room.capacity - room.used) + ":" + str(accepted))
quit()app.luauとmodel.luauを編集してください。表示されているロック済みのmain.luauは標準入力を一連の行として読み込み、app.run(lines)を呼び出し、その戻り値を最後に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。入力が空の場合は空のシーケンスになります。すべての数値入力はオーバーフローしない範囲です。
公開APIの確認: Model.new(capacity)はcapacityとusedを公開し、usedは初期値が0です。reserveはブール値を返し、正のリクエストが定員に収まる場合にのみusedを更新します。各部屋は独立しています。ロック済みのドライバーはapp.runを呼び出す前にこの動作を確認します。これらの確認が成功した場合、何も出力されません。
リファレンスでは、標準入力を読み取るために最小限のSceneTreeハーネスを使用しています。この適切な形式の空でない行からなる入力では、空行の確認によってEOFで終了します。ビジネスモデルと出力の仕様を移植してください。Luauのドライバーは、エンジンのライフサイクルを介さずに入力行を渡します。
自分で試してみよう
-- 公開APIのチェック
do
local Model=require("./model")
local a,b=Model.new(5),Model.new(2)
assert(a:reserve(6)==false and a.used==0,"oversized reservation must not mutate")
assert(a:reserve(0)==false and a:reserve(-1)==false and a.used==0,"nonpositive requests are rejected")
assert(a:reserve(2)==true and a.used==2,"accepted seats update used")
assert(a:reserve(3)==true and a.used==5 and a.capacity==5,"exact fit succeeds without changing capacity")
assert(b.used==0 and b.capacity==2,"rooms must be independent")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
GDScript開発者のためのLuauのすべてのレッスン
自分で練習してみよう: Luauオンラインコンパイラ