diff --git a/project.godot b/project.godot index 372e306..e909544 100644 --- a/project.godot +++ b/project.godot @@ -40,6 +40,7 @@ cast={"deadzone":0.5,"events":[Object(InputEventKey,"physical_keycode":88)]} talk={"deadzone":0.5,"events":[Object(InputEventKey,"physical_keycode":84)]} rest={"deadzone":0.5,"events":[Object(InputEventKey,"physical_keycode":72)]} inventory={"deadzone":0.5,"events":[Object(InputEventKey,"physical_keycode":73)]} +crafting={"deadzone":0.5,"events":[Object(InputEventKey,"physical_keycode":66)]} character={"deadzone":0.5,"events":[Object(InputEventKey,"physical_keycode":80)]} quest={"deadzone":0.5,"events":[Object(InputEventKey,"physical_keycode":74)]} audience={"deadzone":0.5,"events":[Object(InputEventKey,"physical_keycode":85)]} diff --git a/scenes/Game.tscn b/scenes/Game.tscn index 9453180..acdfb1b 100644 --- a/scenes/Game.tscn +++ b/scenes/Game.tscn @@ -13,6 +13,7 @@ [ext_resource type="PackedScene" path="res://scenes/ui/LootPanel.tscn" id="11_loot"] [ext_resource type="PackedScene" path="res://scenes/ui/InventoryPanel.tscn" id="12_inventory"] [ext_resource type="PackedScene" path="res://scenes/ui/ShopPanel.tscn" id="13_shop"] +[ext_resource type="PackedScene" path="res://scenes/ui/CraftingPanel.tscn" id="14_crafting"] [sub_resource type="StyleBoxFlat" id="StyleBox_hud_panel"] bg_color = Color(0.035, 0.055, 0.09, 0.9) @@ -83,6 +84,8 @@ script = ExtResource("4_hud") [node name="ShopPanel" parent="HUD" instance=ExtResource("13_shop")] +[node name="CraftingPanel" parent="HUD" instance=ExtResource("14_crafting")] + [node name="ResponsiveLayout" type="Control" parent="HUD"] layout_mode = 3 anchors_preset = 15 diff --git a/scenes/ui/CraftingPanel.tscn b/scenes/ui/CraftingPanel.tscn new file mode 100644 index 0000000..e670eef --- /dev/null +++ b/scenes/ui/CraftingPanel.tscn @@ -0,0 +1,65 @@ +[gd_scene load_steps=3 format=3] + +[ext_resource type="Script" path="res://scripts/presentation/crafting_panel.gd" id="1_crafting"] + +[sub_resource type="StyleBoxFlat" id="StyleBox_crafting_panel"] +bg_color = Color(0.035, 0.055, 0.09, 0.97) +border_width_left = 3 +border_width_top = 3 +border_width_right = 3 +border_width_bottom = 3 +border_color = Color(0.5, 0.8, 0.38, 0.95) +corner_radius_top_left = 8 +corner_radius_top_right = 8 +corner_radius_bottom_right = 8 +corner_radius_bottom_left = 8 + +[node name="CraftingPanel" type="PanelContainer"] +visible = false +layout_mode = 1 +anchors_preset = 8 +anchor_left = 0.5 +anchor_top = 0.5 +anchor_right = 0.5 +anchor_bottom = 0.5 +offset_left = -400.0 +offset_top = -235.0 +offset_right = 400.0 +offset_bottom = 235.0 +grow_horizontal = 2 +grow_vertical = 2 +theme_override_styles/panel = SubResource("StyleBox_crafting_panel") +script = ExtResource("1_crafting") + +[node name="Title" type="Label" parent="."] +layout_mode = 1 +anchors_preset = 10 +anchor_left = 0.5 +anchor_right = 0.5 +offset_left = -350.0 +offset_top = 18.0 +offset_right = 350.0 +offset_bottom = 46.0 +grow_horizontal = 2 +theme_override_colors/font_color = Color(0.7, 1, 0.55, 1) +theme_override_font_sizes/font_size = 24 +text = "ALCHIMIE ET ARTISANAT" +horizontal_alignment = 1 + +[node name="Entries" type="RichTextLabel" parent="."] +layout_mode = 0 +offset_left = 28.0 +offset_top = 66.0 +offset_right = 355.0 +offset_bottom = 400.0 +theme_override_colors/default_color = Color(0.92, 0.95, 1, 1) +theme_override_font_sizes/normal_font_size = 18 + +[node name="Details" type="RichTextLabel" parent="."] +layout_mode = 0 +offset_left = 380.0 +offset_top = 66.0 +offset_right = 770.0 +offset_bottom = 420.0 +theme_override_colors/default_color = Color(0.92, 0.95, 1, 1) +theme_override_font_sizes/normal_font_size = 17 diff --git a/scripts/domain/items/crafting_engine.gd b/scripts/domain/items/crafting_engine.gd new file mode 100644 index 0000000..d23cb56 --- /dev/null +++ b/scripts/domain/items/crafting_engine.gd @@ -0,0 +1,99 @@ +class_name CraftingEngine +extends RefCounted + +const ItemDefinitionType = preload("res://scripts/domain/items/item_definition.gd") +const ItemInstanceType = preload("res://scripts/domain/items/item_instance.gd") + +var _catalog: ContentCatalog +var _recipes: Dictionary[StringName, Dictionary] = {} + +func _init(catalog: ContentCatalog) -> void: + _catalog = catalog + _load_recipes() + +func recipe_ids() -> Array[StringName]: + var ids: Array[StringName] = _recipes.keys() + ids.sort() + return ids + +func recipe(recipe_id: StringName) -> Dictionary: + return _recipes.get(recipe_id, {}).duplicate(true) + +func recipe_availability(recipe_id: StringName, inventory: InventoryState, floor_number: int) -> Dictionary: + var definition := recipe(recipe_id) + if definition.is_empty(): + return _availability(false, &"unknown_recipe", definition) + if inventory == null: + return _availability(false, &"invalid_inventory", definition) + if floor_number < int(definition.get("min_floor", 0)): + return _availability(false, &"min_floor", definition) + var missing := _missing_materials(definition, inventory) + if not missing.is_empty(): + return _availability(false, &"missing_materials", definition, missing) + return _availability(true, &"", definition) + +func craft(recipe_id: StringName, inventory: InventoryState, floor_number: int) -> Dictionary: + var availability := recipe_availability(recipe_id, inventory, floor_number) + if not bool(availability.available): + return _result(false, StringName(availability.reason), null, availability.missing_materials) + var definition: Dictionary = availability.recipe + var output_data: Dictionary = definition.get("output", {}) + var output_definition := ItemDefinitionType.from_catalog(_catalog, StringName(output_data.get("item_id", ""))) + if not output_definition.is_valid(): + return _result(false, &"invalid_output") + for input_data: Dictionary in definition.get("inputs", []): + _consume(inventory, StringName(input_data.get("item_id", "")), int(input_data.get("qty", 0))) + var output := ItemInstanceType.new(output_definition, maxi(1, int(output_data.get("qty", 1)))) + var added := inventory.add_item(output) + if not bool(added.accepted): + # Availability was checked before mutation; this should only be reachable + # for a malformed inventory implementation, so retain inputs atomically. + for input_data: Dictionary in definition.get("inputs", []): + var input_definition := ItemDefinitionType.from_catalog(_catalog, StringName(input_data.get("item_id", ""))) + inventory.add_item(ItemInstanceType.new(input_definition, int(input_data.get("qty", 0)))) + return _result(false, StringName(added.reason)) + return _result(true, &"", output) + +func _load_recipes() -> void: + var file := FileAccess.open("res://data/ascii/recipes.json", FileAccess.READ) + if file == null: + return + var parsed: Variant = JSON.parse_string(file.get_as_text()) + if not parsed is Array: + return + for entry: Variant in parsed: + if entry is Dictionary and entry.has("id"): + _recipes[StringName(entry.id)] = entry.duplicate(true) + +func _missing_materials(definition: Dictionary, inventory: InventoryState) -> Array[Dictionary]: + var missing: Array[Dictionary] = [] + for input_data: Dictionary in definition.get("inputs", []): + var item_id := StringName(input_data.get("item_id", "")) + var required := maxi(0, int(input_data.get("qty", 0))) + var available := _quantity(inventory, item_id) + if available < required: + missing.append({"item_id": item_id, "required": required, "available": available, "missing": required - available}) + return missing + +func _quantity(inventory: InventoryState, item_id: StringName) -> int: + var quantity := 0 + for item: ItemInstance in inventory.items: + if item.definition.id == item_id: + quantity += item.quantity + return quantity + +func _consume(inventory: InventoryState, item_id: StringName, quantity: int) -> void: + var remaining := quantity + for item: ItemInstance in inventory.items.duplicate(): + if remaining <= 0: + return + if item.definition.id == item_id: + var removed := inventory.remove_item(item.instance_id, remaining) + if bool(removed.accepted): + remaining -= removed.item.quantity + +func _availability(available: bool, reason: StringName, definition: Dictionary, missing_materials: Array[Dictionary] = []) -> Dictionary: + return {"available": available, "reason": reason, "recipe": definition, "missing_materials": missing_materials} + +func _result(accepted: bool, reason: StringName, item: ItemInstance = null, missing_materials: Array[Dictionary] = []) -> Dictionary: + return {"accepted": accepted, "reason": reason, "item": item, "missing_materials": missing_materials} diff --git a/scripts/domain/items/crafting_engine.gd.uid b/scripts/domain/items/crafting_engine.gd.uid new file mode 100644 index 0000000..5a376ed --- /dev/null +++ b/scripts/domain/items/crafting_engine.gd.uid @@ -0,0 +1 @@ +uid://dujwgjlyw240p diff --git a/scripts/game/game.gd b/scripts/game/game.gd index 9ece5e2..75cc08e 100644 --- a/scripts/game/game.gd +++ b/scripts/game/game.gd @@ -24,6 +24,7 @@ const ItemDefinitionType = preload("res://scripts/domain/items/item_definition.g const ItemInstanceType = preload("res://scripts/domain/items/item_instance.gd") const InventoryPanelType = preload("res://scripts/presentation/inventory_panel.gd") const EconomyType = preload("res://scripts/domain/items/economy.gd") +const CraftingEngineType = preload("res://scripts/domain/items/crafting_engine.gd") @onready var event_presenter: EventPresenter = $EventPresenter @onready var map_renderer: MapRenderer = $World/MapRenderer @onready var player_view: ActorView = $World/Player @@ -35,6 +36,7 @@ const EconomyType = preload("res://scripts/domain/items/economy.gd") @onready var loot_panel: LootPanel = $HUD/LootPanel @onready var inventory_panel: InventoryPanel = $HUD/InventoryPanel @onready var shop_panel: ShopPanel = $HUD/ShopPanel +@onready var crafting_panel: CraftingPanel = $HUD/CraftingPanel var pending_loot: Dictionary = {} var active_shop_npc: Dictionary = {} @onready var audio_library = $AudioLibrary @@ -49,6 +51,7 @@ var pending_base_archetype: StringName = &"vanguard" var floor_transition: FloorTransition var spell_catalog: ContentCatalog var spell_state: SpellState +var crafting_engine: CraftingEngine func configure_new_run(settings: RunSettings, player_name: String, base_archetype: StringName) -> void: pending_run_settings = settings @@ -89,6 +92,7 @@ func _initialize_run_state() -> void: run_state.player_name = pending_player_name run_state.base_archetype = pending_base_archetype spell_catalog = ContentCatalogType.load_from_directory("res://data/ascii") + crafting_engine = CraftingEngineType.new(spell_catalog) game_state.content_catalog = spell_catalog spell_state = SpellStateType.new([&"spell_epines_empoisonnees"]) floor_transition = FloorTransitionType.new(spell_catalog) @@ -147,6 +151,20 @@ func _prepare_exit_capture_state() -> void: _sync_camera_to_player() func _unhandled_input(event: InputEvent) -> void: + if crafting_panel.visible and event is InputEventKey and event.is_pressed(): + if event.keycode == KEY_UP: + crafting_panel.select_next(-1) + elif event.keycode == KEY_DOWN: + crafting_panel.select_next(1) + elif event.keycode == KEY_ENTER or event.keycode == KEY_SPACE: + _complete_craft() + elif event.is_action_pressed(&"crafting") or event.keycode == KEY_ESCAPE: + _close_crafting_panel() + else: + get_viewport().set_input_as_handled() + return + get_viewport().set_input_as_handled() + return if shop_panel.visible and event is InputEventKey and event.is_pressed(): if event.keycode == KEY_UP: shop_panel.select_next(-1) @@ -237,6 +255,9 @@ func submit_player_action(action: PlayerAction) -> Array[GameEvent]: &"inventory": last_turn_results = [] return _toggle_inventory_panel() + &"crafting": + last_turn_results = [] + return _toggle_crafting_panel() &"ranged": return _begin_targeting() &"ranged_target": @@ -498,6 +519,28 @@ func _complete_shop_transaction() -> void: else: _record_ranged_event(&"shop_purchase_refused", &"", {"item_id": selected, "reason": purchase.reason, "price": purchase.price}, "Achat impossible : or insuffisant ou inventaire plein.") +func _toggle_crafting_panel() -> Array[GameEvent]: + if crafting_panel.visible: + return _close_crafting_panel() + crafting_panel.present(crafting_engine, run_state.inventory, run_state.current_floor) + return _record_ranged_event(&"crafting_opened", &"", {"recipe_count": crafting_engine.recipe_ids().size()}, "Atelier d’artisanat ouvert.") + +func _close_crafting_panel() -> Array[GameEvent]: + crafting_panel.dismiss() + return _record_ranged_event(&"crafting_closed", &"", {}, "Atelier d’artisanat fermé.") + +func _complete_craft() -> void: + var recipe_id := crafting_panel.selected_recipe_id() + if recipe_id.is_empty(): + return + var result := crafting_engine.craft(recipe_id, run_state.inventory, run_state.current_floor) + if bool(result.accepted): + _record_ranged_event(&"craft_completed", &"", {"recipe_id": recipe_id, "item_id": result.item.definition.id, "quantity": result.item.quantity}, "Fabrication réussie : %s x%d." % [result.item.definition.name, result.item.quantity]) + else: + _record_ranged_event(&"craft_refused", &"", {"recipe_id": recipe_id, "reason": result.reason, "missing_materials": result.missing_materials}, "Fabrication impossible.") + crafting_panel.refresh() + _refresh_inventory_panel() + func _toggle_inventory_panel() -> Array[GameEvent]: if inventory_panel.visible: inventory_panel.dismiss() diff --git a/scripts/game/input_bindings.gd b/scripts/game/input_bindings.gd index 4910e80..2080941 100644 --- a/scripts/game/input_bindings.gd +++ b/scripts/game/input_bindings.gd @@ -20,6 +20,7 @@ const ACTIONS: Array[StringName] = [ &"talk", &"rest", &"inventory", + &"crafting", &"character", &"quest", &"audience", @@ -45,6 +46,7 @@ const HELP_NAMES := { &"talk": "Parler", &"rest": "Se reposer", &"inventory": "Inventaire", + &"crafting": "Artisanat", &"character": "Personnage", &"quest": "Quêtes", &"audience": "Audience", diff --git a/scripts/presentation/crafting_panel.gd b/scripts/presentation/crafting_panel.gd new file mode 100644 index 0000000..ace2974 --- /dev/null +++ b/scripts/presentation/crafting_panel.gd @@ -0,0 +1,72 @@ +class_name CraftingPanel +extends PanelContainer + +@onready var entries: RichTextLabel = $Entries +@onready var details: RichTextLabel = $Details + +var _engine: CraftingEngine +var _inventory: InventoryState +var _floor_number := 0 +var _selected_index := 0 + +func present(engine: CraftingEngine, inventory: InventoryState, floor_number: int) -> void: + _engine = engine + _inventory = inventory + _floor_number = floor_number + _selected_index = clampi(_selected_index, 0, maxi(0, _recipe_count() - 1)) + refresh() + visible = true + +func dismiss() -> void: + visible = false + +func select_next(delta: int) -> void: + if _recipe_count() == 0: + return + _selected_index = posmod(_selected_index + delta, _recipe_count()) + refresh() + +func selected_recipe_id() -> StringName: + if _engine == null or _selected_index < 0 or _selected_index >= _recipe_count(): + return &"" + return _engine.recipe_ids()[_selected_index] + +func refresh() -> void: + if _engine == null or _inventory == null: + entries.text = "Aucune recette disponible." + details.text = "Aucune recette disponible." + return + _selected_index = clampi(_selected_index, 0, maxi(0, _recipe_count() - 1)) + var lines: PackedStringArray = [] + for index in _recipe_count(): + var recipe_id := _engine.recipe_ids()[index] + var recipe := _engine.recipe(recipe_id) + var availability := _engine.recipe_availability(recipe_id, _inventory, _floor_number) + var cursor := "> " if index == _selected_index else " " + var status := "Disponible" if bool(availability.available) else _status(availability) + lines.append("%s%s — %s" % [cursor, String(recipe.get("name", recipe_id)), status]) + entries.text = "\n".join(lines) if not lines.is_empty() else "Aucune recette disponible." + var selected := _engine.recipe(selected_recipe_id()) + details.text = _details(selected) if not selected.is_empty() else "Aucune recette disponible." + +func _recipe_count() -> int: + return _engine.recipe_ids().size() if _engine != null else 0 + +func _status(availability: Dictionary) -> String: + if availability.reason == &"min_floor": + return "Niveau %d requis" % int(availability.recipe.get("min_floor", 0)) + if availability.reason == &"missing_materials": + return "Matériaux manquants" + return "Indisponible" + +func _details(recipe: Dictionary) -> String: + var ingredients: PackedStringArray = [] + for input_data: Dictionary in recipe.get("inputs", []): + ingredients.append("%s x%d" % [String(input_data.get("item_id", "")), int(input_data.get("qty", 0))]) + var output: Dictionary = recipe.get("output", {}) + return "%s\n\nIngrédients\n%s\n\nProduit\n%s x%d\n\n↑/↓ Sélectionner Entrée Fabriquer B/Échap Fermer" % [ + String(recipe.get("description", "")), + "\n".join(ingredients), + String(output.get("item_id", "")), + int(output.get("qty", 0)), + ] diff --git a/scripts/presentation/crafting_panel.gd.uid b/scripts/presentation/crafting_panel.gd.uid new file mode 100644 index 0000000..a6d97b6 --- /dev/null +++ b/scripts/presentation/crafting_panel.gd.uid @@ -0,0 +1 @@ +uid://cacbdlpre261y diff --git a/task-D5.md b/task-D5.md new file mode 100644 index 0000000..a362bea --- /dev/null +++ b/task-D5.md @@ -0,0 +1,43 @@ +# Task D5 — Crafting recipes and alchemy + +## Scope + +Implemented D5 only in the Godot port worktree: + +- `CraftingEngine` reads `data/ascii/recipes.json`, reports recipe availability, enforces `min_floor`, identifies every missing material, consumes input quantities, and adds the declared output item quantity. +- Crafting consumes inputs before adding the output so fully consumed ingredient slots can be reused by the result; validated availability prevents a failed attempt from consuming materials. +- Added modal `CraftingPanel` and a dedicated **B** (`crafting`) action. It lists all recipes, shows availability/requirements, supports arrow selection, Enter/Space crafting, and B/Escape dismissal. +- Integrated crafting journal events (`crafting_opened`, `craft_completed`, `craft_refused`, `crafting_closed`) and refreshes an already-open inventory after crafting. +- Added strict TDD coverage for JSON inputs, missing-material details, minimum floor, output quantity, capacity-slot reuse, and real keyboard panel-to-inventory E2E flow. + +No D6 content-import or performance work was included. + +## Root-cause report + +There was no previous crafting domain or UI path: `recipes.json` existed but was neither loaded by the generic content catalog nor reachable from `Game`. Consequently, its `inputs`, `min_floor`, and `output` contract could not affect inventory state. The focused red test first failed because `crafting_engine.gd` was absent. A subsequent capacity regression test exposed a transactional ordering issue in the initial green implementation: it tried to add output before consuming ingredients, incorrectly rejecting an otherwise valid craft when ingredient stacks occupied all slots. The final engine validates all prerequisites first, consumes recipe inputs, then adds output, with input restoration as a defensive fallback if output insertion is unexpectedly rejected. + +A first panel E2E attempt also exposed that **C** is already bound to diagonal movement (`move_southeast`). The crafting action was moved to **B**, avoiding the existing input-map collision rather than changing unrelated movement controls. + +## TDD evidence + +1. Red: `tests/unit/test_crafting.gd` failed before implementation because `res://scripts/domain/items/crafting_engine.gd` did not exist (`/tmp/d5-red-unit.log`). +2. Green: focused unit suite passed: 4 tests, 25 assertions (`/tmp/d5-green-unit-final.log`). +3. Red capacity regression: the added capacity-slot reuse test failed with the initial output-before-consume ordering (`/tmp/d5-red-capacity.log`). +4. Green panel E2E passed: 1 test, 11 assertions (`/tmp/d5-green-e2e-final.log`). + +## Full verification + +Executed `scripts/verify.sh` successfully: + +- Unit: **139/139** tests, **1070** assertions. +- Integration: **7/7** tests, **9255** assertions. +- E2E (including `test_crafting_e2e.gd`): **36/36** tests, **372** assertions. +- Visual capture/check passed. Generated ignored artifacts: + - `artifacts/visual-check.png` + - `artifacts/visual-check-exit.png` + +Godot/GUT emitted pre-existing resource/UID warnings and shutdown resource-leak diagnostics, but no test or parse failures; `verify` ended with `unit, integration, E2E, and visual checks passed`. + +## Delivery + +Local commit only; no push and no pull request. diff --git a/tests/e2e/test_crafting_e2e.gd b/tests/e2e/test_crafting_e2e.gd new file mode 100644 index 0000000..1cea5c9 --- /dev/null +++ b/tests/e2e/test_crafting_e2e.gd @@ -0,0 +1,57 @@ +extends GutTest + +const GameScene = preload("res://scenes/Game.tscn") +const ItemDefinitionType = preload("res://scripts/domain/items/item_definition.gd") +const ItemInstanceType = preload("res://scripts/domain/items/item_instance.gd") + +var game: Game + +func before_each() -> void: + game = GameScene.instantiate() + add_child_autofree(game) + await get_tree().process_frame + +func _add(item_id: StringName, quantity: int) -> void: + var definition := ItemDefinitionType.from_catalog(game.spell_catalog, item_id) + assert_true(game.get_run_state().inventory.add_item(ItemInstanceType.new(definition, quantity)).accepted) + +func _quantity(item_id: StringName) -> int: + var quantity := 0 + for item in game.get_run_state().inventory.items: + if item.definition.id == item_id: + quantity += item.quantity + return quantity + +func test_crafting_panel_flow_shows_available_recipe_and_crafts_into_run_inventory() -> void: + game.get_run_state().current_floor = 3 + game.get_game_state().floor_state.floor_number = 3 + _add(&"misc_soufre", 2) + _add(&"misc_charbon", 1) + + await _dispatch_key(KEY_B) + var panel := game.get_node("HUD/CraftingPanel") as PanelContainer + var entries := game.get_node("HUD/CraftingPanel/Entries") as RichTextLabel + assert_true(panel.visible) + assert_string_contains(entries.get_parsed_text(), "Poudre a canon artisanale") + assert_string_contains(entries.get_parsed_text(), "Disponible") + + await _dispatch_key(KEY_ENTER) + assert_true(panel.visible) + assert_eq(_quantity(&"misc_soufre"), 0) + assert_eq(_quantity(&"misc_charbon"), 0) + assert_eq(_quantity(&"misc_poudre_a_canon"), 1) + assert_eq(game.get_run_state().recent_events(1)[0].kind, &"craft_completed") + assert_string_contains((game.get_node("HUD/CraftingPanel/Details") as RichTextLabel).get_parsed_text(), "x1") + +func _dispatch_key(keycode: Key) -> void: + Input.parse_input_event(_key_event(keycode, true)) + await get_tree().process_frame + Input.parse_input_event(_key_event(keycode, false)) + await get_tree().process_frame + +func _key_event(keycode: Key, pressed: bool) -> InputEventKey: + var event := InputEventKey.new() + event.keycode = keycode + event.physical_keycode = keycode + event.pressed = pressed + return event diff --git a/tests/e2e/test_crafting_e2e.gd.uid b/tests/e2e/test_crafting_e2e.gd.uid new file mode 100644 index 0000000..42a197a --- /dev/null +++ b/tests/e2e/test_crafting_e2e.gd.uid @@ -0,0 +1 @@ +uid://bem5nv87aa0gb diff --git a/tests/unit/test_crafting.gd b/tests/unit/test_crafting.gd new file mode 100644 index 0000000..6f70831 --- /dev/null +++ b/tests/unit/test_crafting.gd @@ -0,0 +1,78 @@ +extends GutTest + +const ContentCatalogType = preload("res://scripts/domain/content/content_catalog.gd") +const CraftingEngineType = preload("res://scripts/domain/items/crafting_engine.gd") +const InventoryStateType = preload("res://scripts/domain/inventory/inventory_state.gd") +const ItemDefinitionType = preload("res://scripts/domain/items/item_definition.gd") +const ItemInstanceType = preload("res://scripts/domain/items/item_instance.gd") + +var catalog: ContentCatalog +var engine: CraftingEngine + +func before_each() -> void: + catalog = ContentCatalogType.load_from_directory("res://data/ascii") + engine = CraftingEngineType.new(catalog) + ItemInstanceType.reset_id_sequence_for_tests() + +func _add(inventory: InventoryState, item_id: StringName, quantity: int) -> void: + var definition := ItemDefinitionType.from_catalog(catalog, item_id) + assert_true(inventory.add_item(ItemInstanceType.new(definition, quantity)).accepted) + +func _quantity(inventory: InventoryState, item_id: StringName) -> int: + var quantity := 0 + for item in inventory.items: + if item.definition.id == item_id: + quantity += item.quantity + return quantity + +func test_recipe_from_ascii_requires_its_declared_inputs_and_reports_each_missing_material() -> void: + var inventory := InventoryStateType.new() + _add(inventory, &"misc_soufre", 1) + + var availability := engine.recipe_availability(&"recipe_poudre_a_canon", inventory, 3) + + assert_false(availability.available) + assert_eq(availability.reason, &"missing_materials") + assert_eq(availability.missing_materials, [ + {"item_id": &"misc_soufre", "required": 2, "available": 1, "missing": 1}, + {"item_id": &"misc_charbon", "required": 1, "available": 0, "missing": 1}, + ]) + +func test_recipe_availability_enforces_minimum_floor_before_consuming_materials() -> void: + var inventory := InventoryStateType.new() + _add(inventory, &"misc_soufre", 2) + _add(inventory, &"misc_charbon", 1) + + var crafted := engine.craft(&"recipe_poudre_a_canon", inventory, 2) + + assert_false(crafted.accepted) + assert_eq(crafted.reason, &"min_floor") + assert_eq(_quantity(inventory, &"misc_soufre"), 2) + assert_eq(_quantity(inventory, &"misc_charbon"), 1) + assert_eq(_quantity(inventory, &"misc_poudre_a_canon"), 0) + +func test_crafting_uses_slots_freed_by_fully_consumed_materials_for_the_output() -> void: + var inventory := InventoryStateType.new(2) + _add(inventory, &"misc_soufre", 2) + _add(inventory, &"misc_charbon", 1) + + var crafted := engine.craft(&"recipe_poudre_a_canon", inventory, 3) + + assert_true(crafted.accepted) + assert_eq(inventory.items.size(), 1) + assert_eq(_quantity(inventory, &"misc_poudre_a_canon"), 1) + +func test_crafting_consumes_recipe_input_quantities_and_adds_declared_output_quantity() -> void: + var inventory := InventoryStateType.new() + _add(inventory, &"misc_soufre", 4) + _add(inventory, &"misc_charbon", 2) + + var crafted := engine.craft(&"recipe_poudre_a_canon", inventory, 3) + + assert_true(crafted.accepted) + assert_eq(crafted.reason, &"") + assert_eq(crafted.item.definition.id, &"misc_poudre_a_canon") + assert_eq(crafted.item.quantity, 1) + assert_eq(_quantity(inventory, &"misc_soufre"), 2) + assert_eq(_quantity(inventory, &"misc_charbon"), 1) + assert_eq(_quantity(inventory, &"misc_poudre_a_canon"), 1) diff --git a/tests/unit/test_crafting.gd.uid b/tests/unit/test_crafting.gd.uid new file mode 100644 index 0000000..24286cc --- /dev/null +++ b/tests/unit/test_crafting.gd.uid @@ -0,0 +1 @@ +uid://b0mcqurh8av6d