HexRules.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace HexaCrazy
  5. {
  6. [Serializable] public class LevelSpec
  7. {
  8. public int mode, level, cells, target, colors, locks, debris, shape, seconds;
  9. public int Reward => mode == 1 ? 160 + 35 * level : mode == 2 ? 150 + 32 * level : 130 + 30 * level;
  10. }
  11. [Serializable] public class HexCell
  12. {
  13. public int q, r, need;
  14. public List<int> tiles = new List<int>();
  15. public int Top => tiles.Count == 0 ? -1 : tiles[tiles.Count - 1];
  16. public int TopCount { get { int n = 0; for (int i = tiles.Count - 1; i >= 0 && tiles[i] == Top; i--) n++; return n; } }
  17. }
  18. [Serializable] public class HandGroup { public int color, count; public HandGroup(int c, int n) { color = c; count = n; } }
  19. public enum StepKind { Place, Merge, Clear, Neighbor }
  20. public class RuleStep
  21. {
  22. public StepKind kind; public int from = -1, to, color, count, chain, gain, baseCount, startIndex;
  23. }
  24. public sealed class HexRules
  25. {
  26. public const int ClearCount = 8;
  27. public static readonly int[,] Directions = { {1,0},{1,-1},{0,-1},{-1,0},{-1,1},{0,1} };
  28. public readonly List<HexCell> Cells;
  29. public HandGroup[] Hand = new HandGroup[3];
  30. public readonly LevelSpec Spec;
  31. public int Score, Clears;
  32. public float Time;
  33. public bool Over;
  34. public bool ReviveUsed { get; private set; }
  35. public bool TryRevive()
  36. {
  37. if (!Over || ReviveUsed || Score >= Spec.target) return false;
  38. Over = false;
  39. if (!HasSpace)
  40. {
  41. var smallest = Cells.Where(c => c.need <= Score && c.tiles.Count > 0)
  42. .OrderBy(c => c.tiles.Count).Take(3).ToArray();
  43. foreach (var cell in smallest) cell.tiles.Clear();
  44. }
  45. if (Spec.mode == 1 && Time <= 0) Time = 30;
  46. ReviveUsed = true;
  47. return true;
  48. }
  49. readonly Random random;
  50. public HexRules(LevelSpec spec, int seed, bool tutorial = false)
  51. {
  52. Spec = spec; random = new Random(seed); Time = spec.seconds;
  53. Cells = Generate(spec.cells, spec.shape, random);
  54. var order = Enumerable.Range(0, Cells.Count).OrderBy(_ => random.Next()).ToList();
  55. int p = 0;
  56. for (int i = 0; i < spec.locks; i++) Cells[order[p++]].need = 60 + 12 * spec.level + random.Next(40);
  57. for (int i = 0; i < spec.debris; i++)
  58. {
  59. var c = Cells[order[p++]]; int a = random.Next(spec.colors), b = random.Next(spec.colors - 1); if (b >= a) b++;
  60. c.tiles.Add(a); if (random.Next(2) == 1) c.tiles.Add(a); c.tiles.Add(b);
  61. }
  62. Refill(true);
  63. if (tutorial)
  64. {
  65. foreach (var c in Cells) { c.need = 0; c.tiles.Clear(); }
  66. var center = Cells.First(c => c.q == 0 && c.r == 0);
  67. center.tiles.AddRange(Enumerable.Repeat(1, 7));
  68. for (int i = 0; i < 3; i++) Hand[i] = new HandGroup(1, 1);
  69. }
  70. }
  71. public bool Locked(int i) => Cells[i].need > Score;
  72. public bool CanPlace(int i) => !Over && i >= 0 && i < Cells.Count && !Locked(i) && Cells[i].tiles.Count == 0;
  73. public bool HasSpace => Enumerable.Range(0, Cells.Count).Any(CanPlace);
  74. public List<int> Neighbors(int i)
  75. {
  76. var list = new List<int>(); var c = Cells[i];
  77. for (int d = 0; d < 6; d++) { int j = Cells.FindIndex(o => o.q == c.q + Directions[d, 0] && o.r == c.r + Directions[d, 1]); if (j >= 0) list.Add(j); }
  78. return list;
  79. }
  80. public HandGroup Deal()
  81. {
  82. double hard = (Spec.level - 1) / 19.0, roll = random.NextDouble();
  83. int n = roll < .34 - .24 * hard ? 2 : roll < .78 - .06 * hard ? 3 : 4;
  84. return new HandGroup(random.Next(Spec.colors), n);
  85. }
  86. public void Refill(bool force = false) { if (force || Hand.All(h => h == null)) for (int i = 0; i < 3; i++) Hand[i] = Deal(); }
  87. public void Bonus() { int i = Array.FindIndex(Hand, h => h == null); Hand[i < 0 ? 2 : i] = new HandGroup(random.Next(Spec.colors), 3); }
  88. public bool Unlock() { int i = Enumerable.Range(0, Cells.Count).Where(Locked).OrderBy(x => Cells[x].need).DefaultIfEmpty(-1).First(); if (i < 0) return false; Cells[i].need = 0; return true; }
  89. public bool Hammer(int i) { if (i < 0 || i >= Cells.Count || Locked(i) || Cells[i].tiles.Count == 0) return false; Cells[i].tiles.Clear(); return true; }
  90. public IEnumerable<RuleStep> Place(int slot, int cell)
  91. {
  92. if (slot < 0 || slot >= 3 || Hand[slot] == null || !CanPlace(cell)) yield break;
  93. var h = Hand[slot]; Hand[slot] = null; Cells[cell].tiles.AddRange(Enumerable.Repeat(h.color, h.count)); Score += h.count * 2;
  94. yield return new RuleStep { kind = StepKind.Place, from = slot, to = cell, color = h.color, count = h.count };
  95. Refill();
  96. foreach (var step in Resolve()) yield return step;
  97. }
  98. public static bool FindRun(List<int> tiles, out int start, out int count)
  99. {
  100. for (int i = 0; i < tiles.Count;) { int j = i + 1; while (j < tiles.Count && tiles[j] == tiles[i]) j++; if (j - i >= ClearCount) { start = i; count = j - i; return true; } i = j; }
  101. start = count = 0; return false;
  102. }
  103. sealed class ChainContext { public int value = 1; }
  104. IEnumerable<RuleStep> Clear(int i, ChainContext ctx)
  105. {
  106. int start, n;
  107. while (FindRun(Cells[i].tiles, out start, out n))
  108. {
  109. int color = Cells[i].tiles[start], chain = ctx.value++;
  110. Cells[i].tiles.RemoveRange(start, n);
  111. int gain = (60 + 12 * Math.Max(0, n - 8)) * chain;
  112. Score += gain; Clears++; if (Spec.mode == 1) Time += 4;
  113. yield return new RuleStep { kind = StepKind.Clear, to = i, color = color, count = n, chain = chain, gain = gain, startIndex = start };
  114. var affected = Neighbors(i).Where(j => !Locked(j) && Cells[j].Top == color).ToList();
  115. foreach (int j in affected) { Cells[j].tiles.Add(color); yield return new RuleStep { kind = StepKind.Neighbor, to = j, color = color, count = 1 }; }
  116. foreach (int j in affected) foreach (var s in Clear(j, ctx)) yield return s;
  117. }
  118. }
  119. public IEnumerable<RuleStep> Resolve()
  120. {
  121. var ctx = new ChainContext();
  122. for (int guard = 0; guard < 512; guard++)
  123. {
  124. int run = Cells.FindIndex(c => FindRun(c.tiles, out _, out _));
  125. if (run >= 0) { foreach (var s in Clear(run, ctx)) yield return s; continue; }
  126. var seen = new HashSet<int>(); List<int> group = null;
  127. for (int i = 0; i < Cells.Count; i++)
  128. {
  129. if (seen.Contains(i) || Locked(i) || Cells[i].Top < 0) continue;
  130. var g = new List<int> { i }; seen.Add(i); int color = Cells[i].Top;
  131. for (int p = 0; p < g.Count; p++) foreach (int j in Neighbors(g[p]))
  132. if (!seen.Contains(j) && !Locked(j) && Cells[j].Top == color) { seen.Add(j); g.Add(j); }
  133. if (g.Count > 1) { group = g; break; }
  134. }
  135. if (group == null) yield break;
  136. Func<int, int> degree = i => Neighbors(i).Count(group.Contains);
  137. Func<int, int> diversity = i => Cells[i].tiles.Distinct().Count();
  138. int target = group.OrderByDescending(degree).ThenBy(diversity).ThenByDescending(i => Cells[i].tiles.Count).First();
  139. var sources = group.Where(i => i != target).OrderBy(degree).ThenByDescending(diversity).ThenBy(i => Cells[i].tiles.Count).ToList();
  140. foreach (int src in sources)
  141. {
  142. var c = Cells[src]; int n = c.TopCount, color = c.Top, baseCount = Cells[target].tiles.Count;
  143. c.tiles.RemoveRange(c.tiles.Count - n, n); Cells[target].tiles.AddRange(Enumerable.Repeat(color, n));
  144. yield return new RuleStep { kind = StepKind.Merge, from = src, to = target, color = color, count = n, baseCount = baseCount };
  145. }
  146. }
  147. throw new InvalidOperationException("Settlement did not converge");
  148. }
  149. static List<HexCell> Disk(int radius)
  150. {
  151. var list = new List<HexCell>();
  152. for (int q = -radius; q <= radius; q++) for (int r = Math.Max(-radius, -q - radius); r <= Math.Min(radius, -q + radius); r++) list.Add(new HexCell { q = q, r = r });
  153. return list;
  154. }
  155. static int Distance(HexCell c) => Math.Max(Math.Abs(c.q), Math.Max(Math.Abs(c.r), Math.Abs(c.q + c.r)));
  156. public static bool Connected(List<HexCell> list)
  157. {
  158. if (list.Count == 0) return false;
  159. var visited = new HashSet<HexCell> { list[0] }; var queue = new Queue<HexCell>(); queue.Enqueue(list[0]);
  160. while (queue.Count > 0) { var c = queue.Dequeue(); for (int d = 0; d < 6; d++) { var n = list.Find(o => o.q == c.q + Directions[d, 0] && o.r == c.r + Directions[d, 1]); if (n != null && visited.Add(n)) queue.Enqueue(n); } }
  161. return visited.Count == list.Count;
  162. }
  163. public static List<HexCell> Generate(int n, int shape, Random rng)
  164. {
  165. int radius = 1; while (3 * radius * radius + 3 * radius + 1 < n) radius++;
  166. if (shape == 0) return Disk(radius);
  167. if (shape == 2 && n >= 25)
  168. {
  169. var keep = Disk(radius); var gone = new HashSet<string>();
  170. Func<HexCell,int> missing = c => Enumerable.Range(0,6).Count(d => gone.Contains((c.q+Directions[d,0])+","+(c.r+Directions[d,1])));
  171. for (int guard = 0; keep.Count > n && guard < 2000; guard++)
  172. {
  173. var list = keep.Where(c => Distance(c) > 0).ToList(); var ring = list.Where(c => missing(c)>0).ToList(); List<HexCell> pool;
  174. if (ring.Count > 0 && rng.NextDouble() < .85) { int mx = ring.Max(missing); pool = ring.Where(c => missing(c)==mx).ToList(); }
  175. else { pool = list.Where(c => missing(c)==0).ToList(); if(pool.Count==0) pool=list; }
  176. var pick=pool[rng.Next(pool.Count)]; int idx=keep.IndexOf(pick); keep.RemoveAt(idx);
  177. if (!Connected(keep)) { keep.Insert(idx,pick); continue; } gone.Add(pick.q+","+pick.r);
  178. }
  179. if (keep.Count == n) return keep;
  180. }
  181. var result = new List<HexCell>();
  182. for (int rad=0; result.Count<n;rad++)
  183. {
  184. var ring=Disk(rad).Where(c=>Distance(c)==rad).OrderBy(c=>Math.Atan2(Math.Sqrt(3)*(c.r+c.q/2.0),1.5*c.q)).ToList();
  185. int remaining=n-result.Count;
  186. if (remaining>=ring.Count) result.AddRange(ring);
  187. else for(int i=0;i<remaining;i++) result.Add(ring[(int)Math.Floor((i+.5)*ring.Count/remaining)%ring.Count]);
  188. }
  189. return result;
  190. }
  191. }
  192. }