| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace DevilLink2.Gameplay
- {
- /// <summary>One player-owned mutation gateway for currency, purchases and inventory.</summary>
- public enum VictoryRewardStatus { Granted, CapacityExceeded, AlreadyProcessed }
- public sealed class PlayerEconomy
- {
- private readonly HashSet<Guid> processed = new HashSet<Guid>();
- private readonly IUtcClock clock;
- internal object SyncRoot { get; } = new object();
- internal IUtcClock UtcClock => clock;
- public RewardState Rewards { get; }
- public long Coins { get; private set; }
- public long SpinTickets { get; private set; }
- public ItemInventory Inventory { get; }
- public CoinLedger Ledger { get; } = new CoinLedger();
- public IReadOnlyList<Guid> ProcessedTransactionIds => Array.AsReadOnly(processed.OrderBy(id => id).ToArray());
- public event Action<PlayerChangeKind> PersistentStateChanged;
- public PlayerEconomy(long coins = 2000, long spinTickets = 0, IUtcClock clock = null,
- ItemInventory inventory = null, IEnumerable<CoinTransaction> ledger = null, IEnumerable<Guid> processedIds = null, RewardState rewards = null)
- {
- if (coins < 0) throw new ArgumentOutOfRangeException(nameof(coins));
- if (spinTickets < 0) throw new ArgumentOutOfRangeException(nameof(spinTickets));
- this.clock = clock ?? new SystemUtcClock(); Inventory = inventory ?? new ItemInventory();
- Coins = coins; SpinTickets = spinTickets; Rewards = rewards ?? new RewardState();
- // Saved ledger is newest first. Replay in reverse to preserve ties without changing balances.
- if (ledger != null) foreach (var entry in ledger.Reverse())
- if (entry != null && processed.Add(entry.Id)) Ledger.Append(entry);
- foreach (var operation in Rewards.Operations) processed.Add(operation.Id);
- if (processedIds != null) foreach (var id in processedIds) if (id != Guid.Empty) processed.Add(id);
- }
- private void Commit(CoinTransaction transaction, long coins, long tickets)
- { processed.Add(transaction.Id); Coins = coins; SpinTickets = tickets; Ledger.Append(transaction); }
- internal VictoryRewardStatus GrantVictory(GameSession session)
- {
- lock (SyncRoot)
- {
- if (processed.Contains(session.Id)) return VictoryRewardStatus.AlreadyProcessed;
- if (Coins > long.MaxValue - session.Definition.ClearCoinReward ||
- SpinTickets > long.MaxValue - session.Definition.ClearTicketReward)
- {
- // Consume the settlement identity without crediting either resource or fabricating a ledger entry.
- processed.Add(session.Id);
- return VictoryRewardStatus.CapacityExceeded;
- }
- long coins = checked(Coins + session.Definition.ClearCoinReward);
- long tickets = checked(SpinTickets + session.Definition.ClearTicketReward);
- var transaction = new CoinTransaction(session.Id, session.Definition.ClearCoinReward, CoinCategory.LevelVictory,
- clock.UtcNow, session.Mode + " level " + session.Definition.Level);
- Commit(transaction, coins, tickets);
- // GameFlowController saves after progress is also committed, through Settled.
- return VictoryRewardStatus.Granted;
- }
- }
- internal PurchaseStatus Purchase(ItemType type, Guid id)
- {
- lock (SyncRoot)
- {
- if (!Enum.IsDefined(typeof(ItemType), type)) return PurchaseStatus.InvalidItem;
- if (id == Guid.Empty) return PurchaseStatus.InvalidTransactionId;
- if (processed.Contains(id)) return PurchaseStatus.DuplicateTransaction;
- int price = ShopService.Price(type);
- if (Coins < price) return PurchaseStatus.InsufficientCoins;
- if (!Inventory.CanAdd(type)) return PurchaseStatus.InventoryFull;
- var transaction = new CoinTransaction(id, -price, CoinCategory.ShopPurchase, clock.UtcNow, "Shop: " + type);
- Inventory.Add(type); Commit(transaction, Coins - price, SpinTickets);
- PersistentStateChanged?.Invoke(PlayerChangeKind.Purchase);
- return PurchaseStatus.Success;
- }
- }
- // Shared extension point for other reward producers.
- public bool TryCredit(Guid id, long amount, string description)
- {
- lock (SyncRoot)
- {
- if (id == Guid.Empty || amount <= 0 || processed.Contains(id)) return false;
- long coins = checked(Coins + amount);
- var transaction = new CoinTransaction(id, amount, CoinCategory.Reward, clock.UtcNow, description);
- Commit(transaction, coins, SpinTickets); PersistentStateChanged?.Invoke(PlayerChangeKind.Reward); return true;
- }
- }
- internal RewardResult CheckRewardOperation(Guid id)
- {
- if (id == Guid.Empty) return new RewardResult(RewardStatus.InvalidOperationId, SpinTickets);
- return processed.Contains(id) ? new RewardResult(RewardStatus.DuplicateOperation, SpinTickets, Rewards.Find(id)) : null;
- }
- internal RewardStatus RewardCapacity(RewardDefinition reward)
- {
- if (reward.Kind == RewardKind.Coins) return Coins > long.MaxValue - reward.Amount ? RewardStatus.CoinOverflow : RewardStatus.Success;
- return Inventory.GetCount((ItemType)((int)reward.Kind - 1)) > int.MaxValue - reward.Amount ? RewardStatus.InventoryOverflow : RewardStatus.Success;
- }
- internal RewardResult ApplyReward(Guid id, RewardOperationKind kind, int number, DateTimeOffset now, bool useTicket)
- {
- var duplicate = CheckRewardOperation(id);
- if (duplicate != null) return duplicate;
- if (useTicket && SpinTickets == 0) return new RewardResult(RewardStatus.InsufficientTickets, SpinTickets);
- RewardOperationRecord receipt; CoinTransaction transaction = null;
- long coins = Coins; long tickets = SpinTickets - (useTicket ? 1 : 0);
- RewardDefinition reward; ItemType item = ItemType.Hint;
- try
- {
- receipt = new RewardOperationRecord(id, kind, number, now, useTicket, tickets);
- reward = receipt.Reward;
- var capacity = RewardCapacity(reward);
- if (capacity != RewardStatus.Success) return new RewardResult(capacity, SpinTickets, number: number, reward: reward);
- if (reward.Kind == RewardKind.Coins)
- {
- coins = checked(Coins + reward.Amount);
- transaction = new CoinTransaction(id, reward.Amount,
- kind == RewardOperationKind.DailyCheckIn ? CoinCategory.DailyCheckIn : CoinCategory.LuckyWheel,
- now, kind + " " + number);
- }
- else
- {
- item = (ItemType)((int)reward.Kind - 1);
- if (Inventory.GetCount(item) > int.MaxValue - reward.Amount)
- return new RewardResult(RewardStatus.InventoryOverflow, SpinTickets, number: number, reward: reward);
- }
- }
- catch (OverflowException) { return new RewardResult(RewardStatus.CoinOverflow, SpinTickets); }
- catch (ArgumentException error) { return new RewardResult(RewardStatus.OperationFailed, SpinTickets, error: error.Message); }
- // All external clock/RNG calls, validation and arithmetic have finished before mutation.
- // No callbacks run until balances, inventory, calendar state and receipts are committed.
- if (transaction != null) Commit(transaction, coins, tickets);
- else { Inventory.Add(item); SpinTickets = tickets; processed.Add(id); }
- Rewards.Commit(receipt);
- string notificationError = null;
- var listeners = PersistentStateChanged;
- if (listeners != null) foreach (Action<PlayerChangeKind> listener in listeners.GetInvocationList())
- {
- try { listener(PlayerChangeKind.Reward); }
- catch (Exception error) { notificationError = error.Message; } // Committed success stays success; later save listeners still run.
- }
- return new RewardResult(RewardStatus.Success, SpinTickets, receipt, error: notificationError);
- }
- internal void ConsumeItem(ItemType type)
- {
- lock (SyncRoot)
- {
- if (!Inventory.Consume(type)) throw new InvalidOperationException("Reserved item is no longer available.");
- }
- }
- internal void NotifyItemUsed() { PersistentStateChanged?.Invoke(PlayerChangeKind.ItemUsed); }
- }
- }
|