IndieGame/client/Assets/Scripts/System/PropItem/BackPack/BackPackSystem.cs

185 lines
4.7 KiB
C#
Raw Normal View History

2024-10-11 10:12:15 +08:00

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Ether
{
public class BackPackSystem : Singleton<BackPackSystem>
{
private int maxNum = 100;
/// <summary>
/// 背包格子
/// </summary>
private Dictionary<int, PropItemData> gridDic = new Dictionary<int, PropItemData>();
private Dictionary<int, PropItemData> freeDic = new Dictionary<int, PropItemData>();
public void Init()
{
}
/// <summary>
/// 放入背包
/// </summary>
public bool PutIn(int itemId, int num)
{
PropItemData propItemData = PropItemSystem.Inst.GeneratePropItem(itemId, num);
return PutIn(propItemData);
}
/// <summary>
/// 放入背包
/// </summary>
public bool PutIn(PropItemData propItemData)
{
//不占背包格的物品
if (!propItemData.PropItemTable.Occupy)
{
if (freeDic.TryGetValue(propItemData.itemId, out PropItemData bagItem))
{
bagItem.num += propItemData.num;
propItemData.PushPool();
}
else
{
freeDic.Add(propItemData.itemId, propItemData);
}
return true;
}
//占用背包格的物品
int firstEmptyIndex = -1;
for (int i = 0; i < maxNum; i++)
{
if (!gridDic.ContainsKey(i))
{
if (firstEmptyIndex == -1)
{
firstEmptyIndex = i;
}
continue;
}
PropItemData bagItem = gridDic[i];
if (bagItem.itemId == propItemData.itemId)
{
bagItem.num += propItemData.num;
propItemData.PushPool();
return true;
}
}
if (firstEmptyIndex == -1)
{
Debug.LogError("背包已满!");
return false;
}
gridDic.Add(firstEmptyIndex, propItemData);
return true;
}
/// <summary>
/// 取出道具
/// </summary>
public void TakeOut(int itemId, int num)
{
//不占背包格的物品
if (freeDic.TryGetValue(itemId, out PropItemData freeBagItem))
{
freeBagItem.num -= num;
if (freeBagItem.num <= 0)
{
freeBagItem.PushPool();
freeDic.Remove(itemId);
}
return;
}
//占用背包格的物品
int removeNum = num;
for (int i = 0; i < maxNum; i++)
{
if (!gridDic.ContainsKey(i))
{
continue;
}
PropItemData bagItem = gridDic[i];
if (bagItem.itemId == itemId)
{
if (bagItem.num < removeNum)
{
removeNum -= bagItem.num;
bagItem.num = 0;
}
else
{
bagItem.num -= removeNum;
removeNum = 0;
}
if (bagItem.num == 0)
{
bagItem.PushPool();
gridDic.Remove(i);
}
if (removeNum == 0)
{
return;
}
}
}
}
/// <summary>
/// 获取对应位置的道具数据
/// </summary>
public PropItemData GetPropItemByGridIndex(int index)
{
if (gridDic.ContainsKey(index))
{
return gridDic[index];
}
return null;
}
/// <summary>
/// 根据itemId获取对应的道具数量
/// </summary>
public int GetPropItemNumByItemId(int itemId)
{
//不占背包格的物品
if (freeDic.TryGetValue(itemId, out PropItemData bagItem))
{
return bagItem.num;
}
//占用背包格的物品
int haveNum = 0;
foreach (var itemPair in gridDic)
{
if (itemPair.Value.itemId == itemId)
{
haveNum += itemPair.Value.num;
}
}
return haveNum;
}
}
}