91 lines
3.1 KiB
C#

namespace ET.Server
{
[FriendOf(typeof(BagComponent))]
[FriendOf(typeof(ItemUnit))]
[FriendOf(typeof(Hero))]
public static class HeroEquipService
{
private static bool IsEquipItem(int itemId)
{
return itemId >= 10000;
}
public static bool TryWearEquip(Player player, long heroId, long itemIndex, int slotIndex, out string reason)
{
reason = string.Empty;
BagComponent bag = player?.GetComponent<BagComponent>();
Hero hero = player?.GetComponent<HeroComponent>()?.GetHero(heroId);
if (bag == null || hero == null)
{
reason = "hero_or_bag_not_found";
return false;
}
if (!bag.ItemMap.TryGetValue(itemIndex, out EntityRef<ItemUnit> unitRef))
{
reason = "equip_not_found";
return false;
}
ItemUnit unit = unitRef;
if (!IsEquipItem(unit.ItemId))
{
reason = "item_not_equip";
return false;
}
if (hero.EquipSlots.TryGetValue(slotIndex, out long oldItemIndex) && oldItemIndex > 0)
{
bag.SetHeroIdOnEquip(oldItemIndex, 0);
}
if (unit.HeroId > 0 && unit.HeroId != heroId)
{
Hero oldHero = player.GetComponent<HeroComponent>()?.GetHero(unit.HeroId);
if (oldHero != null)
{
foreach (var pair in oldHero.EquipSlots)
{
if (pair.Value == unit.ItemIndex)
{
oldHero.EquipSlots[pair.Key] = 0;
break;
}
}
}
}
hero.EquipSlots[slotIndex] = unit.ItemIndex;
bag.SetHeroIdOnEquip(unit.ItemIndex, heroId);
player.SetDirty();
LogExtensions.Audit("Hero", "HeroWearEquip", $"{{\"playerId\":{player.Id},\"heroId\":{heroId},\"itemIndex\":{itemIndex},\"slotIndex\":{slotIndex}}}");
return true;
}
public static bool TryTakeOffEquip(Player player, long heroId, int slotIndex, out long itemIndex, out string reason)
{
itemIndex = 0;
reason = string.Empty;
BagComponent bag = player?.GetComponent<BagComponent>();
Hero hero = player?.GetComponent<HeroComponent>()?.GetHero(heroId);
if (bag == null || hero == null)
{
reason = "hero_or_bag_not_found";
return false;
}
if (!hero.EquipSlots.TryGetValue(slotIndex, out itemIndex) || itemIndex <= 0)
{
reason = "slot_empty";
return false;
}
hero.EquipSlots[slotIndex] = 0;
bag.SetHeroIdOnEquip(itemIndex, 0);
player.SetDirty();
LogExtensions.Audit("Hero", "HeroTakeOffEquip", $"{{\"playerId\":{player.Id},\"heroId\":{heroId},\"itemIndex\":{itemIndex},\"slotIndex\":{slotIndex}}}");
return true;
}
}
}