BoardMoveFinder.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  1. using System;
  2. using System.Collections.Generic;
  3. namespace DevilLink2.Core
  4. {
  5. /// <summary>A snapshot of a legal move. Query again after changing the board.</summary>
  6. public sealed class BoardMove
  7. {
  8. public Tile First { get; }
  9. public Tile Second { get; }
  10. public IReadOnlyList<GridPosition> Path { get; }
  11. internal BoardMove(Tile first, Tile second, IReadOnlyList<GridPosition> path)
  12. { First = first; Second = second; Path = path; }
  13. }
  14. public sealed class BoardMoveFinder
  15. {
  16. private readonly LinkPathFinder paths = new LinkPathFinder();
  17. /// <summary>Scans in stable row/column order without mutating the board.</summary>
  18. public bool TryFindMove(Board board, out BoardMove move)
  19. {
  20. if (board == null) throw new ArgumentNullException(nameof(board));
  21. move = null;
  22. var tiles = new List<Tile>();
  23. for (int r = 0; r < board.Rows; r++) for (int c = 0; c < board.Columns; c++)
  24. if (!board.IsEmpty(r, c)) tiles.Add(board.GetTile(r, c));
  25. for (int i = 0; i < tiles.Count; i++) for (int j = i + 1; j < tiles.Count; j++)
  26. if (tiles[i].Symbol == tiles[j].Symbol &&
  27. paths.TryFindPath(board, tiles[i].Position, tiles[j].Position, out var path))
  28. { move = new BoardMove(tiles[i], tiles[j], path); return true; }
  29. return false;
  30. }
  31. }
  32. }