ItemInventory.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System;
  2. namespace DevilLink2.Gameplay
  3. {
  4. public enum ItemType { Hint, Shuffle, Time }
  5. public sealed class ItemInventory
  6. {
  7. private readonly int[] counts;
  8. public ItemInventory(int hint = 1, int shuffle = 1, int time = 0)
  9. {
  10. if (hint < 0 || shuffle < 0 || time < 0) throw new ArgumentOutOfRangeException(nameof(hint));
  11. counts = new[] { hint, shuffle, time };
  12. }
  13. public int GetCount(ItemType type) { Validate(type); return counts[(int)type]; }
  14. internal bool CanAdd(ItemType type) => GetCount(type) < int.MaxValue;
  15. internal void Add(ItemType type) { Validate(type); counts[(int)type] = checked(counts[(int)type] + 1); }
  16. internal bool Consume(ItemType type)
  17. { if (GetCount(type) == 0) return false; counts[(int)type]--; return true; }
  18. internal static void Validate(ItemType type)
  19. { if (!Enum.IsDefined(typeof(ItemType), type)) throw new ArgumentOutOfRangeException(nameof(type)); }
  20. }
  21. public enum PurchaseStatus { Success, InsufficientCoins, DuplicateTransaction, InvalidItem, InvalidTransactionId, InventoryFull }
  22. public sealed class ShopService
  23. {
  24. private readonly PlayerEconomy economy;
  25. public ShopService(PlayerEconomy economy) { this.economy = economy ?? throw new ArgumentNullException(nameof(economy)); }
  26. public static int Price(ItemType type)
  27. {
  28. switch (type)
  29. {
  30. case ItemType.Hint: return 2000;
  31. case ItemType.Shuffle: return 5000;
  32. case ItemType.Time: return 3000;
  33. default: throw new ArgumentOutOfRangeException(nameof(type));
  34. }
  35. }
  36. // The caller reuses the same ID when delivering/retrying the same logical purchase.
  37. public PurchaseStatus TryBuy(ItemType type, Guid transactionId) => economy.Purchase(type, transactionId);
  38. }
  39. }