using System; using System.Collections.Generic; using DevilLink2.Core; using DevilLink2.Interaction; namespace DevilLink2.Gameplay { /// Owns exactly one interaction subscription set and no duplicate board. /// Update-before-click makes timeout win at the deadline. A last-pair Matched freezes time /// immediately, before the existing 240ms delayed BoardCleared notification. public sealed class GameSessionRuntime : IDisposable { private readonly IMonotonicClock clock; private readonly HashSet scoredTileIds = new HashSet(); private double lastRead; private bool disposed; public GameSession Session { get; } public SessionTimer Timer { get; } public SessionScore Score { get; } public BoardInteractionState Interaction { get; } public bool IsCleared { get; private set; } public bool IsTimedOut { get; private set; } public bool IsPaused => Timer.IsPaused; public bool IsFinished => IsCleared || IsTimedOut || Error != null; public string Error { get; private set; } public event Action TimedOut; public event Action ClearBonusAwarded; public GameSessionRuntime(GameSession session, IMonotonicClock clock) { Session = session ?? throw new ArgumentNullException(nameof(session)); if (!session.IsInitialized) throw new ArgumentException("Initialize the session first.", nameof(session)); this.clock = clock ?? throw new ArgumentNullException(nameof(clock)); GameplayTime.Read(clock, ref lastRead); Timer = new SessionTimer(session.Definition); Score = new SessionScore(clock); Interaction = new BoardInteractionState(session.Board, session.RandomSeed); Timer.Expired += OnExpired; Interaction.Matched += OnMatched; Interaction.InvalidMatch += OnInvalid; Interaction.BoardCleared += OnCleared; Interaction.Failed += OnFailed; Interaction.Initialize(); } public void Update() { if (disposed) return; double before = lastRead; double now = GameplayTime.Read(clock, ref lastRead); Score.Update(); Timer.Advance(now - before); if (!IsPaused && !IsTimedOut && Error == null) Interaction.Advance(now - before); } public TileClickResult Click(int row, int column) { Update(); if (disposed || IsFinished || Timer.IsExpired || IsPaused) return TileClickResult.Ignored; return Interaction.Click(row, column); } public void Pause() { Update(); if (!disposed && !IsFinished) Timer.Pause(); } public void Resume() { Update(); if (!disposed && !IsFinished) Timer.Resume(); } public bool AddTime(double seconds) { Update(); return !disposed && !IsFinished && Timer.AddTime(seconds); } private void OnInvalid(Tile first, Tile second) { if (!disposed && !IsFinished && !IsPaused) Timer.ApplyInvalidMatchPenalty(); } private void OnMatched(PairMatch match) { if (disposed || IsFinished || Timer.IsExpired || IsPaused || scoredTileIds.Contains(match.First.Id) || scoredTileIds.Contains(match.Second.Id)) return; scoredTileIds.Add(match.First.Id); scoredTileIds.Add(match.Second.Id); // Mark last-pair completion before score callbacks can re-enter Update/Click. bool lastPair = Session.Board.RemainingTileCount == 0; if (lastPair) { IsCleared = true; Timer.Stop(); } Score.RegisterMatch(); if (lastPair) AwardClear(); } private void OnCleared() { if (disposed || IsFinished || Timer.IsExpired) return; IsCleared = true; Timer.Stop(); AwardClear(); } private void AwardClear() { int bonus = Score.CompleteClear(Timer.HasTimer, Timer.RemainingTime); if (bonus > 0) ClearBonusAwarded?.Invoke(bonus); } private void OnExpired() { if (disposed || IsFinished) return; IsTimedOut = true; Score.EndWithoutBonus(); TimedOut?.Invoke(); } private void OnFailed(string error) { if (!IsFinished) { Error = error; Timer.Stop(); Score.EndWithoutBonus(); } } public void Dispose() { if (disposed) return; disposed = true; Timer.Stop(); Score.EndWithoutBonus(); Timer.Expired -= OnExpired; Interaction.Matched -= OnMatched; Interaction.InvalidMatch -= OnInvalid; Interaction.BoardCleared -= OnCleared; Interaction.Failed -= OnFailed; // Reuse the existing same-tile deselection, without attempting a new match. var selected = Interaction.Selected; if (selected != null) Interaction.Click(selected.Row, selected.Column); } } }