Net.Project.B/Src/Inventory/IPlayerEquipmentInventory.cs

64 lines
2.0 KiB
C#

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using BITKit;
namespace Net.Project.B.Inventory
{
public interface IPlayerEquipmentInventory
{
IReadOnlyDictionary<int, IRuntimeItem> Items { get; }
public event Action<int, IRuntimeItem> OnItemAdded;
public event Action<int, IRuntimeItem> OnItemUpdated;
public event Action<int, IRuntimeItem> OnItemConsumed;
public event Action<int, IRuntimeItem> OnItemRemoved;
bool AddOrUpdate(int slot, IRuntimeItem item);
bool Remove(int slot);
bool Consume(int slot);
}
public class PlayerEquipmentInventory : IPlayerEquipmentInventory
{
public IReadOnlyDictionary<int, IRuntimeItem> Items => _items;
private readonly ConcurrentDictionary<int, IRuntimeItem> _items = new();
public event Action<int, IRuntimeItem> OnItemAdded;
public event Action<int, IRuntimeItem> OnItemUpdated;
public event Action<int, IRuntimeItem> OnItemConsumed;
public event Action<int, IRuntimeItem> OnItemRemoved;
public virtual bool AddOrUpdate(int slot, IRuntimeItem item)
{
if (_items.TryGetValue(slot, out var current))
{
if (current.Id != item.Id) return false;
_items[slot] = item;
OnItemUpdated?.Invoke(slot, item);
}
else
{
_items.TryAdd(slot, item);
OnItemAdded?.Invoke(slot, item);
}
return true;
}
public virtual bool Remove(int slot)
{
if (!_items.TryRemove(slot, out var item)) return false;
OnItemRemoved?.Invoke(slot, item);
return true;
}
public virtual bool Consume(int slot)
{
if (_items.TryRemove(slot, out _) is false) return false;
OnItemConsumed?.Invoke(slot, null);
return true;
}
}
}