Implement inventory system with item management and pickup functionality
This commit is contained in:
46
GameCore/Inventory/InventoryComponent.cs
Normal file
46
GameCore/Inventory/InventoryComponent.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using GameCore.ECS.Interfaces;
|
||||
|
||||
namespace GameCore.Inventory;
|
||||
|
||||
public class InventoryComponent : IComponent
|
||||
{
|
||||
private readonly Dictionary<string, Item> _items = new();
|
||||
|
||||
public bool AddItem(Item itemToAdd)
|
||||
{
|
||||
if (_items.TryGetValue(itemToAdd.ItemId, out var exisitingItem))
|
||||
{
|
||||
exisitingItem.Quantity += itemToAdd.Quantity;
|
||||
_items[itemToAdd.ItemId] = exisitingItem;
|
||||
}
|
||||
else
|
||||
{
|
||||
_items.Add(itemToAdd.ItemId, itemToAdd);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool RemoveItem(string itemId, int quantity)
|
||||
{
|
||||
if (!_items.TryGetValue(itemId, out var existingItem) || existingItem.Quantity < quantity) return false;
|
||||
|
||||
existingItem.Quantity -= quantity;
|
||||
if (existingItem.Quantity <= 0)
|
||||
_items.Remove(itemId);
|
||||
else
|
||||
_items[itemId] = existingItem;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public int GetItemCount(string itemId)
|
||||
{
|
||||
return _items.TryGetValue(itemId, out var existingItem) ? existingItem.Quantity : 0;
|
||||
}
|
||||
|
||||
public bool HasItem(string itemId, int quantity = 1)
|
||||
{
|
||||
return GetItemCount(itemId) >= quantity;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user