using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Ether { public class BackPackSystem : Singleton { private int maxNum = 100; /// /// 背包格子 /// private Dictionary gridDic = new Dictionary(); private Dictionary freeDic = new Dictionary(); public void Init() { } /// /// 放入背包 /// public bool PutIn(int itemId, int num) { PropItemData propItemData = PropItemSystem.Inst.GeneratePropItem(itemId, num); return PutIn(propItemData); } /// /// 放入背包 /// 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; } /// /// 取出道具 /// 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; } } } } /// /// 获取对应位置的道具数据 /// public PropItemData GetPropItemByGridIndex(int index) { if (gridDic.ContainsKey(index)) { return gridDic[index]; } return null; } /// /// 根据itemId获取对应的道具数量 /// 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; } } }