GameFlowController.cs 8.9 KB

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