2025-02-24 23:02:49 +08:00
|
|
|
using System;
|
|
|
|
using System.Collections;
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using BITKit;
|
2025-08-03 02:28:22 +08:00
|
|
|
using Microsoft.Extensions.Logging;
|
2025-02-24 23:02:49 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
{
|
2025-08-03 02:28:22 +08:00
|
|
|
private readonly ILogger<PlayerEquipmentInventory> _logger;
|
|
|
|
|
2025-02-24 23:02:49 +08:00
|
|
|
public IReadOnlyDictionary<int, IRuntimeItem> Items => _items;
|
|
|
|
private readonly ConcurrentDictionary<int, IRuntimeItem> _items = new();
|
2025-08-03 02:28:22 +08:00
|
|
|
|
|
|
|
public PlayerEquipmentInventory(ILogger<PlayerEquipmentInventory> logger)
|
|
|
|
{
|
|
|
|
_logger = logger;
|
|
|
|
}
|
|
|
|
|
2025-02-24 23:02:49 +08:00
|
|
|
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)
|
|
|
|
{
|
2025-08-03 02:28:22 +08:00
|
|
|
if (_items.TryRemove(slot, out var item) is false) return false;
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
OnItemConsumed?.Invoke(slot, item);
|
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
|
|
|
_logger.LogCritical(e,e.Message);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2025-02-24 23:02:49 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|