Files
RuinAdventurer/Scripts/Gameplay/Crafting/Inventory.cs
T

132 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
public class Inventory
{
public List<Item> items = new List<Item>();
public int maxInventorySize = 16;
public event EventHandler OnInventoryUpdate;
public bool AddItem(Item item, int amount)
{
if (GetFreeCapacity(item.data.Id, item.data.StackSize) < amount)
{
return false;
}
int remainingAmount = amount;
foreach (Item inventoryItem in items)
{
if (inventoryItem.data.Id != item.data.Id) continue;
if (inventoryItem.currentAmount >= inventoryItem.data.StackSize) continue;
int amountToAdd = Math.Min(
remainingAmount,
inventoryItem.data.StackSize - inventoryItem.currentAmount
);
inventoryItem.currentAmount += amountToAdd;
remainingAmount -= amountToAdd;
if (remainingAmount <= 0)
{
NotifyInventoryChanged();
return true;
}
}
while (remainingAmount > 0 && items.Count < maxInventorySize * GameData.maxRobotCount)
{
int amountToAdd = Math.Min(remainingAmount, item.data.StackSize);
items.Add(new Item { data = item.data, currentAmount = amountToAdd });
remainingAmount -= amountToAdd;
}
NotifyInventoryChanged();
return remainingAmount <= 0;
}
public bool CanCraft(List<Ingredient> neededIngredients, int amount)
{
foreach (Ingredient ingredient in neededIngredients)
{
if (GetItemAmount(ingredient.Item) < ingredient.Amount * amount)
{
return false;
}
}
return true;
}
public void RemoveItem(string id, int amount)
{
TryRemoveItem(id, amount);
}
public bool TryRemoveItem(string id, int amount)
{
if (GetItemAmount(id) < amount)
{
return false;
}
int remainingAmount = amount;
for (int i = items.Count - 1; i >= 0 && remainingAmount > 0; i--)
{
Item item = items[i];
if (item.data.Id != id) continue;
int removedAmount = Math.Min(item.currentAmount, remainingAmount);
item.currentAmount -= removedAmount;
remainingAmount -= removedAmount;
if (item.currentAmount <= 0)
{
items.RemoveAt(i);
}
}
NotifyInventoryChanged();
return true;
}
public int GetItemAmount(string id)
{
int amount = 0;
foreach (Item item in items)
{
if (item.data.Id == id)
{
amount += item.currentAmount;
}
}
return amount;
}
private void NotifyInventoryChanged()
{
OnInventoryUpdate?.Invoke(this, EventArgs.Empty);
}
private int GetFreeCapacity(string id, int stackSize)
{
int freeCapacity = 0;
foreach (Item item in items)
{
if (item.data.Id == id)
{
freeCapacity += stackSize - item.currentAmount;
}
}
int freeSlots = maxInventorySize * GameData.maxRobotCount - items.Count;
freeCapacity += freeSlots * stackSize;
return freeCapacity;
}
}