You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Babushka/scripts/CSharp/Common/Inventory/InventoryInstance.cs

86 lines
2.4 KiB

#nullable enable
using System;
using Godot;
using System.Collections.Generic;
namespace Babushka.scripts.CSharp.Common.Inventory;
public partial class InventoryInstance : Node
{
private List<InventorySlot> _slots = new();
public IReadOnlyList<InventorySlot> Slots => _slots;
[Signal]
public delegate void SlotAmountChangedEventHandler();
[Signal]
public delegate void InventoryContentsChangedEventHandler();
[Export]
public int SlotAmount
{
get => _slots.Count;
set
{
if (value < _slots.Count)
{
_slots.RemoveRange(value, _slots.Count - value);
}
else if (value > _slots.Count)
{
for (var i = _slots.Count; i < value; i++)
{
_slots.Add(new InventorySlot());
}
}
EmitSignal(SignalName.SlotAmountChanged);
}
}
public InventoryActionResult AddItem(ItemInstance newItem, int inventorySlot = -1)
{
if (inventorySlot < 0)
{
inventorySlot = _slots.FindIndex(slot => slot.IsEmpty());
}
if (inventorySlot < 0 || !_slots[inventorySlot].IsEmpty())
{
return InventoryActionResult.DestinationFull;
}
if (inventorySlot >= _slots.Count)
{
return InventoryActionResult.DestinationDoesNotExists;
}
_slots[inventorySlot].itemInstance = newItem;
EmitSignal(SignalName.InventoryContentsChanged);
return InventoryActionResult.Success;
}
public InventoryActionResult RemoveItem(int inventorySlot, out ItemInstance? itemInstance )
{
if (inventorySlot < 0 || inventorySlot >= _slots.Count)
{
itemInstance = null;
return InventoryActionResult.SourceDoesNotExists;
}
if (_slots[inventorySlot].IsEmpty())
{
itemInstance = null;
return InventoryActionResult.SourceIsEmpty;
}
itemInstance = _slots[inventorySlot].itemInstance;
_slots[inventorySlot].itemInstance = null;
EmitSignal(SignalName.InventoryContentsChanged);
return InventoryActionResult.Success;
}
public InventoryActionResult RemoveItem(int inventorySlot)
{
return RemoveItem(inventorySlot, out _);
}
}