Implement phase-2 board template engine integration

- Add BoardTemplateJson (nullable string) to GameRules so admin-defined
  board layouts are snapshotted at session creation; in-flight games are
  unaffected by subsequent template edits.
- Introduce BoardTemplateSnapshot + SnapshotTile types in SOR.Game.Grid
  (integer-enum serialisation matching the admin builder).
- BoardShapeGenerator.FromTemplate / FromTemplateJson: build a Board from
  a snapshot, respecting AffinityOverrideable + StartingRandomTilePct.
- GameEngine.Initialize: use FromTemplateJson when BoardTemplateJson is set,
  falling back to algorithmic Generate.
- GameLobbyReadyHandler: load BoardTemplateIdOverride template from DB and
  embed as BoardTemplateJson in the rule snapshot at lobby start.
- MatchmakerService: load BoardTemplateId template from DB and embed via
  JsonElement in the ranked-rule snapshot at match creation.

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-03-27 21:03:05 -04:00
co-authored by Claude Happy
parent 4924f61483
commit 1368083405
6 changed files with 200 additions and 2 deletions
+4 -2
View File
@@ -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)
+8
View File
@@ -62,5 +62,13 @@ public sealed record GameRules
/// <summary>Number of players in this game. 2 = standard 1v1.</summary>
public int PlayerCount { get; init; } = 2;
/// <summary>
/// When non-null, the board is built from this admin-defined template snapshot instead of
/// being generated algorithmically from <see cref="BoardShape"/>.
/// Set at session-creation time from <c>BoardTemplate.TilesJson</c> +
/// <c>StartingZonesJson</c> so that in-flight games are unaffected by template edits.
/// </summary>
public string? BoardTemplateJson { get; init; }
public static readonly GameRules Default = new();
}
@@ -1,5 +1,6 @@
namespace SOR.Game.Grid;
using System.Text.Json;
using SOR.Database.Enums;
/// <summary>
@@ -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 ──────────────────────────────────────────────────
/// <summary>
/// Separate options for template deserialisation: no JsonStringEnumConverter —
/// the admin builder serialises affinities as integers.
/// </summary>
private static readonly JsonSerializerOptions _templateJson =
new(JsonSerializerDefaults.Web);
/// <summary>
/// Build a <see cref="Board"/> from a <see cref="BoardTemplateSnapshot"/>.
///
/// All Width × Height cells are present in the result; tiles absent from
/// <paramref name="snapshot"/>.<see cref="BoardTemplateSnapshot.Tiles"/> default to Void+Void.
///
/// When <paramref name="startingRandomTilePct"/> is &gt; 0, tiles whose
/// <see cref="SnapshotTile.AffinityOverrideable"/> flag is set are independently
/// randomised with that probability (matching the normal <see cref="Board.Create"/> logic).
/// Locked tiles (<c>AffinityOverrideable = false</c>) always keep their designed affinity.
/// </summary>
public static Board FromTemplate(
BoardTemplateSnapshot snapshot,
int playerCount,
int startingRandomTilePct = 0)
{
var pct = Math.Clamp(startingRandomTilePct, 0, 100);
var tiles = new Dictionary<string, Tile>(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<int, HashSet<Coord>>();
if (snapshot.StartingZones.TryGetValue(playerCount, out var seatMap))
{
foreach (var (seat, coords) in seatMap)
{
var set = new HashSet<Coord>(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,
};
}
/// <summary>
/// Deserialise a JSON snapshot string and delegate to
/// <see cref="FromTemplate(BoardTemplateSnapshot, int, int)"/>.
/// </summary>
public static Board FromTemplateJson(string json, int playerCount, int startingRandomTilePct = 0)
{
var snapshot = JsonSerializer.Deserialize<BoardTemplateSnapshot>(json, _templateJson)
?? throw new InvalidOperationException("Failed to deserialise BoardTemplateSnapshot.");
return FromTemplate(snapshot, playerCount, startingRandomTilePct);
}
// ── Helpers ───────────────────────────────────────────────────────────────
private static HashSet<Coord> CoordsInRect(int x0, int y0, int x1, int y1, int w, int h)
@@ -0,0 +1,34 @@
namespace SOR.Game.Grid;
using System.Text.Json.Serialization;
using SOR.Database.Enums;
/// <summary>
/// Lightweight snapshot of a <c>BoardTemplate</c> DB entity embedded in
/// <see cref="GameRules.BoardTemplateJson"/> at session-creation time.
///
/// Integer enum values are used throughout (matching the admin builder serialisation)
/// so <c>System.Text.Json</c> default options (no JsonStringEnumConverter) are sufficient.
/// </summary>
public sealed class BoardTemplateSnapshot
{
public int Width { get; set; }
public int Height { get; set; }
public List<SnapshotTile> Tiles { get; set; } = new();
/// <summary>
/// playerCount → (seatIndex → list of "x,y" coordinate strings).
/// Keys are integers serialised as JSON strings by STJ.
/// </summary>
public Dictionary<int, Dictionary<int, List<string>>> 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; }
}
@@ -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<List<SnapshotTile>>(tmpl.TilesJson, tileOpts) ?? new();
var zones = JsonSerializer.Deserialize<Dictionary<int, Dictionary<int, List<string>>>>(
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,
};
@@ -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<JsonElement>(tmpl.TilesJson);
var zonesElem = JsonSerializer.Deserialize<JsonElement>(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,
};