using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 物品库存
///
public class Inventory {
/// 背包容量
public int capacity;
/// 插槽列表
public List slots;
/// 改变事件
public event Action OnChange;
/// 物品库存
public Inventory(int capacity) {
this.capacity = capacity;
slots = new List();
for (int i = 0; i < capacity; i++) { slots.Add(new InventorySlot()); }
}
/// 应用修改
public void Apply() => OnChange?.Invoke(this);
/// 遍历数组
public void ForEach(Action action) => slots.ForEach(action);
/// 添加物品
public void AddItem(DataItem item, int count) {
int remain = MergeToSlots(item, count);
// 如果还有剩余,按照MaxStack分批放入空位
if (remain > 0) { AddToSlots(item, remain, true); }
OnChange?.Invoke(this);
}
/// 添加物品
public void AddToSlots(DataItem item, int count, bool isWhile) {
(bool isComplete, int remain) = AddToSlots(item, count);
if (!isComplete || remain == 0 || !isWhile) { return; }
AddToSlots(item, remain, isWhile);
}
/// 添加到插槽 bool = 是否添加成功,int = 余量
public (bool, int) AddToSlots(DataItem item, int count) {
InventorySlot emptySlot = slots.FirstOrDefault(s => s.item == null);
if (emptySlot == null) { return (false, count); }
int addCount = Mathf.Min(count, item.MaxStack);
emptySlot.Settings(item, addCount);
return (true, count - addCount);
}
/// 合并到插槽
public int MergeToSlots(DataItem item, int count) {
// 查询所有可合并的插槽
List sameSlots = slots.Where(slot => slot.Same(item)).ToList();
// 合并到已有插槽
sameSlots.ForEach(obj => MergeToSlots(obj, ref count));
return count;
}
/// 合并到插槽
public void MergeToSlots(InventorySlot slot, ref int count) {
int canAdd = slot.MaxStack - slot.count;
int addCount = Mathf.Min(canAdd, count);
slot.count += addCount;
count -= addCount;
}
}
///
/// 库存插槽
///
public class InventorySlot {
/// 数量
public int count;
/// 物品
public DataItem item;
// /// 图片
public Sprite Sprite => item != null ? item.sprite : null;
// /// 堆叠数量
public int MaxStack => item != null ? item.MaxStack : 0;
public InventorySlot() { }
public InventorySlot(DataItem item, int count) {
this.item = item;
this.count = count;
}
/// 设置
public void Settings(DataItem item, int count) {
this.item = item;
this.count = count;
}
/// 是否相同
public bool Same(DataItem obj) {
return item != null && item.name == obj.name && count < MaxStack;
}
}