using System; using System.Collections.Generic; using System.Text; using UnityEngine; namespace BeiBao { /// /// 背包类 /// 背包是由多个格子组成的,每个格子都可以存放不同的物品。 /// public class Inventory { private int _slotCount; public int SlotCount => _slotCount; // 背包格子的数量 private List slots; public IReadOnlyList Slots => slots; public Action> RefreshInventorySlot; public Inventory(int slotCount) { _slotCount = slotCount; slots = new List(); for (int i = 0; i < _slotCount; i++) { slots.Add(new InventorySlot()); } } // 向背包中添加物品 public bool AddItem(Item item, int quantity, out int restCount) { int remainingQuantity = quantity; int tmpQuantity = quantity; foreach (var slot in slots) { if (remainingQuantity == 0) break; if (slot.IsEmpty) { var tmpItem = new Item(item.ItemName, item.ItemID, item.MaxStack); // 如果格子为空,直接放入物品 remainingQuantity = tmpItem.CheckAddQuantity(remainingQuantity); slot.AddItem(tmpItem, tmpQuantity - remainingQuantity); } else if (slot.Item.ItemID == item.ItemID && slot.Item.Quantity < slot.Item.MaxStack) { // 如果格子内物品与新物品相同,并且未满堆叠,堆叠物品 remainingQuantity = slot.Item.CheckAddQuantity(remainingQuantity); slot.Item.AddQuantity(tmpQuantity - remainingQuantity); } tmpQuantity = remainingQuantity; } Debug.Log($"向背包中添加{item.ItemName} 数量为:{quantity}"); RefreshInventorySlot?.Invoke(Slots); restCount = remainingQuantity; return remainingQuantity == 0; } // 从背包中取出物品 public bool RemoveItem(int itemID, int quantity, out int restCount) { int remainingQuantity = quantity; int tmpQuantity = quantity; for (var i = slots.Count - 1; i >= 0; i--) { if (remainingQuantity == 0) break; var slot = slots[i]; if (!slot.IsEmpty && slot.Item.ItemID == itemID) { remainingQuantity = slot.Item.CheckRemoveQuantity(remainingQuantity); slot.RemoveItem(tmpQuantity - remainingQuantity); tmpQuantity = remainingQuantity; } } Debug.Log($"向背包中取出物品id{itemID} 数量为:{quantity}"); RefreshInventorySlot?.Invoke(Slots); restCount = remainingQuantity; return remainingQuantity == 0; } // 查看背包内容 public void ShowInventory() { StringBuilder sb = new StringBuilder(); foreach (var slot in slots) { if (!slot.IsEmpty) { sb.AppendLine($"{slot.Item.ItemName} - {slot.Item.Quantity}/{slot.Item.MaxStack}"); } } Debug.Log(sb.ToString()); } } }