Files
Net.Project.B/Src/Inventory/IPlayerEquipmentInventory.cs
CortexCore 519c93d651 1
2025-08-03 02:28:22 +08:00

83 lines
2.4 KiB
C#

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using BITKit;
using Microsoft.Extensions.Logging;
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
{
private readonly ILogger<PlayerEquipmentInventory> _logger;
public IReadOnlyDictionary<int, IRuntimeItem> Items => _items;
private readonly ConcurrentDictionary<int, IRuntimeItem> _items = new();
public PlayerEquipmentInventory(ILogger<PlayerEquipmentInventory> logger)
{
_logger = logger;
}
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 var item) is false) return false;
try
{
OnItemConsumed?.Invoke(slot, item);
}
catch (Exception e)
{
_logger.LogCritical(e,e.Message);
}
return true;
}
}
}