86 lines
1.9 KiB
C#
86 lines
1.9 KiB
C#
namespace Sasalka;
|
|
|
|
public abstract class AmmoUseableBase : UseableBase
|
|
{
|
|
private WeaponItemDefinition _cachedWeaponDef;
|
|
private InventoryItem _cachedAmmoItem;
|
|
|
|
protected InventoryItem AmmoItem => FindAmmoItem();
|
|
|
|
private InventoryItem FindAmmoItem()
|
|
{
|
|
var player = Dedugan.Local;
|
|
if (player?.Inventory == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
// Кэшируем WeaponDefinition для избежания повторных вызовов
|
|
if (_cachedWeaponDef == null)
|
|
{
|
|
_cachedWeaponDef = GetWeaponDefinition();
|
|
if (_cachedWeaponDef == null)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// Проверяем кэшированный результат
|
|
if (_cachedAmmoItem != null && _cachedAmmoItem.Count > 0)
|
|
{
|
|
return _cachedAmmoItem;
|
|
}
|
|
|
|
// Ищем патроны
|
|
foreach (var item in player.Inventory.Items)
|
|
{
|
|
if (item.Definition is AmmoItemDefinition ammoDef && ammoDef.IsCompatibleWith(_cachedWeaponDef.AmmoType))
|
|
{
|
|
_cachedAmmoItem = item;
|
|
return item;
|
|
}
|
|
}
|
|
|
|
_cachedAmmoItem = null;
|
|
return null;
|
|
}
|
|
|
|
protected virtual WeaponItemDefinition GetWeaponDefinition()
|
|
{
|
|
// Переопределите в наследниках для возврата определения оружия
|
|
return null;
|
|
}
|
|
|
|
public override bool CanUse()
|
|
{
|
|
var ammo = AmmoItem;
|
|
var baseCanUse = base.CanUse();
|
|
var hasAmmo = ammo != null && ammo.Count > 0;
|
|
|
|
return baseCanUse && hasAmmo;
|
|
}
|
|
|
|
public override void Use()
|
|
{
|
|
if (!CanUse())
|
|
return;
|
|
|
|
OnUse();
|
|
|
|
var ammo = AmmoItem;
|
|
if (ammo != null)
|
|
{
|
|
// Уменьшаем количество патронов
|
|
if (ammo.TryRemoveCount(1))
|
|
{
|
|
// Если патроны закончились, удаляем предмет из инвентаря
|
|
if (ammo.Count <= 0)
|
|
{
|
|
Dedugan.Local.Inventory.RemoveItem(ammo);
|
|
_cachedAmmoItem = null; // Очищаем кэш
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|