/// <summary>
/// 背包整理是游戏中常用的逻辑,将玩家目前背包中的所有格子,按照ID排序统一摆放,同时每个格子中的道具数量不能超过20.
/// 输入
/// [[100,4], [101, 5], [0, 0], [100, 5], [101, 8]],20
/// 输出
/// [[100, 9],[101,13]]
/// 注:空项清除
/// </summary>
/// <param name="vtBag">背包里项目编号以及个数,实质是二维数组</param>
/// <param name="maxStack">每项最大个数</param>
/// <returns></returns>
public List<List<int>> TidyBag(List<List<int>> vtBag, int maxStack) {
List<List<int>> bag = new List<List<int>>();//临时背包
for (int i = 0; i < vtBag.Count; i++) {//遍历所有项
if (vtBag[i][0] != 0) {//判断数量是否为0
int index = HasItem(vtBag[i][0], bag);//判断包里是否有该编号的物品
if (index == -1) {
bag.Add(vtBag[i]);
} else {
bag[index][1] += vtBag[i][1];
}
}
}
bag.Sort((a, b) => { return a[0] > b[0] ? 1 : -1; });//对bag排序
List<List<int>> lastBag = new List<List<int>>();
foreach (List<int> item in bag) {//遍历临时包内每一项
if (item[1] > maxStack) {//如果大于单项的阈值
for (int i = 0; i < item[1] / maxStack; i++) {//满个数的
lastBag.Add(new List<int> { item[0], maxStack });
}
lastBag.Add(new List<int> { item[0], item[1] % maxStack });//多余的
} else {
lastBag.Add(item);
}
}
return lastBag;
}
public int HasItem(int id, List<List<int>> bag) {//判断是否存在
for (int i = 0; i < bag.Count; i++) {
if (bag[i][0] == id) {
return i; //存在返回index
}
}
return -1; //返回-1则无此项
}