在庫を更新する
CoddyのGDScriptジャーニー「ロジックとフロー」セクションの一部。レッスン 73/78。
チャレンジ
簡単コマンド update を追加します。これまでの手順で書いた内容はすべて残してください。
update Apple -20 のような行は、Apple の在庫数に -20 を加算します。正の数量は入荷、負の数量は出庫です。
_ready() の上に関数 update_stock(inventory, item, quantity) を書きます。
- 商品が
inventoryにない場合は、商品名を含めてError: Item 'Orange' not found.を出力します - 新しい在庫数が負になる場合は、
Error: Insufficient stock for 'Apple'.を出力し、在庫数は以前の値のままにします - それ以外の場合は、新しい在庫数を保存して
Stock for 'Apple' updated successfully.を出力します
ループ内に、update 用の elif 分岐を追加します。
- 行の要素数がちょうど
3でない場合は、Error: Use update ITEM QUANTITYを出力します - 数量が整数でない場合は、
Error: Quantity must be an integer.を出力します - それ以外の場合は、
update_stock()を呼び出します
コマンド add Apple 0.5 100、add Banana 0.2 50、add Apple 0.6 30、update Apple -20、update Banana 30、update Orange 10、update Apple -90、show、exit に対する出力は次のとおりです。
Inventory Management System
Item 'Apple' added successfully.
Item 'Banana' added successfully.
Error: Item 'Apple' already exists.
Stock for 'Apple' updated successfully.
Stock for 'Banana' updated successfully.
Error: Item 'Orange' not found.
Error: Insufficient stock for 'Apple'.
{ "Apple": { "price": 0.5, "stock": 80 }, "Banana": { "price": 0.2, "stock": 80 } }
Goodbye!自分で試してみよう
extends Node
func add_item(inventory: Dictionary, item: String, price: float, stock: int) -> void:
if inventory.has(item):
print("Error: Item '%s' already exists." % item)
return
inventory[item] = {"price": price, "stock": stock}
print("Item '%s' added successfully." % item)
func _ready():
# 在庫: 商品名 -> {"price": float, "stock": int}
var inventory := {}
print("Inventory Management System")
while true:
var line := OS.read_string_from_stdin()
var parts := line.split(" ")
var command := parts[0]
if command == "exit":
print("Goodbye!")
break
elif command == "show":
print(inventory)
elif command == "add":
if parts.size() != 4:
print("Error: Use add ITEM PRICE STOCK")
elif not parts[2].is_valid_float() or not parts[3].is_valid_int():
print("Error: Price and stock must be numeric.")
else:
add_item(inventory, parts[1], float(parts[2]), int(parts[3]))
else:
print("Unknown command")
ロジックとフローのすべてのレッスン
自分で練習してみよう: GDScriptオンラインコンパイラ