using System; using DevilLink2.Interaction; namespace DevilLink2.Gameplay { /// Single lifecycle/settlement authority. Commands invoked inside its notifications /// are rejected; consumers can invoke the next command after the current update/click returns. /// A restart replaces the session, so terminal results never change into another outcome. public sealed class GameFlowController : IDisposable { private readonly GameSessionFactory factory = new GameSessionFactory(); private readonly IMonotonicClock clock; private int nextSeed; private bool busy, disposed, disposeRequested; private Action clearHandler; private Action timeoutHandler; public GameFlowState State { get; private set; } = GameFlowState.Ready; public GameSessionRuntime Runtime { get; private set; } public ModeProgress Progress { get; } public PlayerEconomy Economy { get; } public ItemUseService Items { get; } public GameResult Result { get; private set; } public event Action StateChanged; public event Action SessionChanged; public event Action Settled; public event Action LobbyRequested; public GameFlowController(GameMode mode, ModeProgress progress, PlayerEconomy economy, IMonotonicClock clock, int randomSeed = 2026) { Progress = progress ?? throw new ArgumentNullException(nameof(progress)); Economy = economy ?? throw new ArgumentNullException(nameof(economy)); this.clock = clock ?? throw new ArgumentNullException(nameof(clock)); nextSeed = unchecked(randomSeed + 1); Runtime = Prepare(factory.Create(mode, progress, randomSeed)); AttachRuntime(); Items = new ItemUseService(this, new Random(unchecked(randomSeed ^ 0x7a13))); } private GameSessionRuntime Prepare(GameSession session) { var runtime = new GameSessionRuntime(session, clock); runtime.Timer.Pause(); // Ready must not consume time before Start. return runtime; } private bool Execute(Func command) { if (disposed || busy) return false; busy = true; try { return command(); } finally { busy = false; if (disposeRequested) Dispose(); } } // All state assignments and notifications pass through this single transition gate. private void Transition(GameFlowState next) { var previous = State; bool allowed = next == GameFlowState.Abandoned && previous != GameFlowState.Abandoned || previous == GameFlowState.Ready && next == GameFlowState.Running || previous == GameFlowState.Running && (next == GameFlowState.Paused || next == GameFlowState.Victory || next == GameFlowState.Defeat) || previous == GameFlowState.Paused && next == GameFlowState.Running || (previous == GameFlowState.Paused || previous == GameFlowState.Victory || previous == GameFlowState.Defeat) && next == GameFlowState.Ready; if (!allowed) throw new InvalidOperationException("Illegal flow transition: " + previous + " -> " + next); State = next; StateChanged?.Invoke(previous, next); } public bool Start() => Execute(StartCore); private bool StartCore() { if (State != GameFlowState.Ready) return false; Runtime.Resume(); Transition(GameFlowState.Running); return true; } public bool Pause() => Execute(() => { if (State != GameFlowState.Running) return false; Runtime.Pause(); if (State != GameFlowState.Running) return false; // Update-before-pause may have expired. Transition(GameFlowState.Paused); return true; }); public bool Resume() => Execute(() => { if (State != GameFlowState.Paused) return false; Runtime.Resume(); Transition(GameFlowState.Running); return true; }); public void Update() { Execute(() => { if (State != GameFlowState.Abandoned) Runtime.Update(); return true; }); } public TileClickResult Click(int row, int column) { var result = TileClickResult.Ignored; Execute(() => { if (State == GameFlowState.Running) result = Runtime.Click(row, column); return true; }); return result; } public bool AddTime(double seconds) => Execute(() => (State == GameFlowState.Running || State == GameFlowState.Paused) && Runtime.AddTime(seconds)); internal ItemUseResult ExecuteItem(Func operation) { var result = new ItemUseResult(ItemUseStatus.GameNotRunning); Execute(() => { if (State != GameFlowState.Running) return false; Runtime.Update(); // An elapsed deadline wins before an item can revive the run. if (State != GameFlowState.Running || Runtime.IsFinished) return false; result = Runtime.Interaction.IsLocked ? new ItemUseResult(ItemUseStatus.InteractionLocked) : operation(Runtime); return true; }); return result; } public bool RestartCurrentLevel() => Execute(() => { if (State != GameFlowState.Paused && State != GameFlowState.Victory && State != GameFlowState.Defeat) return false; return ReplaceRun(Runtime.Session.Definition); }); public bool Retry() { if (State != GameFlowState.Victory && State != GameFlowState.Defeat) return false; return RestartCurrentLevel(); } public bool NextLevel() => Execute(() => { if (State != GameFlowState.Victory) return false; var current = Runtime.Session.Definition; return ReplaceRun(LevelCatalog.Get(current.Mode, Math.Min(current.Level + 1, LevelCatalog.LevelsPerMode))); }); private bool ReplaceRun(LevelDefinition level) { // Construct successfully before retiring the old run. var replacement = Prepare(factory.CreateForLevel(level, nextSeed)); nextSeed = unchecked(nextSeed + 1); DetachRuntime(); Runtime.Dispose(); Runtime = replacement; Result = null; AttachRuntime(); Transition(GameFlowState.Ready); SessionChanged?.Invoke(Runtime); return StartCore(); } public bool ReturnToLobby() => Execute(() => { if (State == GameFlowState.Abandoned) return false; // Do not advance the clock here: abandonment is not a loss or a victory. DetachRuntime(); Runtime.Dispose(); Transition(GameFlowState.Abandoned); LobbyRequested?.Invoke(); return true; }); private void AttachRuntime() { var source = Runtime; clearHandler = _ => Complete(source, GameOutcome.Victory); timeoutHandler = () => Complete(source, GameOutcome.Defeat); source.ClearBonusAwarded += clearHandler; source.TimedOut += timeoutHandler; } private void DetachRuntime() { Runtime.ClearBonusAwarded -= clearHandler; Runtime.TimedOut -= timeoutHandler; } private void Complete(GameSessionRuntime source, GameOutcome outcome) { if (disposed || !ReferenceEquals(source, Runtime) || State != GameFlowState.Running || Result != null) return; if (outcome == GameOutcome.Victory ? !source.IsCleared || source.IsTimedOut : !source.IsTimedOut || source.IsCleared) return; bool wasBusy = busy; busy = true; try { source.Timer.Stop(); var rewardStatus = VictoryRewardStatus.Granted; if (outcome == GameOutcome.Victory) { // A concurrent reward snapshot must not see coins credited before progress. lock (Economy.SyncRoot) { rewardStatus = Economy.GrantVictory(source.Session); Progress.RecordClear(source.Session.Mode, source.Session.Definition.Level); } } // Score (including the 05B clear bonus) is snapshotted, never recalculated. Result = new GameResult(source, outcome, rewardStatus); Transition(outcome == GameOutcome.Victory ? GameFlowState.Victory : GameFlowState.Defeat); Settled?.Invoke(Result); } finally { busy = wasBusy; if (!busy && disposeRequested) Dispose(); } } public void Dispose() { if (disposed) return; if (busy) { disposeRequested = true; return; } disposeRequested = false; ReturnToLobby(); disposed = true; } } }