GameSessionRuntime.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Collections.Generic;
  3. using DevilLink2.Core;
  4. using DevilLink2.Interaction;
  5. namespace DevilLink2.Gameplay
  6. {
  7. /// <summary>Owns exactly one interaction subscription set and no duplicate board.
  8. /// Update-before-click makes timeout win at the deadline. A last-pair Matched freezes time
  9. /// immediately, before the existing 240ms delayed BoardCleared notification.</summary>
  10. public sealed class GameSessionRuntime : IDisposable
  11. {
  12. private readonly IMonotonicClock clock;
  13. private readonly HashSet<int> scoredTileIds = new HashSet<int>();
  14. private double lastRead;
  15. private bool disposed;
  16. public GameSession Session { get; }
  17. public SessionTimer Timer { get; }
  18. public SessionScore Score { get; }
  19. public BoardInteractionState Interaction { get; }
  20. public bool IsCleared { get; private set; }
  21. public bool IsTimedOut { get; private set; }
  22. public bool IsPaused => Timer.IsPaused;
  23. public bool IsFinished => IsCleared || IsTimedOut || Error != null;
  24. public string Error { get; private set; }
  25. public event Action TimedOut;
  26. public event Action<int> ClearBonusAwarded;
  27. public GameSessionRuntime(GameSession session, IMonotonicClock clock)
  28. {
  29. Session = session ?? throw new ArgumentNullException(nameof(session));
  30. if (!session.IsInitialized) throw new ArgumentException("Initialize the session first.", nameof(session));
  31. this.clock = clock ?? throw new ArgumentNullException(nameof(clock));
  32. GameplayTime.Read(clock, ref lastRead);
  33. Timer = new SessionTimer(session.Definition); Score = new SessionScore(clock);
  34. Interaction = new BoardInteractionState(session.Board, session.RandomSeed);
  35. Timer.Expired += OnExpired;
  36. Interaction.Matched += OnMatched;
  37. Interaction.InvalidMatch += OnInvalid;
  38. Interaction.BoardCleared += OnCleared;
  39. Interaction.Failed += OnFailed;
  40. Interaction.Initialize();
  41. }
  42. public void Update()
  43. {
  44. if (disposed) return;
  45. double before = lastRead;
  46. double now = GameplayTime.Read(clock, ref lastRead);
  47. Score.Update();
  48. Timer.Advance(now - before);
  49. if (!IsPaused && !IsTimedOut && Error == null) Interaction.Advance(now - before);
  50. }
  51. public TileClickResult Click(int row, int column)
  52. {
  53. Update();
  54. if (disposed || IsFinished || Timer.IsExpired || IsPaused) return TileClickResult.Ignored;
  55. return Interaction.Click(row, column);
  56. }
  57. public void Pause() { Update(); if (!disposed && !IsFinished) Timer.Pause(); }
  58. public void Resume() { Update(); if (!disposed && !IsFinished) Timer.Resume(); }
  59. public bool AddTime(double seconds)
  60. { Update(); return !disposed && !IsFinished && Timer.AddTime(seconds); }
  61. private void OnInvalid(Tile first, Tile second)
  62. { if (!disposed && !IsFinished && !IsPaused) Timer.ApplyInvalidMatchPenalty(); }
  63. private void OnMatched(PairMatch match)
  64. {
  65. if (disposed || IsFinished || Timer.IsExpired || IsPaused || scoredTileIds.Contains(match.First.Id) || scoredTileIds.Contains(match.Second.Id)) return;
  66. scoredTileIds.Add(match.First.Id); scoredTileIds.Add(match.Second.Id);
  67. // Mark last-pair completion before score callbacks can re-enter Update/Click.
  68. bool lastPair = Session.Board.RemainingTileCount == 0;
  69. if (lastPair) { IsCleared = true; Timer.Stop(); }
  70. Score.RegisterMatch();
  71. if (lastPair) AwardClear();
  72. }
  73. private void OnCleared()
  74. {
  75. if (disposed || IsFinished || Timer.IsExpired) return;
  76. IsCleared = true; Timer.Stop(); AwardClear();
  77. }
  78. private void AwardClear()
  79. {
  80. int bonus = Score.CompleteClear(Timer.HasTimer, Timer.RemainingTime);
  81. if (bonus > 0) ClearBonusAwarded?.Invoke(bonus);
  82. }
  83. private void OnExpired()
  84. {
  85. if (disposed || IsFinished) return;
  86. IsTimedOut = true; Score.EndWithoutBonus(); TimedOut?.Invoke();
  87. }
  88. private void OnFailed(string error)
  89. { if (!IsFinished) { Error = error; Timer.Stop(); Score.EndWithoutBonus(); } }
  90. public void Dispose()
  91. {
  92. if (disposed) return;
  93. disposed = true; Timer.Stop(); Score.EndWithoutBonus();
  94. Timer.Expired -= OnExpired;
  95. Interaction.Matched -= OnMatched; Interaction.InvalidMatch -= OnInvalid;
  96. Interaction.BoardCleared -= OnCleared; Interaction.Failed -= OnFailed;
  97. // Reuse the existing same-tile deselection, without attempting a new match.
  98. var selected = Interaction.Selected;
  99. if (selected != null) Interaction.Click(selected.Row, selected.Column);
  100. }
  101. }
  102. }