Menu
CoddyTech

עדכון המלאי

חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-GDScript של Coddy. שיעור 73 מתוך 78.

challenge icon

אתגר

קל

הוסף את הפקודה update. השאר את כל מה שכתבת בשלבים הקודמים.

שורה כמו update Apple -20 מוסיפה -20 למלאי של Apple: כמות חיובית מציינת אספקה, וכמות שלילית מוציאה פריטים מהמלאי.

כתוב את הפונקציה update_stock(inventory, item, quantity) מעל _ready():

  1. אם הפריט לא נמצא ב-inventory, הדפס Error: Item 'Orange' not found. (עם שם הפריט)
  2. אם המלאי החדש יהיה שלילי, הדפס Error: Insufficient stock for 'Apple'. והשאר את המלאי הישן
  3. אחרת, שמור את המלאי החדש והדפס Stock for 'Apple' updated successfully.

בלולאה, הוסף ענף elif עבור update:

  • אם השורה אינה מכילה בדיוק 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 אונליין