62 lines
1.5 KiB
C#
62 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using UnityEditor.Tilemaps;
|
|
|
|
[Serializable]
|
|
public class Inventory : IDataPersistence<InventoryData>
|
|
{
|
|
private int capacity = 0;
|
|
private Dictionary<string, int> items = new Dictionary<string, int>();
|
|
|
|
public Inventory(int capacity)
|
|
{
|
|
this.capacity = capacity;
|
|
}
|
|
|
|
public IReadOnlyDictionary<string, int> Items => items;
|
|
|
|
public int Capacity => capacity;
|
|
|
|
public int Load => items.Sum(kvp => kvp.Value);
|
|
|
|
public int Free => Capacity < 0 ? int.MaxValue : Capacity - Load;
|
|
|
|
public override string ToString()
|
|
{
|
|
string text = string.Join(Environment.NewLine, items);
|
|
text += Environment.NewLine + Environment.NewLine + $"Занято {Load}";
|
|
if (Capacity >= 0)
|
|
text += $", свободно {Capacity - Load}";
|
|
|
|
return text;
|
|
}
|
|
|
|
public int Add(string key, int value, bool allowPartialAdd = false)
|
|
{
|
|
if (!allowPartialAdd && (Capacity >= 0) && (Capacity < Load + value))
|
|
return 0;
|
|
|
|
value = Math.Min(value, Free);
|
|
|
|
if (items.ContainsKey(key))
|
|
items[key] += value;
|
|
else
|
|
items[key] = value;
|
|
|
|
return value;
|
|
}
|
|
|
|
public void LoadData(InventoryData data)
|
|
{
|
|
items = data.items;
|
|
capacity = data.capacity;
|
|
}
|
|
|
|
public void SaveData(InventoryData data)
|
|
{
|
|
data.items = new SerializableDictionary<string, int>(items);
|
|
data.capacity = capacity;
|
|
}
|
|
}
|