using System; using System.Collections.Generic; namespace DevilLink2.Core { public enum BoardShuffleStatus { Success, EmptyBoard, NoMatchingSymbols, VerificationFailed } public sealed class BoardShuffleResult { public BoardShuffleStatus Status { get; } public bool Succeeded => Status == BoardShuffleStatus.Success; public int RandomAttempts { get; } public bool UsedFallback { get; } public BoardMove Move { get; } public string Error { get; } internal BoardShuffleResult(BoardShuffleStatus status, int attempts, bool fallback, BoardMove move, string error = null) { Status = status; RandomAttempts = attempts; UsedFallback = fallback; Move = move; Error = error; } } /// Shared algorithm for automatic/manual shuffles. Never charges inventory. /// Mutates the supplied board in place, retaining tile instances, IDs and empty cells. public sealed class BoardShuffleService { public const int MaxRandomAttempts = 40; private readonly BoardMoveFinder moves = new BoardMoveFinder(); private readonly LinkPathFinder paths = new LinkPathFinder(); public BoardShuffleResult Shuffle(Board board, int seed) => Shuffle(board, new Random(seed)); // Random injection permits repeatable tests, including forty failed permutations. public BoardShuffleResult Shuffle(Board board, Random random) { if (board == null) throw new ArgumentNullException(nameof(board)); if (random == null) throw new ArgumentNullException(nameof(random)); var original = new List(); var positions = new List(); for (int r = 0; r < board.Rows; r++) for (int c = 0; c < board.Columns; c++) if (!board.IsEmpty(r, c)) { original.Add(board.GetTile(r, c)); positions.Add(new GridPosition(r, c)); } if (original.Count == 0) return new BoardShuffleResult(BoardShuffleStatus.EmptyBoard, 0, false, null); int pairA = -1, pairB = -1; for (int i = 0; i < original.Count && pairA < 0; i++) for (int j = i + 1; j < original.Count; j++) if (original[i].Symbol == original[j].Symbol) { pairA = i; pairB = j; break; } if (pairA < 0) return new BoardShuffleResult(BoardShuffleStatus.NoMatchingSymbols, 0, false, null, "No two remaining tiles share a symbol."); // Roll back the permutation if a random source or the final verification fails. try { var permutation = new List(original); for (int attempt = 1; attempt <= MaxRandomAttempts; attempt++) { BoardGenerator.Shuffle(permutation, random); board.Rearrange(permutation); if (moves.TryFindMove(board, out var move)) return new BoardShuffleResult(BoardShuffleStatus.Success, attempt, false, move); } int first = 0, second = 1; long bestDistance = long.MaxValue; // Strict improvement retains row-major pair order when distances tie. for (int i = 0; i < positions.Count; i++) for (int j = i + 1; j < positions.Count; j++) { long distance = Math.Abs((long)positions[i].Row - positions[j].Row) + Math.Abs((long)positions[i].Column - positions[j].Column); if (distance < bestDistance) { bestDistance = distance; first = i; second = j; } } var arranged = new Tile[original.Count]; arranged[first] = original[pairA]; arranged[second] = original[pairB]; int next = 0; for (int i = 0; i < original.Count; i++) { if (i == pairA || i == pairB) continue; while (arranged[next] != null) next++; arranged[next] = original[i]; } board.Rearrange(arranged); // A third occupied cell on a shortest L path would be closer to an endpoint, // contradicting global minimum distance. Thus this chosen pair needs <=1 turn. if (paths.TryFindPath(board, positions[first], positions[second], out var path)) return new BoardShuffleResult(BoardShuffleStatus.Success, MaxRandomAttempts, true, new BoardMove(arranged[first], arranged[second], path)); board.Rearrange(original); return new BoardShuffleResult(BoardShuffleStatus.VerificationFailed, MaxRandomAttempts, true, null, "Deterministic fallback did not produce a legal link; original board restored."); } catch { board.Rearrange(original); throw; } } } }