using System; using Godot; namespace Babushka.scripts.CSharp.Common.Inventory; public partial class InventoryManager : Node { [Signal] public delegate void SlotIndexChangedEventHandler(int newIndex); public static InventoryManager Instance { get; private set; } = null!; public int CurrentSelectedSlotIndex { get => _currentSelectedSlotIndex; set { if (value >= 0 && value <= 8) { _currentSelectedSlotIndex = value; EmitSignalSlotIndexChanged(_currentSelectedSlotIndex); } } } public InventoryInstance? playerInventory; private int _currentSelectedSlotIndex = 0; public override void _EnterTree() { Instance = this; } public override void _Ready() { playerInventory = new InventoryInstance(); playerInventory.SlotAmount = 37; AddChild(playerInventory); } public InventoryActionResult CreateItem( ItemResource itemBlueprint, InventoryInstance inventory, int amount = 1, int inventorySlot = -1) { var newItem = new ItemInstance { blueprint = itemBlueprint, amount = amount }; return inventorySlot < 0 ? inventory.AddItem(newItem) : inventory.AddItemToSlot(newItem, inventorySlot); } public InventoryActionResult MoveItem( InventoryInstance sourceInventory, int sourceSlot, InventoryInstance destinationInventory, int destinationSlot) { var remResult = sourceInventory.RemoveItem(sourceSlot, out var item); if (remResult != InventoryActionResult.Success) return remResult; var addResult = destinationInventory.AddItemToSlot(item!, destinationSlot); if (addResult == InventoryActionResult.Success) return InventoryActionResult.Success; // if adding in the destination failed, re-add the item into the source sourceInventory.AddItemToSlot(item!, sourceSlot); // can not fail ... in theory return addResult; } public InventoryActionResult RemoveItem( InventoryInstance inventory, int inventorySlot, out ItemInstance? itemInstance) { return inventory.RemoveItem(inventorySlot, out itemInstance); } public InventoryActionResult RemoveItem( InventoryInstance inventory, int inventorySlot) { return inventory.RemoveItem(inventorySlot); } public InventoryActionResult CollectItem(ItemInstance itemInstance) { return playerInventory.AddItem(itemInstance); } public InventorySlot GetCurrentSelectedSlot() { if (CurrentSelectedSlotIndex < 0 || CurrentSelectedSlotIndex > 8) throw new ArgumentOutOfRangeException( nameof(CurrentSelectedSlotIndex), "currentInventoryBarIndex must be between 0 and 8 (inclusively)"); return playerInventory.Slots[CurrentSelectedSlotIndex]; } }