Menu
CoddyTech

Générer un rapport

Fait partie de la section Logique et flux d’exécution du Journey GDScript de Coddy. Leçon 75 sur 78.

challenge icon

Défi

Difficile

Enfin, ajoute la commande sell, qui vend plusieurs articles à la fois et indique le chiffre d’affaires. Conserve tout ce que tu as écrit aux étapes précédentes.

Une ligne comme sell Apple:30 Banana:20 vend 30 pommes et 20 bananes. Chaque partie après sell contient un nom d’article, deux-points et une quantité, et un article apparaît au plus une fois par ligne.

Écris la fonction sales_report(inventory, sales) au-dessus de _ready(). sales est un dictionnaire qui associe chaque nom d’article à la quantité vendue. Pour chaque article, dans l’ordre :

  1. Si l’article ne se trouve pas dans inventory, affiche Error: Item 'Orange' not found. et passe à l’article suivant
  2. Si son stock est inférieur à la quantité, affiche Error: Insufficient stock for 'Apple'. et passe à l’article suivant
  3. Sinon, retire la quantité du stock et ajoute à la recette la quantité multipliée par le prix

La fonction renvoie le texte Total revenue: $ suivi de la recette avec deux décimales.

Dans la boucle, la branche sell crée le dictionnaire sales à partir des parties qui suivent la commande. Une partie qui ne contient pas exactement un nom et un nombre entier séparés par : affiche Error: Invalid sale 'Apple-3'. (avec cette partie) et est ignorée. Affiche ensuite ce que renvoie sales_report().

Pour les commandes add Apple 0.5 50, add Banana 0.2 60, sell Apple:30 Banana:20 Orange:10, show et exit, le résultat est :

Inventory Management System
Item 'Apple' added successfully.
Item 'Banana' added successfully.
Error: Item 'Orange' not found.
Total revenue: $19.00
{ "Apple": { "price": 0.5, "stock": 20 }, "Banana": { "price": 0.2, "stock": 40 } }
Goodbye!

Essayez vous-même

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 update_stock(inventory: Dictionary, item: String, quantity: int) -> void:
	if not inventory.has(item):
		print("Error: Item '%s' not found." % item)
		return
	var new_stock: int = inventory[item]["stock"] + quantity
	if new_stock < 0:
		print("Error: Insufficient stock for '%s'." % item)
		return
	inventory[item]["stock"] = new_stock
	print("Stock for '%s' updated successfully." % item)

func check_availability(inventory: Dictionary, item: String) -> int:
	if not inventory.has(item):
		return -1
	return inventory[item]["stock"]

func _ready():
	# L'inventaire : nom de l'article -> {"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]))
		elif command == "update":
			if parts.size() != 3:
				print("Error: Use update ITEM QUANTITY")
			elif not parts[2].is_valid_int():
				print("Error: Quantity must be an integer.")
			else:
				update_stock(inventory, parts[1], int(parts[2]))
		elif command == "check":
			if parts.size() != 2:
				print("Error: Use check ITEM")
			else:
				var stock := check_availability(inventory, parts[1])
				if stock == -1:
					print("Item not found")
				else:
					print(parts[1], ": ", stock, " in stock")
		else:
			print("Unknown command")

Toutes les leçons de Logique et flux d’exécution

Entraînez-vous par vous-même : Compilateur GDScript en ligne