PlayerEconomy.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace DevilLink2.Gameplay
  5. {
  6. /// <summary>One player-owned mutation gateway for currency, purchases and inventory.</summary>
  7. public enum VictoryRewardStatus { Granted, CapacityExceeded, AlreadyProcessed }
  8. public sealed class PlayerEconomy
  9. {
  10. private readonly HashSet<Guid> processed = new HashSet<Guid>();
  11. private readonly IUtcClock clock;
  12. internal object SyncRoot { get; } = new object();
  13. internal IUtcClock UtcClock => clock;
  14. public RewardState Rewards { get; }
  15. public long Coins { get; private set; }
  16. public long SpinTickets { get; private set; }
  17. public ItemInventory Inventory { get; }
  18. public CoinLedger Ledger { get; } = new CoinLedger();
  19. public IReadOnlyList<Guid> ProcessedTransactionIds => Array.AsReadOnly(processed.OrderBy(id => id).ToArray());
  20. public event Action<PlayerChangeKind> PersistentStateChanged;
  21. public PlayerEconomy(long coins = 2000, long spinTickets = 0, IUtcClock clock = null,
  22. ItemInventory inventory = null, IEnumerable<CoinTransaction> ledger = null, IEnumerable<Guid> processedIds = null, RewardState rewards = null)
  23. {
  24. if (coins < 0) throw new ArgumentOutOfRangeException(nameof(coins));
  25. if (spinTickets < 0) throw new ArgumentOutOfRangeException(nameof(spinTickets));
  26. this.clock = clock ?? new SystemUtcClock(); Inventory = inventory ?? new ItemInventory();
  27. Coins = coins; SpinTickets = spinTickets; Rewards = rewards ?? new RewardState();
  28. // Saved ledger is newest first. Replay in reverse to preserve ties without changing balances.
  29. if (ledger != null) foreach (var entry in ledger.Reverse())
  30. if (entry != null && processed.Add(entry.Id)) Ledger.Append(entry);
  31. foreach (var operation in Rewards.Operations) processed.Add(operation.Id);
  32. if (processedIds != null) foreach (var id in processedIds) if (id != Guid.Empty) processed.Add(id);
  33. }
  34. private void Commit(CoinTransaction transaction, long coins, long tickets)
  35. { processed.Add(transaction.Id); Coins = coins; SpinTickets = tickets; Ledger.Append(transaction); }
  36. internal VictoryRewardStatus GrantVictory(GameSession session)
  37. {
  38. lock (SyncRoot)
  39. {
  40. if (processed.Contains(session.Id)) return VictoryRewardStatus.AlreadyProcessed;
  41. if (Coins > long.MaxValue - session.Definition.ClearCoinReward ||
  42. SpinTickets > long.MaxValue - session.Definition.ClearTicketReward)
  43. {
  44. // Consume the settlement identity without crediting either resource or fabricating a ledger entry.
  45. processed.Add(session.Id);
  46. return VictoryRewardStatus.CapacityExceeded;
  47. }
  48. long coins = checked(Coins + session.Definition.ClearCoinReward);
  49. long tickets = checked(SpinTickets + session.Definition.ClearTicketReward);
  50. var transaction = new CoinTransaction(session.Id, session.Definition.ClearCoinReward, CoinCategory.LevelVictory,
  51. clock.UtcNow, session.Mode + " level " + session.Definition.Level);
  52. Commit(transaction, coins, tickets);
  53. // GameFlowController saves after progress is also committed, through Settled.
  54. return VictoryRewardStatus.Granted;
  55. }
  56. }
  57. internal PurchaseStatus Purchase(ItemType type, Guid id)
  58. {
  59. lock (SyncRoot)
  60. {
  61. if (!Enum.IsDefined(typeof(ItemType), type)) return PurchaseStatus.InvalidItem;
  62. if (id == Guid.Empty) return PurchaseStatus.InvalidTransactionId;
  63. if (processed.Contains(id)) return PurchaseStatus.DuplicateTransaction;
  64. int price = ShopService.Price(type);
  65. if (Coins < price) return PurchaseStatus.InsufficientCoins;
  66. if (!Inventory.CanAdd(type)) return PurchaseStatus.InventoryFull;
  67. var transaction = new CoinTransaction(id, -price, CoinCategory.ShopPurchase, clock.UtcNow, "Shop: " + type);
  68. Inventory.Add(type); Commit(transaction, Coins - price, SpinTickets);
  69. PersistentStateChanged?.Invoke(PlayerChangeKind.Purchase);
  70. return PurchaseStatus.Success;
  71. }
  72. }
  73. // Shared extension point for other reward producers.
  74. public bool TryCredit(Guid id, long amount, string description)
  75. {
  76. lock (SyncRoot)
  77. {
  78. if (id == Guid.Empty || amount <= 0 || processed.Contains(id)) return false;
  79. long coins = checked(Coins + amount);
  80. var transaction = new CoinTransaction(id, amount, CoinCategory.Reward, clock.UtcNow, description);
  81. Commit(transaction, coins, SpinTickets); PersistentStateChanged?.Invoke(PlayerChangeKind.Reward); return true;
  82. }
  83. }
  84. internal RewardResult CheckRewardOperation(Guid id)
  85. {
  86. if (id == Guid.Empty) return new RewardResult(RewardStatus.InvalidOperationId, SpinTickets);
  87. return processed.Contains(id) ? new RewardResult(RewardStatus.DuplicateOperation, SpinTickets, Rewards.Find(id)) : null;
  88. }
  89. internal RewardStatus RewardCapacity(RewardDefinition reward)
  90. {
  91. if (reward.Kind == RewardKind.Coins) return Coins > long.MaxValue - reward.Amount ? RewardStatus.CoinOverflow : RewardStatus.Success;
  92. return Inventory.GetCount((ItemType)((int)reward.Kind - 1)) > int.MaxValue - reward.Amount ? RewardStatus.InventoryOverflow : RewardStatus.Success;
  93. }
  94. internal RewardResult ApplyReward(Guid id, RewardOperationKind kind, int number, DateTimeOffset now, bool useTicket)
  95. {
  96. var duplicate = CheckRewardOperation(id);
  97. if (duplicate != null) return duplicate;
  98. if (useTicket && SpinTickets == 0) return new RewardResult(RewardStatus.InsufficientTickets, SpinTickets);
  99. RewardOperationRecord receipt; CoinTransaction transaction = null;
  100. long coins = Coins; long tickets = SpinTickets - (useTicket ? 1 : 0);
  101. RewardDefinition reward; ItemType item = ItemType.Hint;
  102. try
  103. {
  104. receipt = new RewardOperationRecord(id, kind, number, now, useTicket, tickets);
  105. reward = receipt.Reward;
  106. var capacity = RewardCapacity(reward);
  107. if (capacity != RewardStatus.Success) return new RewardResult(capacity, SpinTickets, number: number, reward: reward);
  108. if (reward.Kind == RewardKind.Coins)
  109. {
  110. coins = checked(Coins + reward.Amount);
  111. transaction = new CoinTransaction(id, reward.Amount,
  112. kind == RewardOperationKind.DailyCheckIn ? CoinCategory.DailyCheckIn : CoinCategory.LuckyWheel,
  113. now, kind + " " + number);
  114. }
  115. else
  116. {
  117. item = (ItemType)((int)reward.Kind - 1);
  118. if (Inventory.GetCount(item) > int.MaxValue - reward.Amount)
  119. return new RewardResult(RewardStatus.InventoryOverflow, SpinTickets, number: number, reward: reward);
  120. }
  121. }
  122. catch (OverflowException) { return new RewardResult(RewardStatus.CoinOverflow, SpinTickets); }
  123. catch (ArgumentException error) { return new RewardResult(RewardStatus.OperationFailed, SpinTickets, error: error.Message); }
  124. // All external clock/RNG calls, validation and arithmetic have finished before mutation.
  125. // No callbacks run until balances, inventory, calendar state and receipts are committed.
  126. if (transaction != null) Commit(transaction, coins, tickets);
  127. else { Inventory.Add(item); SpinTickets = tickets; processed.Add(id); }
  128. Rewards.Commit(receipt);
  129. string notificationError = null;
  130. var listeners = PersistentStateChanged;
  131. if (listeners != null) foreach (Action<PlayerChangeKind> listener in listeners.GetInvocationList())
  132. {
  133. try { listener(PlayerChangeKind.Reward); }
  134. catch (Exception error) { notificationError = error.Message; } // Committed success stays success; later save listeners still run.
  135. }
  136. return new RewardResult(RewardStatus.Success, SpinTickets, receipt, error: notificationError);
  137. }
  138. internal void ConsumeItem(ItemType type)
  139. {
  140. lock (SyncRoot)
  141. {
  142. if (!Inventory.Consume(type)) throw new InvalidOperationException("Reserved item is no longer available.");
  143. }
  144. }
  145. internal void NotifyItemUsed() { PersistentStateChanged?.Invoke(PlayerChangeKind.ItemUsed); }
  146. }
  147. }