BoardGenerator.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System;
  2. using System.Collections.Generic;
  3. namespace DevilLink2.Core
  4. {
  5. public static class BoardGenerator
  6. {
  7. public static Board Generate(int columns, int rows, int seed)
  8. {
  9. if (columns <= 0) throw new ArgumentOutOfRangeException(nameof(columns));
  10. if (rows <= 0) throw new ArgumentOutOfRangeException(nameof(rows));
  11. long count = (long)columns * rows;
  12. if (count > int.MaxValue || count % 2 != 0)
  13. throw new ArgumentException("A full board requires an even, representable cell count.");
  14. var symbols = new List<TileSymbol>((int)count);
  15. for (int pair = 0; pair < count / 2; pair++)
  16. {
  17. var symbol = (TileSymbol)(pair % 12);
  18. symbols.Add(symbol); symbols.Add(symbol);
  19. }
  20. Shuffle(symbols, new Random(seed));
  21. var tiles = new List<Tile>((int)count);
  22. for (int i = 0; i < count; i++)
  23. tiles.Add(new Tile(i + 1, symbols[i], i / columns, i % columns));
  24. return new Board(columns, rows, tiles);
  25. }
  26. /// <summary>In-place Fisher-Yates; one unbiased bounded draw per swap.</summary>
  27. public static void Shuffle<T>(IList<T> values, Random random)
  28. {
  29. if (values == null) throw new ArgumentNullException(nameof(values));
  30. if (random == null) throw new ArgumentNullException(nameof(random));
  31. for (int i = values.Count - 1; i > 0; i--)
  32. {
  33. int j = random.Next(i + 1);
  34. T value = values[i]; values[i] = values[j]; values[j] = value;
  35. }
  36. }
  37. }
  38. }