using System; using System.Collections.Generic; using DevilLink2.Core; namespace DevilLink2.Interaction { public enum TileClickResult { Ignored, Selected, Deselected, Switched, InvalidLink, Matched } public sealed class PairMatch { public Tile First { get; } public Tile Second { get; } public IReadOnlyList Path { get; } internal PairMatch(Tile first, Tile second, IReadOnlyList path) { First = first; Second = second; Path = path; } } /// Single-threaded interaction state. Owns no duplicate board and no animation callbacks. /// Advance receives unscaled elapsed seconds. Only this state should remove tiles during a match. public sealed class BoardInteractionState { public const double MatchLockSeconds = .240; private readonly LinkPathFinder paths = new LinkPathFinder(); private readonly BoardMoveFinder moves = new BoardMoveFinder(); private readonly BoardShuffleService shuffles = new BoardShuffleService(); private readonly Random random; private double lockRemaining; private bool pendingCompletion, initialized; public Board Board { get; } public Tile Selected { get; private set; } public bool IsLocked => pendingCompletion; public bool IsCleared { get; private set; } public string Error { get; private set; } public event Action SelectionChanged; public event Action InvalidMatch; // Future GameSession may apply -3 seconds. public event Action Matched; public event Action Reshuffled; public event Action BoardCleared; public event Action Failed; public BoardInteractionState(Board board, int seed) : this(board, new Random(seed)) { } public BoardInteractionState(Board board, Random random) { Board = board ?? throw new ArgumentNullException(nameof(board)); this.random = random ?? throw new ArgumentNullException(nameof(random)); } public void Initialize() { if (initialized) return; initialized = true; CheckMoves(); } public TileClickResult Click(int row, int column) { if (!initialized || IsLocked || IsCleared || Error != null || !Board.Contains(row, column)) return TileClickResult.Ignored; var tile = Board.GetTile(row, column); if (tile == null) return TileClickResult.Ignored; if (Selected != null && !ReferenceEquals(Board.GetTile(Selected.Row, Selected.Column), Selected)) SetSelection(null); if (ReferenceEquals(Selected, tile)) { SetSelection(null); return TileClickResult.Deselected; } if (Selected == null) { SetSelection(tile); return TileClickResult.Selected; } var first = Selected; if (first.Symbol != tile.Symbol) { SetSelection(tile); return TileClickResult.Switched; } if (!paths.TryFindPath(Board, first.Position, tile.Position, out var path)) { SetSelection(tile); // Original HTML retains the second tile as the selection. InvalidMatch?.Invoke(first, tile); return TileClickResult.InvalidLink; } pendingCompletion = true; lockRemaining = MatchLockSeconds; Board.RemoveTile(first); Board.RemoveTile(tile); SetSelection(null); Matched?.Invoke(new PairMatch(first, tile, path)); return TileClickResult.Matched; } public void Advance(double seconds) { if (seconds < 0 || double.IsNaN(seconds) || double.IsInfinity(seconds)) throw new ArgumentOutOfRangeException(nameof(seconds)); if (!pendingCompletion) return; lockRemaining -= seconds; if (lockRemaining > 0.000000001) return; pendingCompletion = false; CheckMoves(); } /// Manual entry to the same shuffle service. The caller commits its reserved /// inventory only after algorithm success, before publishing visual notifications. public bool TryManualShuffle(Random source, Action commit, out BoardShuffleResult result, out string error) { result = null; error = null; if (!initialized || IsLocked || IsCleared || Error != null) { error = "Interaction is unavailable."; return false; } try { result = shuffles.Shuffle(Board, source); } catch (Exception exception) { error = exception.Message; return false; } if (!result.Succeeded) { error = result.Error ?? result.Status.ToString(); return false; } commit?.Invoke(); SetSelection(null); lockRemaining = 0; pendingCompletion = false; Reshuffled?.Invoke(result); return true; } private void SetSelection(Tile tile) { Selected = tile; SelectionChanged?.Invoke(tile); } private void CheckMoves() { if (IsCleared || Error != null) return; if (Board.RemainingTileCount == 0) { IsCleared = true; BoardCleared?.Invoke(); return; } if (moves.TryFindMove(Board, out _)) return; SetSelection(null); try { var result = shuffles.Shuffle(Board, random); if (!result.Succeeded) { Fail("Automatic shuffle failed: " + result.Status + ". " + result.Error); return; } Reshuffled?.Invoke(result); } catch (Exception e) { Fail("Automatic shuffle failed: " + e.Message); } } private void Fail(string error) { Error = error; Failed?.Invoke(error); } } }