Menu
CoddyTech

更新库存

本课属于 Coddy GDScript 学习旅程的“逻辑与流程”单元。第 73 课,共 78 课。

challenge icon

挑战

简单

添加 update 命令。保留你在前面步骤中编写的所有内容。

像 update Apple -20 这样的命令会从 Apple 的库存中加上 -20:正数表示进货,负数表示取出商品。

在 _ready() 上方编写函数 update_stock(inventory, item, quantity):

  1. 如果 inventory 中没有该商品,打印 Error: Item 'Orange' not found.(包含商品名称)
  2. 如果更新后的库存会变成负数,打印 Error: Insufficient stock for 'Apple'. 并保留原库存
  3. 否则,保存更新后的库存并打印 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 在线编译器