namespace SOR.Game.Grid; using System.Text.Json; using SOR.Database.Enums; /// /// Generates instances for different board shapes, populating /// for each player seat. /// public static class BoardShapeGenerator { /// /// Returns the recommended board shape for a given player count when none is explicitly specified. /// public static string AutoShape(int playerCount) => playerCount switch { 3 => "Triangular", 4 => "Cross", 5 => "RadialStar", 6 => "HexRing", 7 => "Decagonal", 8 => "Decagonal", 9 => "Decagonal", 10 => "Decagonal", _ => "Rectangle", // 2 }; /// /// Normalize inbound shape labels to canonical values. /// Null/empty/"Default" auto-selects by player count. /// public static string NormalizeShape(string? shape, int playerCount) { if (string.IsNullOrWhiteSpace(shape) || shape.Equals("Default", StringComparison.OrdinalIgnoreCase)) return AutoShape(playerCount); return shape.Trim().ToLowerInvariant() switch { "rectangle" => "Rectangle", "cross" => "Cross", "triangular" => "Triangular", "triangle" => "Triangular", // alias accepted from older/alternate clients "radialstar" => "RadialStar", "hexring" => "HexRing", "decagonal" => "Decagonal", "hexagon" => "Hexagon", _ => "Rectangle", }; } /// Generate a board appropriate for the given shape, rules, and player count. public static Board Generate(string? shape, GameRules rules, int playerCount) { var normalized = NormalizeShape(shape, playerCount); return normalized switch { "Cross" => MakeCross(rules), "Triangular" => MakeTriangular(rules), "RadialStar" => MakeRadialStar(rules), "HexRing" => MakeHexRing(rules), "Decagonal" => MakeDecagonal(rules, playerCount), "Hexagon" => MakeHexagon(rules, playerCount), _ => MakeRectangle(rules, playerCount), }; } /// /// Rectangle board. Starting zones per seat: /// Seat 0 = rows 0–1 (bottom edge) /// Seat 1 = rows Height-2 .. Height-1 (top edge) /// Seat 2 = cols 0–1 (left edge) /// Seat 3 = cols Width-2 .. Width-1 (right edge) /// private static Board MakeRectangle(GameRules rules, int playerCount) { var board = Board.Create(rules.BoardWidth, rules.BoardHeight, rules.StartingRandomTilePct); int w = rules.BoardWidth, h = rules.BoardHeight; var zones = new Dictionary>(); // 2-player: one placement row each (preserves original 1v1 behavior). // 3-4 player: two rows/cols per seat to give more placement room. if (playerCount <= 2) { zones[0] = CoordsInRows(0, 0, w); if (playerCount >= 2) zones[1] = CoordsInRows(h - 1, h - 1, w); } else { zones[0] = CoordsInRows(0, 1, w); if (playerCount >= 2) zones[1] = CoordsInRows(h - 2, h - 1, w); if (playerCount >= 3) zones[2] = CoordsInCols(0, 1, h); if (playerCount >= 4) zones[3] = CoordsInCols(w - 2, w - 1, h); } // Return a new Board with the zones attached (Board is a reference type with mutable Tiles // so we create a wrapper that shares the same Tiles dictionary). return new Board { Width = board.Width, Height = board.Height, Tiles = board.Tiles, StartingZones = zones }; } /// /// Cross (plus-sign) board for 4 players. /// A square center arena with 4 arms; the tip of each arm is one player's starting zone. /// private static Board MakeCross(GameRules rules) { const int arm = 4; const int center = 5; int total = center + arm * 2; // 13 in each dimension var tiles = new Dictionary(); // Center square for (int x = arm; x < arm + center; x++) for (int y = arm; y < arm + center; y++) AddTile(tiles, x, y); int mid = arm + center / 2; // midpoint column/row of the center section // Bottom arm for (int i = 0; i < arm; i++) AddTile(tiles, mid, i); // Top arm for (int i = 0; i < arm; i++) AddTile(tiles, mid, arm + center + i); // Left arm for (int i = 0; i < arm; i++) AddTile(tiles, i, mid); // Right arm for (int i = 0; i < arm; i++) AddTile(tiles, arm + center + i, mid); var zones = new Dictionary> { [0] = new() { new Coord(mid, 0) }, // bottom tip [1] = new() { new Coord(mid, arm + center - 1 + arm) }, // top tip [2] = new() { new Coord(0, mid) }, // left tip [3] = new() { new Coord(arm + center - 1 + arm, mid) }, // right tip }; return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones }; } /// /// Triangular board for 3 players. /// Uses a symmetric sparse footprint with equal corner-to-corner path lengths: /// Seat 0 = bottom-left corner, Seat 1 = bottom-right corner, Seat 2 = top apex. /// /// Geometry is chosen so: /// base distance (corner↔corner) == side distance (corner↔apex) /// under orthogonal movement. /// private static Board MakeTriangular(GameRules rules) { // Let "side" be the desired equal travel distance between any two starting corners. // For an isosceles triangle on an orthogonal grid: // base = w - 1 // side = (w - 1)/2 + (h - 1) // Enforce equality by picking h = (w + 1)/2, i.e. side = base. int side = Math.Max(12, Math.Max(rules.BoardWidth - 1, 2 * (rules.BoardHeight - 1))); if (side % 2 != 0) side++; // keep width odd so apex is centered exactly int w = side + 1; // odd int h = side / 2 + 1; // ensures equidistant corners int cx = w / 2; var tiles = new Dictionary(); for (int y = 0; y < h; y++) { // Shrink by 1 tile per side each row moving upward. int halfSpan = (h - 1) - y; int x0 = cx - halfSpan; int x1 = cx + halfSpan; for (int x = x0; x <= x1; x++) AddTile(tiles, x, y, rules.StartingRandomTilePct); } var seat0 = new Coord(0, 0); var seat1 = new Coord(w - 1, 0); var seat2 = new Coord(cx, h - 1); var zones = new Dictionary> { [0] = new() { seat0 }, [1] = new() { seat1 }, [2] = new() { seat2 }, }; return new Board { Width = w, Height = h, Tiles = tiles, StartingZones = zones }; } /// /// Radial star board for 5 players. /// Five arms radiating from a central arena; one starting-zone tile at each arm tip. /// Arms point: bottom, lower-right, upper-right, upper-left, lower-left (pentagon arrangement). /// private static Board MakeRadialStar(GameRules rules) { const int armLen = 5; // tiles per arm (not counting center) const int arenaR = 4; // radius of central filled square (half-width) int center = arenaR * 2 + 1; // 9 int total = center + armLen * 2; // 19 in each dimension (plenty of room) var tiles = new Dictionary(); // Central arena int c = total / 2; for (int x = c - arenaR; x <= c + arenaR; x++) for (int y = c - arenaR; y <= c + arenaR; y++) AddTile(tiles, x, y); // 5 arms at angles 270°, 342°, 54°, 126°, 198° (bottom-first, counter-clockwise) // Approximated on a square grid as (dx, dy) unit directions scaled to armLen steps. // Pentagon vertices (unit circle, starting at bottom): // 270° → (0, -1) lower center // 342° → (0.95, -0.31) → approx (1, 0) then (1,-1) staircase // 54° → (0.59, 0.81) → approx (1, 1) staircase // 126° → (-0.59, 0.81) → approx (-1, 1) // 198° → (-0.95, -0.31) → approx (-1, 0) then (-1,-1) // Grid-friendly arm directions for the 5 seats: (int dx, int dy)[] dirs = [ ( 0, -1), // Seat 0: bottom ( 1, -1), // Seat 1: lower-right (diagonal) ( 1, 1), // Seat 2: upper-right (diagonal) (-1, 1), // Seat 3: upper-left (diagonal) (-1, -1), // Seat 4: lower-left (diagonal) ]; var zones = new Dictionary>(); for (int seat = 0; seat < dirs.Length; seat++) { var (dx, dy) = dirs[seat]; int tipX = c, tipY = c; for (int step = 1; step <= armLen; step++) { int ax = c + dx * step; int ay = c + dy * step; AddTile(tiles, ax, ay); tipX = ax; tipY = ay; } zones[seat] = new HashSet { new Coord(tipX, tipY) }; } return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones }; } /// /// Hexagonal ring board for 6 players. /// A filled hexagon (approximated on a square grid) with 6 starting zones at the /// flat-top hex vertices: bottom-left, bottom, bottom-right, top-right, top, top-left. /// private static Board MakeHexRing(GameRules rules) { // Use a rectangle large enough to contain the hex, with random tiles. int w = Math.Max(rules.BoardWidth, 14); int h = Math.Max(rules.BoardHeight, 12); var board = Board.Create(w, h, rules.StartingRandomTilePct); // Starting zones at 6 evenly-spaced perimeter positions. // Place them like a hex: 2 on bottom row, 2 on top row, 1 left-mid, 1 right-mid. int zW = Math.Max(2, w / 6); int mY = h / 2; // mid row for left/right zones var zones = new Dictionary> { [0] = CoordsInRect(0, 0, zW - 1, 1, w, h), // bottom-left [1] = CoordsInRect(w / 2 - zW / 2, 0, w / 2 + zW / 2 - 1, 1, w, h), // bottom-center [2] = CoordsInRect(w - zW, 0, w - 1, 1, w, h), // bottom-right [3] = CoordsInRect(w - zW, h - 2, w - 1, h - 1, w, h), // top-right [4] = CoordsInRect(w / 2 - zW / 2, h - 2, w / 2 + zW / 2 - 1, h - 1, w, h), // top-center [5] = CoordsInRect(0, h - 2, zW - 1, h - 1, w, h), // top-left }; return new Board { Width = board.Width, Height = board.Height, Tiles = board.Tiles, StartingZones = zones }; } /// /// Decagonal radial board for 7–10 players. /// A filled square central arena with up to 10 arms evenly spaced around it. /// Only the first arms are activated; the rest are omitted. /// Arm tips in clockwise order starting at the bottom: 270°, 306°, 342°, 18°, 54°, 90°, /// 126°, 162°, 198°, 234°. /// private static Board MakeDecagonal(GameRules rules, int playerCount) { const int armLen = 5; const int arenaR = 5; // half-width of central square (11×11) int center = arenaR * 2 + 1; // 11 int total = center + armLen * 2; // 21 var tiles = new Dictionary(); int c = total / 2; // Central arena for (int x = c - arenaR; x <= c + arenaR; x++) for (int y = c - arenaR; y <= c + arenaR; y++) AddTile(tiles, x, y, rules.StartingRandomTilePct); // 10 arm directions evenly spaced at 36° each. // Grid-approximated unit directions (dx, dy) — chosen so each arm has // a non-degenerate path from the arena edge to its tip. // Angles: 270°, 306°, 342°, 18°, 54°, 90°, 126°, 162°, 198°, 234° (int dx, int dy)[] allDirs = [ ( 0, -1), // 0: 270° bottom ( 1, -1), // 1: 306° lower-right diagonal ( 1, 0), // 2: 342°/0° right ( 1, 1), // 3: 54° upper-right diagonal ( 0, 1), // 4: 90° top (-1, 1), // 5: 126° upper-left diagonal (-1, 0), // 6: 162°/180° left (-1, -1), // 7: 198°/216° lower-left diagonal // Two extra arms split the diagonal sectors for 9/10 players. // These reuse adjacent diagonals with a slight offset (arm root shifted). ( 1, -1), // 8: duplicate lower-right — arm rooted 2 cols right of center (-1, 1), // 9: duplicate upper-left — arm rooted 2 cols left of center ]; // Root offsets for arms 8 and 9 to avoid overlap with arms 1/5. int[] rootOffsetX = [0, 0, 0, 0, 0, 0, 0, 0, 2, -2]; int[] rootOffsetY = [0, 0, 0, 0, 0, 0, 0, 0, -2, 2]; int seats = Math.Clamp(playerCount, 7, 10); var zones = new Dictionary>(); for (int seat = 0; seat < seats; seat++) { var (dx, dy) = allDirs[seat]; int rx = c + rootOffsetX[seat]; int ry = c + rootOffsetY[seat]; int tipX = rx, tipY = ry; for (int step = 1; step <= armLen; step++) { int ax = rx + dx * step; int ay = ry + dy * step; // Clamp to grid bounds. if (ax < 0 || ax >= total || ay < 0 || ay >= total) break; AddTile(tiles, ax, ay, rules.StartingRandomTilePct); tipX = ax; tipY = ay; } zones[seat] = new HashSet { new Coord(tipX, tipY) }; } return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones }; } /// /// Regular hexagonal board. N controls size (3–10). /// Diameter = 2N−1. Up to 6 starting zones, one per flat-top edge, assigned in order /// bottom → lower-right → upper-right → top → upper-left → lower-left. /// private static Board MakeHexagon(GameRules rules, int playerCount) { int N = Math.Clamp(rules.HexSides > 0 ? rules.HexSides : 5, 3, 10); int diameter = 2 * N - 1; var tiles = new Dictionary(); for (int x = 0; x < diameter; x++) for (int y = 0; y < diameter; y++) { var c = new Coord(x, y); if (HexGrid.IsInBounds(c, N)) AddTile(tiles, x, y, rules.StartingRandomTilePct); } // Six edge directions in axial (dq, dr) — each edge spans N tiles. // Axial corners (q,r): (N-1, -(N-1)), (N-1, 0), (0, N-1), // (-(N-1), N-1), (-(N-1), 0), (0, -(N-1)) (int q, int r)[] corners = [ ( N-1, -(N-1)), // edge 0 start (bottom-right corner) ( N-1, 0), // edge 1 start (right corner) ( 0, N-1), // edge 2 start (upper-right corner) (-(N-1), N-1), // edge 3 start (upper-left corner) — top edge start (-(N-1), 0), // edge 4 start (left corner) ( 0, -(N-1)), // edge 5 start (lower-left corner) ]; (int dq, int dr)[] edgeDirs = [ (-1, +1), // edge 0: bottom (-1, 0), // edge 1: lower-right ( 0, -1), // edge 2: upper-right (+1, -1), // edge 3: top (+1, 0), // edge 4: upper-left ( 0, +1), // edge 5: lower-left ]; int seats = Math.Clamp(playerCount, 2, 6); int[] edgeAssign = seats switch { 2 => [0, 3], 3 => [0, 2, 4], 4 => [0, 1, 3, 4], 5 => [0, 1, 2, 3, 4], _ => [0, 1, 2, 3, 4, 5], }; var zones = new Dictionary>(); for (int seat = 0; seat < seats; seat++) { int ei = edgeAssign[seat]; var (sq, sr) = corners[ei]; var (dq, dr) = edgeDirs[ei]; var edge = new HashSet(N); for (int step = 0; step < N; step++) { var c = HexGrid.FromAxial(sq + dq * step, sr + dr * step, N); if (HexGrid.IsInBounds(c, N)) edge.Add(c); } zones[seat] = edge; } return new Board { Width = diameter, Height = diameter, HexSides = N, Tiles = tiles, StartingZones = zones, }; } // ── Template-based board ────────────────────────────────────────────────── /// /// Separate options for template deserialisation: no JsonStringEnumConverter — /// the admin builder serialises affinities as integers. /// private static readonly JsonSerializerOptions _templateJson = new(JsonSerializerDefaults.Web); /// /// Build a from a . /// /// All Width × Height cells are present in the result; tiles absent from /// . default to Void+Void. /// /// When is > 0, tiles whose /// flag is set are independently /// randomised with that probability (matching the normal logic). /// Locked tiles (AffinityOverrideable = false) always keep their designed affinity. /// public static Board FromTemplate( BoardTemplateSnapshot snapshot, int playerCount, int startingRandomTilePct = 0) { var pct = Math.Clamp(startingRandomTilePct, 0, 100); var tiles = new Dictionary(snapshot.Width * snapshot.Height); // Populate all cells with default Void+Void. for (int y = 0; y < snapshot.Height; y++) for (int x = 0; x < snapshot.Width; x++) { var c = new Coord(x, y); tiles[c.ToKey()] = new Tile { Coord = c }; } // Apply designed affinities, respecting the overrideable flag. foreach (var td in snapshot.Tiles) { if (td.X < 0 || td.X >= snapshot.Width || td.Y < 0 || td.Y >= snapshot.Height) continue; var c = new Coord(td.X, td.Y); // Absent tiles are completely removed from the board (sparse layout). if (td.IsAbsent) { tiles.Remove(c.ToKey()); continue; } var tile = new Tile { Coord = c }; if (td.AffinityOverrideable && pct > 0 && Random.Shared.Next(100) < pct) { // Randomise Base1/Base2 identically to Board.Create. var b1 = _base1Pool[Random.Shared.Next(_base1Pool.Length)]; var b2 = Random.Shared.Next(100) < pct ? _base2Pool[Random.Shared.Next(_base2Pool.Length)] : Affinity.Void; if (b2 != Affinity.Void) { tile.Base1 = b1; tile.Base2 = b2; } } else { tile.Base1 = td.Base1; tile.Base2 = td.Base2; } tiles[c.ToKey()] = tile; } // Resolve starting zones for the given player count. var zones = new Dictionary>(); if (snapshot.StartingZones.TryGetValue(playerCount, out var seatMap)) { foreach (var (seat, coords) in seatMap) { var set = new HashSet(coords.Count); foreach (var xy in coords) { var sep = xy.IndexOf(','); if (sep > 0 && int.TryParse(xy[..sep], out int cx) && int.TryParse(xy[(sep + 1)..], out int cy)) set.Add(new Coord(cx, cy)); } zones[seat] = set; } } return new Board { Width = snapshot.Width, Height = snapshot.Height, HexSides = snapshot.HexSides, Tiles = tiles, StartingZones = zones, }; } /// /// Deserialise a JSON snapshot string and delegate to /// . /// public static Board FromTemplateJson(string json, int playerCount, int startingRandomTilePct = 0) { var snapshot = JsonSerializer.Deserialize(json, _templateJson) ?? throw new InvalidOperationException("Failed to deserialise BoardTemplateSnapshot."); return FromTemplate(snapshot, playerCount, startingRandomTilePct); } // ── Helpers ─────────────────────────────────────────────────────────────── private static HashSet CoordsInRect(int x0, int y0, int x1, int y1, int w, int h) { var s = new HashSet(); for (int x = Math.Max(0, x0); x <= Math.Min(w - 1, x1); x++) for (int y = Math.Max(0, y0); y <= Math.Min(h - 1, y1); y++) s.Add(new Coord(x, y)); return s; } private static HashSet CoordsInRows(int r0, int r1, int width) { var s = new HashSet(); for (int x = 0; x < width; x++) for (int y = r0; y <= r1; y++) s.Add(new Coord(x, y)); return s; } private static HashSet CoordsInCols(int c0, int c1, int height) { var s = new HashSet(); for (int x = c0; x <= c1; x++) for (int y = 0; y < height; y++) s.Add(new Coord(x, y)); return s; } private static HashSet CollectExistingRect( Dictionary tiles, int x0, int y0, int x1, int y1) { var s = new HashSet(); for (int x = Math.Min(x0, x1); x <= Math.Max(x0, x1); x++) for (int y = Math.Min(y0, y1); y <= Math.Max(y0, y1); y++) { var c = new Coord(x, y); if (tiles.ContainsKey(c.ToKey())) s.Add(c); } return s; } private static readonly Affinity[] _base1Pool = [Affinity.Lake, Affinity.Hill, Affinity.Forest, Affinity.Field, Affinity.Aether]; private static readonly Affinity[] _base2Pool = [Affinity.Lake, Affinity.Hill, Affinity.Forest, Affinity.Field, Affinity.Aether, Affinity.Void]; private static void AddTile(Dictionary tiles, int x, int y, int startingRandomTilePct = 0) { var c = new Coord(x, y); var tile = new Tile { Coord = c }; var pct = Math.Clamp(startingRandomTilePct, 0, 100); if (pct > 0 && Random.Shared.Next(100) < pct) { var b1 = _base1Pool[Random.Shared.Next(_base1Pool.Length)]; var b2 = Random.Shared.Next(100) < pct ? _base2Pool[Random.Shared.Next(_base2Pool.Length)] : Affinity.Void; if (b2 != Affinity.Void) { tile.Base1 = b1; tile.Base2 = b2; } } tiles[c.ToKey()] = tile; } }