GameFlowController.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. using System;
  2. using DevilLink2.Interaction;
  3. namespace DevilLink2.Gameplay
  4. {
  5. /// <summary>Single lifecycle/settlement authority. Commands invoked inside its notifications
  6. /// are rejected; consumers can invoke the next command after the current update/click returns.
  7. /// A restart replaces the session. The optional one-time ad revive reopens only a timed-out run.</summary>
  8. public sealed class GameFlowController : IDisposable
  9. {
  10. private readonly GameSessionFactory factory = new GameSessionFactory();
  11. private readonly IMonotonicClock clock;
  12. private int nextSeed;
  13. private bool busy, disposed, disposeRequested;
  14. private Action<int> clearHandler;
  15. private Action timeoutHandler;
  16. public GameFlowState State { get; private set; } = GameFlowState.Ready;
  17. public GameSessionRuntime Runtime { get; private set; }
  18. public ModeProgress Progress { get; }
  19. public PlayerEconomy Economy { get; }
  20. public ItemUseService Items { get; }
  21. public GameResult Result { get; private set; }
  22. public bool HasAdRevived { get; private set; }
  23. public bool CanAdRevive => !disposed && !HasAdRevived && State == GameFlowState.Defeat && Runtime.IsTimedOut && Runtime.Timer.HasTimer;
  24. public bool TryAdRevive(Guid sessionId) => Execute(() => {
  25. if (!CanAdRevive || Runtime.Session.Id != sessionId || !Runtime.ReviveTimedOut()) return false;
  26. HasAdRevived = true; Result = null; Transition(GameFlowState.Running); return true;
  27. });
  28. public event Action<GameFlowState, GameFlowState> StateChanged;
  29. public event Action<GameSessionRuntime> SessionChanged;
  30. public event Action<GameResult> Settled;
  31. public event Action LobbyRequested;
  32. public GameFlowController(GameMode mode, ModeProgress progress, PlayerEconomy economy,
  33. IMonotonicClock clock, int randomSeed = 2026)
  34. {
  35. Progress = progress ?? throw new ArgumentNullException(nameof(progress));
  36. Economy = economy ?? throw new ArgumentNullException(nameof(economy));
  37. this.clock = clock ?? throw new ArgumentNullException(nameof(clock));
  38. nextSeed = unchecked(randomSeed + 1);
  39. Runtime = Prepare(factory.Create(mode, progress, randomSeed));
  40. AttachRuntime();
  41. Items = new ItemUseService(this, new Random(unchecked(randomSeed ^ 0x7a13)));
  42. }
  43. private GameSessionRuntime Prepare(GameSession session)
  44. {
  45. var runtime = new GameSessionRuntime(session, clock);
  46. runtime.Timer.Pause(); // Ready must not consume time before Start.
  47. return runtime;
  48. }
  49. private bool Execute(Func<bool> command)
  50. {
  51. if (disposed || busy) return false;
  52. busy = true;
  53. try { return command(); }
  54. finally { busy = false; if (disposeRequested) Dispose(); }
  55. }
  56. // All state assignments and notifications pass through this single transition gate.
  57. private void Transition(GameFlowState next)
  58. {
  59. var previous = State;
  60. bool allowed = next == GameFlowState.Abandoned && previous != GameFlowState.Abandoned ||
  61. previous == GameFlowState.Ready && next == GameFlowState.Running ||
  62. previous == GameFlowState.Running && (next == GameFlowState.Paused || next == GameFlowState.Victory || next == GameFlowState.Defeat) ||
  63. previous == GameFlowState.Paused && next == GameFlowState.Running ||
  64. (previous == GameFlowState.Paused || previous == GameFlowState.Victory || previous == GameFlowState.Defeat) && next == GameFlowState.Ready;
  65. allowed = allowed || previous == GameFlowState.Defeat && next == GameFlowState.Running && HasAdRevived;
  66. if (!allowed) throw new InvalidOperationException("Illegal flow transition: " + previous + " -> " + next);
  67. State = next; StateChanged?.Invoke(previous, next);
  68. }
  69. public bool Start() => Execute(StartCore);
  70. private bool StartCore()
  71. {
  72. if (State != GameFlowState.Ready) return false;
  73. Runtime.Resume(); Transition(GameFlowState.Running); return true;
  74. }
  75. public bool Pause() => Execute(() =>
  76. {
  77. if (State != GameFlowState.Running) return false;
  78. Runtime.Pause();
  79. if (State != GameFlowState.Running) return false; // Update-before-pause may have expired.
  80. Transition(GameFlowState.Paused); return true;
  81. });
  82. public bool Resume() => Execute(() =>
  83. {
  84. if (State != GameFlowState.Paused) return false;
  85. Runtime.Resume(); Transition(GameFlowState.Running); return true;
  86. });
  87. public void Update()
  88. { Execute(() => { if (State != GameFlowState.Abandoned) Runtime.Update(); return true; }); }
  89. public TileClickResult Click(int row, int column)
  90. {
  91. var result = TileClickResult.Ignored;
  92. Execute(() => { if (State == GameFlowState.Running) result = Runtime.Click(row, column); return true; });
  93. return result;
  94. }
  95. public bool AddTime(double seconds) => Execute(() =>
  96. (State == GameFlowState.Running || State == GameFlowState.Paused) && Runtime.AddTime(seconds));
  97. internal ItemUseResult ExecuteItem(Func<GameSessionRuntime, ItemUseResult> operation)
  98. {
  99. var result = new ItemUseResult(ItemUseStatus.GameNotRunning);
  100. Execute(() => {
  101. if (State != GameFlowState.Running) return false;
  102. Runtime.Update(); // An elapsed deadline wins before an item can revive the run.
  103. if (State != GameFlowState.Running || Runtime.IsFinished) return false;
  104. result = Runtime.Interaction.IsLocked ? new ItemUseResult(ItemUseStatus.InteractionLocked) : operation(Runtime);
  105. return true;
  106. });
  107. return result;
  108. }
  109. public bool RestartCurrentLevel() => Execute(() =>
  110. {
  111. if (State != GameFlowState.Paused && State != GameFlowState.Victory && State != GameFlowState.Defeat) return false;
  112. return ReplaceRun(Runtime.Session.Definition);
  113. });
  114. public bool Retry()
  115. {
  116. if (State != GameFlowState.Victory && State != GameFlowState.Defeat) return false;
  117. return RestartCurrentLevel();
  118. }
  119. public bool NextLevel() => Execute(() =>
  120. {
  121. if (State != GameFlowState.Victory) return false;
  122. var current = Runtime.Session.Definition;
  123. return ReplaceRun(LevelCatalog.Get(current.Mode, Math.Min(current.Level + 1, LevelCatalog.LevelsPerMode)));
  124. });
  125. private bool ReplaceRun(LevelDefinition level)
  126. {
  127. // Construct successfully before retiring the old run.
  128. var replacement = Prepare(factory.CreateForLevel(level, nextSeed));
  129. nextSeed = unchecked(nextSeed + 1);
  130. DetachRuntime(); Runtime.Dispose();
  131. Runtime = replacement; Result = null; HasAdRevived = false; AttachRuntime();
  132. Transition(GameFlowState.Ready);
  133. SessionChanged?.Invoke(Runtime);
  134. return StartCore();
  135. }
  136. public bool ReturnToLobby() => Execute(() =>
  137. {
  138. if (State == GameFlowState.Abandoned) return false;
  139. // Do not advance the clock here: abandonment is not a loss or a victory.
  140. DetachRuntime(); Runtime.Dispose(); Transition(GameFlowState.Abandoned);
  141. LobbyRequested?.Invoke(); return true;
  142. });
  143. private void AttachRuntime()
  144. {
  145. var source = Runtime;
  146. clearHandler = _ => Complete(source, GameOutcome.Victory);
  147. timeoutHandler = () => Complete(source, GameOutcome.Defeat);
  148. source.ClearBonusAwarded += clearHandler; source.TimedOut += timeoutHandler;
  149. }
  150. private void DetachRuntime()
  151. { Runtime.ClearBonusAwarded -= clearHandler; Runtime.TimedOut -= timeoutHandler; }
  152. private void Complete(GameSessionRuntime source, GameOutcome outcome)
  153. {
  154. if (disposed || !ReferenceEquals(source, Runtime) || State != GameFlowState.Running || Result != null) return;
  155. if (outcome == GameOutcome.Victory ? !source.IsCleared || source.IsTimedOut : !source.IsTimedOut || source.IsCleared) return;
  156. bool wasBusy = busy; busy = true;
  157. try
  158. {
  159. source.Timer.Stop();
  160. var rewardStatus = VictoryRewardStatus.Granted;
  161. if (outcome == GameOutcome.Victory)
  162. {
  163. // A concurrent reward snapshot must not see coins credited before progress.
  164. lock (Economy.SyncRoot)
  165. { rewardStatus = Economy.GrantVictory(source.Session); Progress.RecordClear(source.Session.Mode, source.Session.Definition.Level); }
  166. }
  167. // Score (including the 05B clear bonus) is snapshotted, never recalculated.
  168. Result = new GameResult(source, outcome, rewardStatus);
  169. Transition(outcome == GameOutcome.Victory ? GameFlowState.Victory : GameFlowState.Defeat);
  170. Settled?.Invoke(Result);
  171. }
  172. finally { busy = wasBusy; if (!busy && disposeRequested) Dispose(); }
  173. }
  174. public void Dispose()
  175. {
  176. if (disposed) return;
  177. if (busy) { disposeRequested = true; return; }
  178. disposeRequested = false;
  179. ReturnToLobby(); disposed = true;
  180. }
  181. }
  182. }