Menu
CoddyTech

添加商品

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

challenge icon

挑战

简单

添加命令 add。保留你在上一步写的所有内容。

像 add Apple 0.5 100 这样的行会添加商品 Apple,价格为 0.5,库存为 100。商品名称只能有一个单词。

首先,在 _ready() 上方编写函数 add_item(inventory, item, price, stock):

  1. 如果商品已存在于 inventory 中,打印 Error: Item 'Apple' already exists.(包含商品名称),且不做任何更改
  2. 否则,在商品名称下存储 {"price": price, "stock": stock},并打印 Item 'Apple' added successfully.

然后,在循环中为 add 添加一个 elif 分支。调用函数前先检查这一行:

  • 如果这一行不恰好包含 4 个部分,打印 Error: Use add ITEM PRICE STOCK
  • 如果价格不是数字,或者库存不是整数,打印 Error: Price and stock must be numeric.
  • 否则,调用 add_item(),将价格转换为 float,并将库存转换为 int

对于命令 add Apple 0.5 100、add Banana 0.2 50、add Apple 0.6 30、show 和 exit,输出如下:

Inventory Management System
Item 'Apple' added successfully.
Item 'Banana' added successfully.
Error: Item 'Apple' already exists.
{ "Apple": { "price": 0.5, "stock": 100 }, "Banana": { "price": 0.2, "stock": 50 } }
Goodbye!

亲手试试

extends Node

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)
		else:
			print("Unknown command")

逻辑与流程中的所有课

自己练习: GDScript 在线编译器