| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace HexaCrazy
- {
- [Serializable] public class LevelSpec
- {
- public int mode, level, cells, target, colors, locks, debris, shape, seconds;
- public int Reward => mode == 1 ? 160 + 35 * level : mode == 2 ? 150 + 32 * level : 130 + 30 * level;
- }
- [Serializable] public class HexCell
- {
- public int q, r, need;
- public List<int> tiles = new List<int>();
- public int Top => tiles.Count == 0 ? -1 : tiles[tiles.Count - 1];
- public int TopCount { get { int n = 0; for (int i = tiles.Count - 1; i >= 0 && tiles[i] == Top; i--) n++; return n; } }
- }
- [Serializable] public class HandGroup { public int color, count; public HandGroup(int c, int n) { color = c; count = n; } }
- public enum StepKind { Place, Merge, Clear, Neighbor }
- public class RuleStep
- {
- public StepKind kind; public int from = -1, to, color, count, chain, gain, baseCount, startIndex;
- }
- public sealed class HexRules
- {
- public const int ClearCount = 8;
- public static readonly int[,] Directions = { {1,0},{1,-1},{0,-1},{-1,0},{-1,1},{0,1} };
- public readonly List<HexCell> Cells;
- public HandGroup[] Hand = new HandGroup[3];
- public readonly LevelSpec Spec;
- public int Score, Clears;
- public float Time;
- public bool Over;
- public bool ReviveUsed { get; private set; }
- public bool TryRevive()
- {
- if (!Over || ReviveUsed || Score >= Spec.target) return false;
- Over = false;
- if (!HasSpace)
- {
- var smallest = Cells.Where(c => c.need <= Score && c.tiles.Count > 0)
- .OrderBy(c => c.tiles.Count).Take(3).ToArray();
- foreach (var cell in smallest) cell.tiles.Clear();
- }
- if (Spec.mode == 1 && Time <= 0) Time = 30;
- ReviveUsed = true;
- return true;
- }
- readonly Random random;
- public HexRules(LevelSpec spec, int seed, bool tutorial = false)
- {
- Spec = spec; random = new Random(seed); Time = spec.seconds;
- Cells = Generate(spec.cells, spec.shape, random);
- var order = Enumerable.Range(0, Cells.Count).OrderBy(_ => random.Next()).ToList();
- int p = 0;
- for (int i = 0; i < spec.locks; i++) Cells[order[p++]].need = 60 + 12 * spec.level + random.Next(40);
- for (int i = 0; i < spec.debris; i++)
- {
- var c = Cells[order[p++]]; int a = random.Next(spec.colors), b = random.Next(spec.colors - 1); if (b >= a) b++;
- c.tiles.Add(a); if (random.Next(2) == 1) c.tiles.Add(a); c.tiles.Add(b);
- }
- Refill(true);
- if (tutorial)
- {
- foreach (var c in Cells) { c.need = 0; c.tiles.Clear(); }
- var center = Cells.First(c => c.q == 0 && c.r == 0);
- center.tiles.AddRange(Enumerable.Repeat(1, 7));
- for (int i = 0; i < 3; i++) Hand[i] = new HandGroup(1, 1);
- }
- }
- public bool Locked(int i) => Cells[i].need > Score;
- public bool CanPlace(int i) => !Over && i >= 0 && i < Cells.Count && !Locked(i) && Cells[i].tiles.Count == 0;
- public bool HasSpace => Enumerable.Range(0, Cells.Count).Any(CanPlace);
- public List<int> Neighbors(int i)
- {
- var list = new List<int>(); var c = Cells[i];
- 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); }
- return list;
- }
- public HandGroup Deal()
- {
- double hard = (Spec.level - 1) / 19.0, roll = random.NextDouble();
- int n = roll < .34 - .24 * hard ? 2 : roll < .78 - .06 * hard ? 3 : 4;
- return new HandGroup(random.Next(Spec.colors), n);
- }
- public void Refill(bool force = false) { if (force || Hand.All(h => h == null)) for (int i = 0; i < 3; i++) Hand[i] = Deal(); }
- public void Bonus() { int i = Array.FindIndex(Hand, h => h == null); Hand[i < 0 ? 2 : i] = new HandGroup(random.Next(Spec.colors), 3); }
- 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; }
- 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; }
- public IEnumerable<RuleStep> Place(int slot, int cell)
- {
- if (slot < 0 || slot >= 3 || Hand[slot] == null || !CanPlace(cell)) yield break;
- var h = Hand[slot]; Hand[slot] = null; Cells[cell].tiles.AddRange(Enumerable.Repeat(h.color, h.count)); Score += h.count * 2;
- yield return new RuleStep { kind = StepKind.Place, from = slot, to = cell, color = h.color, count = h.count };
- Refill();
- foreach (var step in Resolve()) yield return step;
- }
- public static bool FindRun(List<int> tiles, out int start, out int count)
- {
- 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; }
- start = count = 0; return false;
- }
- sealed class ChainContext { public int value = 1; }
- IEnumerable<RuleStep> Clear(int i, ChainContext ctx)
- {
- int start, n;
- while (FindRun(Cells[i].tiles, out start, out n))
- {
- int color = Cells[i].tiles[start], chain = ctx.value++;
- Cells[i].tiles.RemoveRange(start, n);
- int gain = (60 + 12 * Math.Max(0, n - 8)) * chain;
- Score += gain; Clears++; if (Spec.mode == 1) Time += 4;
- yield return new RuleStep { kind = StepKind.Clear, to = i, color = color, count = n, chain = chain, gain = gain, startIndex = start };
- var affected = Neighbors(i).Where(j => !Locked(j) && Cells[j].Top == color).ToList();
- foreach (int j in affected) { Cells[j].tiles.Add(color); yield return new RuleStep { kind = StepKind.Neighbor, to = j, color = color, count = 1 }; }
- foreach (int j in affected) foreach (var s in Clear(j, ctx)) yield return s;
- }
- }
- public IEnumerable<RuleStep> Resolve()
- {
- var ctx = new ChainContext();
- for (int guard = 0; guard < 512; guard++)
- {
- int run = Cells.FindIndex(c => FindRun(c.tiles, out _, out _));
- if (run >= 0) { foreach (var s in Clear(run, ctx)) yield return s; continue; }
- var seen = new HashSet<int>(); List<int> group = null;
- for (int i = 0; i < Cells.Count; i++)
- {
- if (seen.Contains(i) || Locked(i) || Cells[i].Top < 0) continue;
- var g = new List<int> { i }; seen.Add(i); int color = Cells[i].Top;
- for (int p = 0; p < g.Count; p++) foreach (int j in Neighbors(g[p]))
- if (!seen.Contains(j) && !Locked(j) && Cells[j].Top == color) { seen.Add(j); g.Add(j); }
- if (g.Count > 1) { group = g; break; }
- }
- if (group == null) yield break;
- Func<int, int> degree = i => Neighbors(i).Count(group.Contains);
- Func<int, int> diversity = i => Cells[i].tiles.Distinct().Count();
- int target = group.OrderByDescending(degree).ThenBy(diversity).ThenByDescending(i => Cells[i].tiles.Count).First();
- var sources = group.Where(i => i != target).OrderBy(degree).ThenByDescending(diversity).ThenBy(i => Cells[i].tiles.Count).ToList();
- foreach (int src in sources)
- {
- var c = Cells[src]; int n = c.TopCount, color = c.Top, baseCount = Cells[target].tiles.Count;
- c.tiles.RemoveRange(c.tiles.Count - n, n); Cells[target].tiles.AddRange(Enumerable.Repeat(color, n));
- yield return new RuleStep { kind = StepKind.Merge, from = src, to = target, color = color, count = n, baseCount = baseCount };
- }
- }
- throw new InvalidOperationException("Settlement did not converge");
- }
- static List<HexCell> Disk(int radius)
- {
- var list = new List<HexCell>();
- 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 });
- return list;
- }
- static int Distance(HexCell c) => Math.Max(Math.Abs(c.q), Math.Max(Math.Abs(c.r), Math.Abs(c.q + c.r)));
- public static bool Connected(List<HexCell> list)
- {
- if (list.Count == 0) return false;
- var visited = new HashSet<HexCell> { list[0] }; var queue = new Queue<HexCell>(); queue.Enqueue(list[0]);
- 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); } }
- return visited.Count == list.Count;
- }
- public static List<HexCell> Generate(int n, int shape, Random rng)
- {
- int radius = 1; while (3 * radius * radius + 3 * radius + 1 < n) radius++;
- if (shape == 0) return Disk(radius);
- if (shape == 2 && n >= 25)
- {
- var keep = Disk(radius); var gone = new HashSet<string>();
- Func<HexCell,int> missing = c => Enumerable.Range(0,6).Count(d => gone.Contains((c.q+Directions[d,0])+","+(c.r+Directions[d,1])));
- for (int guard = 0; keep.Count > n && guard < 2000; guard++)
- {
- var list = keep.Where(c => Distance(c) > 0).ToList(); var ring = list.Where(c => missing(c)>0).ToList(); List<HexCell> pool;
- if (ring.Count > 0 && rng.NextDouble() < .85) { int mx = ring.Max(missing); pool = ring.Where(c => missing(c)==mx).ToList(); }
- else { pool = list.Where(c => missing(c)==0).ToList(); if(pool.Count==0) pool=list; }
- var pick=pool[rng.Next(pool.Count)]; int idx=keep.IndexOf(pick); keep.RemoveAt(idx);
- if (!Connected(keep)) { keep.Insert(idx,pick); continue; } gone.Add(pick.q+","+pick.r);
- }
- if (keep.Count == n) return keep;
- }
- var result = new List<HexCell>();
- for (int rad=0; result.Count<n;rad++)
- {
- 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();
- int remaining=n-result.Count;
- if (remaining>=ring.Count) result.AddRange(ring);
- else for(int i=0;i<remaining;i++) result.Add(ring[(int)Math.Floor((i+.5)*ring.Count/remaining)%ring.Count]);
- }
- return result;
- }
- }
- }
|