using System; using System.Collections.Generic; using System.Linq; using UnityEditor.Tilemaps; [Serializable] public class Inventory : IDataPersistence { private int capacity = 0; private Dictionary items = new Dictionary(); public Inventory(int capacity) { this.capacity = capacity; } public IReadOnlyDictionary 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(items); data.capacity = capacity; } }