diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs index 9bee078..9d65720 100644 --- a/Server/src/SOR.Game/GameEngine.cs +++ b/Server/src/SOR.Game/GameEngine.cs @@ -94,8 +94,10 @@ public static class GameEngine PlayerOneAccountId = players[0].accountId.ToString(), SeatOrder = players.Select(p => p.accountId.ToString()).ToList(), Phase = GamePhase.Placement, - Rules = r with { PlayerCount = players.Count, BoardShape = resolvedShape }, - Board = BoardShapeGenerator.Generate(resolvedShape, r, players.Count), + Rules = r with { PlayerCount = players.Count, BoardShape = resolvedShape }, + Board = string.IsNullOrEmpty(r.BoardTemplateJson) + ? BoardShapeGenerator.Generate(resolvedShape, r, players.Count) + : BoardShapeGenerator.FromTemplateJson(r.BoardTemplateJson, players.Count, r.StartingRandomTilePct), }; foreach (var (accountId, deck, arch, seatIdx, teamIdx) in players) diff --git a/Server/src/SOR.Game/GameRules.cs b/Server/src/SOR.Game/GameRules.cs index 4e1d6cd..14c2084 100644 --- a/Server/src/SOR.Game/GameRules.cs +++ b/Server/src/SOR.Game/GameRules.cs @@ -62,5 +62,13 @@ public sealed record GameRules /// Number of players in this game. 2 = standard 1v1. public int PlayerCount { get; init; } = 2; + /// + /// When non-null, the board is built from this admin-defined template snapshot instead of + /// being generated algorithmically from . + /// Set at session-creation time from BoardTemplate.TilesJson + + /// StartingZonesJson so that in-flight games are unaffected by template edits. + /// + public string? BoardTemplateJson { get; init; } + public static readonly GameRules Default = new(); } diff --git a/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs b/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs index e519ac1..e48c264 100644 --- a/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs +++ b/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs @@ -1,5 +1,6 @@ namespace SOR.Game.Grid; +using System.Text.Json; using SOR.Database.Enums; /// @@ -268,6 +269,112 @@ public static class BoardShapeGenerator return new Board { Width = board.Width, Height = board.Height, Tiles = board.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); + 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, + 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) diff --git a/Server/src/SOR.Game/Grid/BoardTemplateSnapshot.cs b/Server/src/SOR.Game/Grid/BoardTemplateSnapshot.cs new file mode 100644 index 0000000..51bab03 --- /dev/null +++ b/Server/src/SOR.Game/Grid/BoardTemplateSnapshot.cs @@ -0,0 +1,34 @@ +namespace SOR.Game.Grid; + +using System.Text.Json.Serialization; +using SOR.Database.Enums; + +/// +/// Lightweight snapshot of a BoardTemplate DB entity embedded in +/// at session-creation time. +/// +/// Integer enum values are used throughout (matching the admin builder serialisation) +/// so System.Text.Json default options (no JsonStringEnumConverter) are sufficient. +/// +public sealed class BoardTemplateSnapshot +{ + public int Width { get; set; } + public int Height { get; set; } + + public List Tiles { get; set; } = new(); + + /// + /// playerCount → (seatIndex → list of "x,y" coordinate strings). + /// Keys are integers serialised as JSON strings by STJ. + /// + public Dictionary>> StartingZones { get; set; } = new(); +} + +public sealed class SnapshotTile +{ + [JsonPropertyName("x")] public int X { get; set; } + [JsonPropertyName("y")] public int Y { get; set; } + [JsonPropertyName("b1")] public Affinity Base1 { get; set; } + [JsonPropertyName("b2")] public Affinity Base2 { get; set; } + [JsonPropertyName("ao")] public bool AffinityOverrideable { get; set; } +} diff --git a/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs b/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs index 92f6f10..9eb0c99 100644 --- a/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs @@ -230,6 +230,30 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler ? lobby.BoardShapeOverride : BoardShapeGenerator.AutoShape(playerCount); + // If the lobby specifies a board template, load it and build a snapshot JSON string + // that will be embedded in the rule snapshot so in-flight games are unaffected by later edits. + string? boardTemplateJson = null; + if (lobby.BoardTemplateIdOverride.HasValue) + { + var tmpl = await _gameDb.BoardTemplates + .FindAsync(new object[] { lobby.BoardTemplateIdOverride.Value }, ct); + if (tmpl is not null) + { + var tileOpts = new JsonSerializerOptions(JsonSerializerDefaults.Web); + var tiles = JsonSerializer.Deserialize>(tmpl.TilesJson, tileOpts) ?? new(); + var zones = JsonSerializer.Deserialize>>>( + tmpl.StartingZonesJson, tileOpts) ?? new(); + boardTemplateJson = JsonSerializer.Serialize( + new BoardTemplateSnapshot + { + Width = tmpl.Width, + Height = tmpl.Height, + Tiles = tiles, + StartingZones = zones, + }, tileOpts); + } + } + // Build effective rules: lobby override → admin custom-default → hard-coded default. var rules = new GameRules { @@ -252,6 +276,7 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler MpBuff = lobby.MpBuffOverride ?? dbDefaults?.MpBuff ?? GameRules.Default.MpBuff, StartingRandomTilePct = lobby.StartingRandomTilePctOverride ?? dbDefaults?.StartingRandomTilePct ?? GameRules.Default.StartingRandomTilePct, BoardShape = boardShape, + BoardTemplateJson = boardTemplateJson, PlayerCount = playerCount, }; diff --git a/Server/src/SOR.Matchmaking/MatchmakerService.cs b/Server/src/SOR.Matchmaking/MatchmakerService.cs index 02b3e0f..1ee0683 100644 --- a/Server/src/SOR.Matchmaking/MatchmakerService.cs +++ b/Server/src/SOR.Matchmaking/MatchmakerService.cs @@ -110,6 +110,27 @@ internal sealed class MatchmakerService : BackgroundService .Where(r => r.IsRankedDefault) .FirstOrDefaultAsync(ct); + // If the ranked ruleset references a board template, embed a snapshot so + // in-flight games are not affected by future template edits. + string? boardTemplateJson = null; + if (rankedRules?.BoardTemplateId.HasValue == true) + { + var tmpl = await gameDb.BoardTemplates + .FindAsync(new object[] { rankedRules.BoardTemplateId.Value }, ct); + if (tmpl is not null) + { + var tilesElem = JsonSerializer.Deserialize(tmpl.TilesJson); + var zonesElem = JsonSerializer.Deserialize(tmpl.StartingZonesJson); + boardTemplateJson = JsonSerializer.Serialize(new + { + width = tmpl.Width, + height = tmpl.Height, + tiles = tilesElem, + startingZones = zonesElem, + }); + } + } + // Create a game session. var session = new GameSession { @@ -143,6 +164,7 @@ internal sealed class MatchmakerService : BackgroundService rankedRules.WinnerOpReward, rankedRules.LoserOpReward, rankedRules.RankDiffOpMultiplierPct, + BoardTemplateJson = boardTemplateJson, }) : null, };