BoardShuffleService.cs 4.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. namespace DevilLink2.Core
  4. {
  5. public enum BoardShuffleStatus { Success, EmptyBoard, NoMatchingSymbols, VerificationFailed }
  6. public sealed class BoardShuffleResult
  7. {
  8. public BoardShuffleStatus Status { get; }
  9. public bool Succeeded => Status == BoardShuffleStatus.Success;
  10. public int RandomAttempts { get; }
  11. public bool UsedFallback { get; }
  12. public BoardMove Move { get; }
  13. public string Error { get; }
  14. internal BoardShuffleResult(BoardShuffleStatus status, int attempts, bool fallback, BoardMove move, string error = null)
  15. { Status = status; RandomAttempts = attempts; UsedFallback = fallback; Move = move; Error = error; }
  16. }
  17. /// <summary>Shared algorithm for automatic/manual shuffles. Never charges inventory.
  18. /// Mutates the supplied board in place, retaining tile instances, IDs and empty cells.</summary>
  19. public sealed class BoardShuffleService
  20. {
  21. public const int MaxRandomAttempts = 40;
  22. private readonly BoardMoveFinder moves = new BoardMoveFinder();
  23. private readonly LinkPathFinder paths = new LinkPathFinder();
  24. public BoardShuffleResult Shuffle(Board board, int seed) => Shuffle(board, new Random(seed));
  25. // Random injection permits repeatable tests, including forty failed permutations.
  26. public BoardShuffleResult Shuffle(Board board, Random random)
  27. {
  28. if (board == null) throw new ArgumentNullException(nameof(board));
  29. if (random == null) throw new ArgumentNullException(nameof(random));
  30. var original = new List<Tile>();
  31. var positions = new List<GridPosition>();
  32. for (int r = 0; r < board.Rows; r++) for (int c = 0; c < board.Columns; c++)
  33. if (!board.IsEmpty(r, c)) { original.Add(board.GetTile(r, c)); positions.Add(new GridPosition(r, c)); }
  34. if (original.Count == 0) return new BoardShuffleResult(BoardShuffleStatus.EmptyBoard, 0, false, null);
  35. int pairA = -1, pairB = -1;
  36. for (int i = 0; i < original.Count && pairA < 0; i++) for (int j = i + 1; j < original.Count; j++)
  37. if (original[i].Symbol == original[j].Symbol) { pairA = i; pairB = j; break; }
  38. if (pairA < 0)
  39. return new BoardShuffleResult(BoardShuffleStatus.NoMatchingSymbols, 0, false, null, "No two remaining tiles share a symbol.");
  40. // Roll back the permutation if a random source or the final verification fails.
  41. try
  42. {
  43. var permutation = new List<Tile>(original);
  44. for (int attempt = 1; attempt <= MaxRandomAttempts; attempt++)
  45. {
  46. BoardGenerator.Shuffle(permutation, random);
  47. board.Rearrange(permutation);
  48. if (moves.TryFindMove(board, out var move))
  49. return new BoardShuffleResult(BoardShuffleStatus.Success, attempt, false, move);
  50. }
  51. int first = 0, second = 1; long bestDistance = long.MaxValue;
  52. // Strict improvement retains row-major pair order when distances tie.
  53. for (int i = 0; i < positions.Count; i++) for (int j = i + 1; j < positions.Count; j++)
  54. {
  55. long distance = Math.Abs((long)positions[i].Row - positions[j].Row) +
  56. Math.Abs((long)positions[i].Column - positions[j].Column);
  57. if (distance < bestDistance) { bestDistance = distance; first = i; second = j; }
  58. }
  59. var arranged = new Tile[original.Count];
  60. arranged[first] = original[pairA]; arranged[second] = original[pairB];
  61. int next = 0;
  62. for (int i = 0; i < original.Count; i++)
  63. {
  64. if (i == pairA || i == pairB) continue;
  65. while (arranged[next] != null) next++;
  66. arranged[next] = original[i];
  67. }
  68. board.Rearrange(arranged);
  69. // A third occupied cell on a shortest L path would be closer to an endpoint,
  70. // contradicting global minimum distance. Thus this chosen pair needs <=1 turn.
  71. if (paths.TryFindPath(board, positions[first], positions[second], out var path))
  72. return new BoardShuffleResult(BoardShuffleStatus.Success, MaxRandomAttempts, true,
  73. new BoardMove(arranged[first], arranged[second], path));
  74. board.Rearrange(original);
  75. return new BoardShuffleResult(BoardShuffleStatus.VerificationFailed, MaxRandomAttempts, true, null,
  76. "Deterministic fallback did not produce a legal link; original board restored.");
  77. }
  78. catch
  79. {
  80. board.Rearrange(original);
  81. throw;
  82. }
  83. }
  84. }
  85. }