using System; using System.Collections.Generic; using System.Text; using UnityEngine; namespace BeiBao { /// /// 背包类 /// 背包是由多个格子组成的,每个格子都可以存放不同的物品。 /// public class Inventory { public int SlotCount { get; set; } // 背包格子的数量 private List slots; 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) { int remainingQuantity = quantity; foreach (var slot in slots) { if (remainingQuantity == 0) break; if (slot.IsEmpty) { // 如果格子为空,直接放入物品 remainingQuantity = item.AddQuantity(remainingQuantity); slot.AddItem(item, quantity - remainingQuantity); } else if (slot.Item.ItemID == item.ItemID && slot.Item.Quantity < slot.Item.MaxStack) { // 如果格子内物品与新物品相同,并且未满堆叠,堆叠物品 remainingQuantity = slot.Item.AddQuantity(remainingQuantity); } } return remainingQuantity == 0; } // 从背包中取出物品 public bool RemoveItem(int itemID, int quantity) { int remainingQuantity = quantity; foreach (var slot in slots) { if (remainingQuantity == 0) break; if (!slot.IsEmpty && slot.Item.ItemID == itemID) { remainingQuantity -= slot.Item.RemoveQuantity(remainingQuantity) ? remainingQuantity : 0; } } 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()); } } }