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

96 lines
3.0 KiB
C#
Raw Normal View History

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-08-05 23:34:30 +08:00
private readonly IPlayerInventory _playerInventory;
2025-08-03 02:28:22 +08:00
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
2025-08-05 23:34:30 +08:00
public PlayerEquipmentInventory(ILogger<PlayerEquipmentInventory> logger, IPlayerInventory playerInventory)
2025-08-03 02:28:22 +08:00
{
_logger = logger;
2025-08-05 23:34:30 +08:00
_playerInventory = playerInventory;
2025-08-03 02:28:22 +08:00
}
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);
2025-08-05 23:34:30 +08:00
foreach (var (id, runtimeItem) in _playerInventory.Container.ItemDictionary)
{
if (runtimeItem.ScriptableId != item.ScriptableId) continue;
if (!_playerInventory.Container.Remove(id)) continue;
if (AddOrUpdate(slot, item))
{
break;
}
throw new InvalidOperationException("内部错误,无法从背包补充物品");
}
2025-08-03 02:28:22 +08:00
}
catch (Exception e)
{
_logger.LogCritical(e,e.Message);
}
2025-02-24 23:02:49 +08:00
return true;
}
}
}