BoardInteractionState.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. using System.Collections.Generic;
  3. using DevilLink2.Core;
  4. namespace DevilLink2.Interaction
  5. {
  6. public enum TileClickResult { Ignored, Selected, Deselected, Switched, InvalidLink, Matched }
  7. public sealed class PairMatch
  8. {
  9. public Tile First { get; }
  10. public Tile Second { get; }
  11. public IReadOnlyList<GridPosition> Path { get; }
  12. internal PairMatch(Tile first, Tile second, IReadOnlyList<GridPosition> path)
  13. { First = first; Second = second; Path = path; }
  14. }
  15. /// <summary>Single-threaded interaction state. Owns no duplicate board and no animation callbacks.
  16. /// Advance receives unscaled elapsed seconds. Only this state should remove tiles during a match.</summary>
  17. public sealed class BoardInteractionState
  18. {
  19. public const double MatchLockSeconds = .240;
  20. private readonly LinkPathFinder paths = new LinkPathFinder();
  21. private readonly BoardMoveFinder moves = new BoardMoveFinder();
  22. private readonly BoardShuffleService shuffles = new BoardShuffleService();
  23. private readonly Random random;
  24. private double lockRemaining;
  25. private bool pendingCompletion, initialized;
  26. public Board Board { get; }
  27. public Tile Selected { get; private set; }
  28. public bool IsLocked => pendingCompletion;
  29. public bool IsCleared { get; private set; }
  30. public string Error { get; private set; }
  31. public event Action<Tile> SelectionChanged;
  32. public event Action<Tile, Tile> InvalidMatch; // Future GameSession may apply -3 seconds.
  33. public event Action<PairMatch> Matched;
  34. public event Action<BoardShuffleResult> Reshuffled;
  35. public event Action BoardCleared;
  36. public event Action<string> Failed;
  37. public BoardInteractionState(Board board, int seed) : this(board, new Random(seed)) { }
  38. public BoardInteractionState(Board board, Random random)
  39. { Board = board ?? throw new ArgumentNullException(nameof(board)); this.random = random ?? throw new ArgumentNullException(nameof(random)); }
  40. public void Initialize()
  41. {
  42. if (initialized) return;
  43. initialized = true;
  44. CheckMoves();
  45. }
  46. public TileClickResult Click(int row, int column)
  47. {
  48. if (!initialized || IsLocked || IsCleared || Error != null || !Board.Contains(row, column)) return TileClickResult.Ignored;
  49. var tile = Board.GetTile(row, column);
  50. if (tile == null) return TileClickResult.Ignored;
  51. if (Selected != null && !ReferenceEquals(Board.GetTile(Selected.Row, Selected.Column), Selected)) SetSelection(null);
  52. if (ReferenceEquals(Selected, tile)) { SetSelection(null); return TileClickResult.Deselected; }
  53. if (Selected == null) { SetSelection(tile); return TileClickResult.Selected; }
  54. var first = Selected;
  55. if (first.Symbol != tile.Symbol) { SetSelection(tile); return TileClickResult.Switched; }
  56. if (!paths.TryFindPath(Board, first.Position, tile.Position, out var path))
  57. {
  58. SetSelection(tile); // Original HTML retains the second tile as the selection.
  59. InvalidMatch?.Invoke(first, tile);
  60. return TileClickResult.InvalidLink;
  61. }
  62. pendingCompletion = true; lockRemaining = MatchLockSeconds;
  63. Board.RemoveTile(first); Board.RemoveTile(tile);
  64. SetSelection(null);
  65. Matched?.Invoke(new PairMatch(first, tile, path));
  66. return TileClickResult.Matched;
  67. }
  68. public void Advance(double seconds)
  69. {
  70. if (seconds < 0 || double.IsNaN(seconds) || double.IsInfinity(seconds)) throw new ArgumentOutOfRangeException(nameof(seconds));
  71. if (!pendingCompletion) return;
  72. lockRemaining -= seconds;
  73. if (lockRemaining > 0.000000001) return;
  74. pendingCompletion = false;
  75. CheckMoves();
  76. }
  77. /// <summary>Manual entry to the same shuffle service. The caller commits its reserved
  78. /// inventory only after algorithm success, before publishing visual notifications.</summary>
  79. public bool TryManualShuffle(Random source, Action commit, out BoardShuffleResult result, out string error)
  80. {
  81. result = null; error = null;
  82. if (!initialized || IsLocked || IsCleared || Error != null) { error = "Interaction is unavailable."; return false; }
  83. try { result = shuffles.Shuffle(Board, source); }
  84. catch (Exception exception) { error = exception.Message; return false; }
  85. if (!result.Succeeded) { error = result.Error ?? result.Status.ToString(); return false; }
  86. commit?.Invoke();
  87. SetSelection(null); lockRemaining = 0; pendingCompletion = false;
  88. Reshuffled?.Invoke(result);
  89. return true;
  90. }
  91. private void SetSelection(Tile tile) { Selected = tile; SelectionChanged?.Invoke(tile); }
  92. private void CheckMoves()
  93. {
  94. if (IsCleared || Error != null) return;
  95. if (Board.RemainingTileCount == 0) { IsCleared = true; BoardCleared?.Invoke(); return; }
  96. if (moves.TryFindMove(Board, out _)) return;
  97. SetSelection(null);
  98. try
  99. {
  100. var result = shuffles.Shuffle(Board, random);
  101. if (!result.Succeeded) { Fail("Automatic shuffle failed: " + result.Status + ". " + result.Error); return; }
  102. Reshuffled?.Invoke(result);
  103. }
  104. catch (Exception e) { Fail("Automatic shuffle failed: " + e.Message); }
  105. }
  106. private void Fail(string error) { Error = error; Failed?.Invoke(error); }
  107. }
  108. }