Files
sor/Server/src/SOR.Admin/Components/Pages/Game/BoardTemplateBuilderPage.razor
T
0572aea4d2 Extend board template builder with hex SVG canvas + filter client by grid type
- Admin builder: SVG hex canvas renders when GridType=Hexagon (pointy-top hexagons, correct axial layout); square CSS grid otherwise
- Admin builder: ApplyHexSides / OnGridTypeChanged handle dimension/tile pruning; canvas header shows N/diameter for hex
- BoardTemplateDto now includes GridType and HexSides so clients can filter
- rules_editor_dialog: Board Width/Height/Shape hidden when hex selected; Hex Sides hidden when square; template picker filtered to matching grid type with live toggle

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>
2026-04-01 21:22:07 -04:00

934 lines
44 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
@page "/game/board-templates/new"
@page "/game/board-templates/{Id:guid}"
@using SOR.Database.Entities.Game
@using System.Text.Json.Serialization
@inject GameDbContext GameDb
@inject NavigationManager Nav
<PageTitle>@(_isNew ? "New Board Template" : _template.Name) — SOR Admin</PageTitle>
@if (_loading)
{
<div class="d-flex align-items-center gap-2 text-muted py-4">
<div class="spinner-border spinner-border-sm"></div>Loading…
</div>
}
else
{
<nav aria-label="breadcrumb" class="mb-2">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="/game/board-templates">Board Templates</a></li>
<li class="breadcrumb-item active">@(_isNew ? "New" : _template.Name)</li>
</ol>
</nav>
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="h3 mb-0">@(_isNew ? "New Board Template" : _template.Name)</h1>
<button class="btn btn-success" @onclick="SaveAsync" disabled="@_saving">
@if (_saving) { <span class="spinner-border spinner-border-sm me-1"></span> }
Save
</button>
</div>
@if (_saved)
{
<div class="alert alert-success alert-dismissible">
Saved successfully.
<button type="button" class="btn-close" @onclick="() => _saved = false"></button>
</div>
}
@if (_error is not null)
{
<div class="alert alert-danger alert-dismissible">
@_error
<button type="button" class="btn-close" @onclick="() => _error = null"></button>
</div>
}
<!-- Metadata + Board Size ──────────────────────────────────────────────── -->
<div class="row g-4 mb-4">
<div class="col-lg-6">
<div class="card h-100">
<div class="card-header">Template Details</div>
<div class="card-body">
<div class="mb-3">
<label class="form-label fw-semibold">Name</label>
<input type="text" class="form-control" @bind="_template.Name"
placeholder="e.g. Standard 9×9" />
</div>
<div class="row g-3 mb-3">
<div class="col">
<label class="form-label fw-semibold">Min Players</label>
<input type="number" class="form-control" min="1" max="10"
@bind="_template.MinPlayers" />
</div>
<div class="col">
<label class="form-label fw-semibold">Max Players</label>
<input type="number" class="form-control" min="1" max="10"
@bind="_template.MaxPlayers" />
</div>
</div>
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" role="switch" id="isEnabled"
@bind="_template.IsEnabled" />
<label class="form-check-label" for="isEnabled">Enabled</label>
</div>
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" role="switch" id="isRanked"
@bind="_template.IsAvailableForRanked" />
<label class="form-check-label" for="isRanked">Available for Ranked</label>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" role="switch" id="isCustom"
@bind="_template.IsAvailableForCustom" />
<label class="form-check-label" for="isCustom">Available for Custom Lobbies</label>
</div>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card h-100">
<div class="card-header">Grid Type</div>
<div class="card-body">
<div class="mb-3">
<label class="form-label fw-semibold">Type</label>
<select class="form-select" @bind="_template.GridType" @bind:after="OnGridTypeChanged">
<option value="Square">Square</option>
<option value="Hexagon">Hexagon</option>
</select>
</div>
@if (_template.GridType == "Hexagon")
{
<div class="mb-3">
<label class="form-label fw-semibold">Hex Sides (N)</label>
<input type="number" class="form-control" min="3" max="10"
@bind="_pendingHexSides" />
<div class="form-text">Diameter = 2N−1. Tiles: 3N²−3N+1.</div>
</div>
<button class="btn btn-outline-secondary btn-sm w-100" @onclick="ApplyHexSides">
Apply Hex Sides
</button>
}
else
{
<div class="mb-3">
<label class="form-label fw-semibold">Width (columns)</label>
<input type="number" class="form-control" min="1" max="32"
@bind="_pendingWidth" />
</div>
<div class="mb-3">
<label class="form-label fw-semibold">Height (rows)</label>
<input type="number" class="form-control" min="1" max="32"
@bind="_pendingHeight" />
</div>
<button class="btn btn-outline-secondary btn-sm w-100" @onclick="ApplySize">
Apply Size
</button>
<div class="form-text mt-1">Tiles inside the new bounds are preserved.</div>
}
</div>
</div>
</div>
</div>
<!-- Toolbar + Canvas ───────────────────────────────────────────────────── -->
<div class="row g-3">
<!-- Toolbar -->
<div class="col-md-3 col-xl-2">
<div class="card">
<div class="card-header">Tools</div>
<div class="card-body p-2">
<!-- Mode toggle -->
<div class="btn-group w-100 mb-3" role="group">
<input type="radio" class="btn-check" name="editMode" id="modePaint"
checked="@(_editMode == "Paint")"
@onchange='() => _editMode = "Paint"' />
<label class="btn btn-outline-primary btn-sm" for="modePaint">
<i class="bi bi-brush me-1"></i>Paint
</label>
<input type="radio" class="btn-check" name="editMode" id="modeZone"
checked="@(_editMode == "ZoneEdit")"
@onchange='() => _editMode = "ZoneEdit"' />
<label class="btn btn-outline-success btn-sm" for="modeZone">
<i class="bi bi-grid-fill me-1"></i>Zones
</label>
</div>
@if (_editMode == "Paint")
{
<!-- Active paint -->
<div class="mb-2 d-flex align-items-center gap-2">
@{ var activeColor = AffinityColor.GetValueOrDefault(
ComputeDisplayAffinity(PaintMap[_paintAffinity].B1, PaintMap[_paintAffinity].B2),
"#6c757d"); }
@if (_paintEmpty)
{
<div style="width:20px;height:20px;border-radius:3px;background:repeating-linear-gradient(45deg,#444 0px,#444 5px,#222 5px,#222 10px);border:1px solid rgba(0,0,0,0.25)"></div>
<span class="small fw-semibold">Empty</span>
}
else
{
<div style="width:20px;height:20px;border-radius:3px;background:@activeColor;border:1px solid rgba(0,0,0,0.25)"></div>
<span class="small fw-semibold">@_paintAffinity</span>
}
</div>
<!-- Empty swatch (removes tile from board entirely) -->
<div style="height:24px;background:repeating-linear-gradient(45deg,#444 0px,#444 5px,#222 5px,#222 10px);
cursor:pointer;border-radius:3px;margin-bottom:4px;
border:@(_paintEmpty ? "2px solid #fff" : "1px solid rgba(0,0,0,0.15)");
box-shadow:@(_paintEmpty ? "0 0 0 1px #333" : "none");
display:flex;align-items:center;justify-content:center;"
title="Empty — removes this cell from the board"
@onclick="() => _paintEmpty = true">
<span style="font-size:9px;color:#aaa;user-select:none;pointer-events:none;">Empty</span>
</div>
<!-- Affinity palette -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:3px;">
@foreach (var aff in PaletteAffinities)
{
var a = aff;
var swatchColor = AffinityColor.GetValueOrDefault(a, "#6c757d");
var isSelected = !_paintEmpty && _paintAffinity == a;
<div style="height:24px;background:@swatchColor;cursor:pointer;border-radius:3px;
border:@(isSelected ? "2px solid #fff" : "1px solid rgba(0,0,0,0.15)");
box-shadow:@(isSelected ? "0 0 0 1px #333" : "none");"
title="@a"
@onclick="() => { _paintEmpty = false; _paintAffinity = a; }">
</div>
}
</div>
}
else
{
<!-- Zone edit controls -->
<div class="mb-2">
<label class="form-label fw-semibold small mb-1">Player Count</label>
<select class="form-select form-select-sm" @bind="_zonePlayerCount">
@for (int pc = Math.Max(2, _template.MinPlayers); pc <= Math.Max(_template.MinPlayers, _template.MaxPlayers); pc++)
{
var p = pc;
<option value="@p">@p players</option>
}
</select>
</div>
<div class="mb-2">
<label class="form-label fw-semibold small mb-1">Paint Seat</label>
<select class="form-select form-select-sm" @bind="_zoneSeat">
<option value="-1">✕ Erase</option>
@for (int s = 0; s < _zonePlayerCount; s++)
{
var seat = s;
<option value="@seat">Seat @seat</option>
}
</select>
</div>
@if (_zoneSeat >= 0)
{
<div class="d-flex align-items-center gap-2 mb-2">
<div style="width:20px;height:20px;border-radius:3px;background:@ZoneColors[_zoneSeat % ZoneColors.Length];border:1px solid rgba(0,0,0,0.25)"></div>
<span class="small fw-semibold">Seat @_zoneSeat</span>
</div>
}
else
{
<div class="d-flex align-items-center gap-2 mb-2">
<div style="width:20px;height:20px;border-radius:3px;background:#6c757d;border:1px solid rgba(0,0,0,0.25)"></div>
<span class="small text-muted">Erasing zones</span>
</div>
}
<hr class="my-2" />
<div class="small fw-semibold text-muted mb-1">Coverage:</div>
@for (int s = 0; s < _zonePlayerCount; s++)
{
var seat = s;
var cnt = GetSeatTileCount(_zonePlayerCount, seat);
<div class="d-flex align-items-center gap-2 mb-1">
<div style="width:12px;height:12px;border-radius:2px;background:@ZoneColors[seat % ZoneColors.Length]"></div>
<span class="small">Seat @seat: @cnt tile@(cnt == 1 ? "" : "s")</span>
</div>
}
}
</div>
</div>
</div>
<!-- Canvas -->
<div class="col-md-9 col-xl-10">
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
@if (_template.GridType == "Hexagon")
{
int _hn = _template.HexSides > 0 ? _template.HexSides : _pendingHexSides;
<span>Canvas <span class="text-muted small">N=@_hn hex (@(2*_hn-1)×@(2*_hn-1))</span></span>
}
else
{
<span>Canvas <span class="text-muted small">@_template.Width × @_template.Height</span></span>
}
<span class="text-muted small d-none d-md-inline">
Click / drag to paint &nbsp;·&nbsp; Double-click for tile flags
</span>
</div>
<div class="card-body p-2" style="overflow:auto;max-height:65vh;">
@if (_template.GridType == "Hexagon")
{
const double HexR = 16.0;
const double HexPad = 12.0;
int hexN = _template.HexSides > 0 ? _template.HexSides : Math.Max(3, _pendingHexSides);
int hexDim = 2 * hexN - 1;
double svgW = HexR * Math.Sqrt(3) * (hexDim - 1) + 2 * HexR + 2 * HexPad;
double svgH = HexR * 1.5 * (hexDim - 1) + 2 * HexR + 2 * HexPad;
<svg width="@((int)Math.Ceiling(svgW))" height="@((int)Math.Ceiling(svgH))"
style="user-select:none;cursor:crosshair;display:block;"
@onmouseup="() => _mouseDown = false"
@onmouseleave="() => _mouseDown = false">
@for (int row = 0; row < hexDim; row++)
{
@for (int col = 0; col < hexDim; col++)
{
if (!IsHexInBounds(col, row, hexN)) continue;
var hr = row; var hc = col;
double cx = HexCellX(hc, hr, hexN, HexR, HexPad);
double cy = HexCellY(hr, hexN, HexR, HexPad);
<polygon points="@HexPolygonPoints(cx, cy, HexR - 1.0)"
fill="@GetCellColor(hc, hr)"
stroke="rgba(0,0,0,0.25)" stroke-width="1"
title="@GetCellTooltip(hc, hr)"
@onmousedown="@(() => OnCellMouseDown(hc, hr))"
@onmouseenter="@(() => OnCellMouseEnter(hc, hr))"
@ondblclick="@(() => OpenTileModal(hc, hr))">
</polygon>
}
}
</svg>
}
else
{
<div style="display:grid;grid-template-columns:repeat(@_template.Width, 28px);gap:1px;width:fit-content;user-select:none;cursor:crosshair;"
@onmouseup="() => _mouseDown = false"
@onmouseleave="() => _mouseDown = false">
@for (int row = 0; row < _template.Height; row++)
{
@for (int col = 0; col < _template.Width; col++)
{
var r = row; var c = col;
<div style="width:28px;height:28px;background:@GetCellColor(c, r);border:1px solid rgba(0,0,0,0.12);"
title="@GetCellTooltip(c, r)"
@onmousedown="@(() => OnCellMouseDown(c, r))"
@onmouseenter="@(() => OnCellMouseEnter(c, r))"
@ondblclick="@(() => OpenTileModal(c, r))">
</div>
}
}
</div>
}
</div>
</div>
</div>
</div>
}
<!-- Tile Flags Modal ───────────────────────────────────────────────────────── -->
@if (_showModal)
{
<div class="modal show d-block" tabindex="-1"
style="background:rgba(0,0,0,0.5);" @onclick="CloseModal">
<div class="modal-dialog" @onclick:stopPropagation="true">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Tile (@_modalX, @_modalY)</h5>
<button type="button" class="btn-close" @onclick="CloseModal"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="form-label fw-semibold">Base 1 (primary slot)</label>
<select class="form-select" @bind="_modalBase1Int">
@foreach (var a in Enum.GetValues<Affinity>())
{
<option value="@((int)a)">@a</option>
}
</select>
</div>
<div class="mb-3">
<label class="form-label fw-semibold">Base 2 (secondary slot)</label>
<select class="form-select" @bind="_modalBase2Int">
@foreach (var a in Enum.GetValues<Affinity>())
{
<option value="@((int)a)">@a</option>
}
</select>
</div>
<div class="mb-3 d-flex align-items-center gap-2">
@{ var previewAff = ComputeDisplayAffinity((Affinity)_modalBase1Int, (Affinity)_modalBase2Int);
var previewColor = AffinityColor.GetValueOrDefault(previewAff, "#6c757d"); }
<div style="width:24px;height:24px;border-radius:4px;background:@previewColor;border:1px solid rgba(0,0,0,0.2)"></div>
<span class="small text-muted">Preview: <strong>@previewAff</strong></span>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="modalAo"
@bind="_modalOverrideable" />
<label class="form-check-label" for="modalAo">Affinity Overrideable</label>
<div class="form-text">
When StartingRandomTilePct &gt; 0, only overrideable tiles may have their
affinity randomized at game start. Locked tiles stay fixed as designed.
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" @onclick="CloseModal">Cancel</button>
<button class="btn btn-primary" @onclick="ApplyModal">Apply</button>
</div>
</div>
</div>
</div>
}
@code {
[Parameter] public Guid Id { get; set; }
private bool _isNew => Id == default;
// ── Template + in-memory state ────────────────────────────────────────────
private BoardTemplate _template = new();
private int _pendingWidth = 8;
private int _pendingHeight = 8;
private int _pendingHexSides = 5;
// Only non-default tiles stored; key = "x,y"
private Dictionary<string, TileDefinition> _tiles = new();
// zones[playerCount][seatIndex] = set of "x,y" coordinate strings
private Dictionary<int, Dictionary<int, HashSet<string>>> _zones = new();
// ── Edit state ────────────────────────────────────────────────────────────
private string _editMode = "Paint";
private Affinity _paintAffinity = Affinity.PureVoid;
private bool _paintEmpty = false;
private int _zonePlayerCount = 2;
private int _zoneSeat = 0;
private bool _mouseDown;
private (int x, int y) _lastPainted = (-1, -1);
// ── Modal state ───────────────────────────────────────────────────────────
private bool _showModal;
private int _modalX, _modalY;
private int _modalBase1Int;
private int _modalBase2Int;
private bool _modalOverrideable;
// ── UI state ──────────────────────────────────────────────────────────────
private bool _loading = true;
private bool _saving;
private bool _saved;
private string? _error;
// ── Lifecycle ─────────────────────────────────────────────────────────────
protected override async Task OnParametersSetAsync()
{
_loading = true;
_error = null;
_tiles.Clear();
_zones.Clear();
if (_isNew)
{
_template = new BoardTemplate { CreatedAt = DateTimeOffset.UtcNow, UpdatedAt = DateTimeOffset.UtcNow };
_pendingWidth = _template.Width;
_pendingHeight = _template.Height;
_pendingHexSides = 5;
}
else
{
var t = await GameDb.BoardTemplates.FindAsync(Id);
if (t is null)
{
_error = "Template not found.";
_loading = false;
return;
}
_template = t;
_pendingWidth = t.Width;
_pendingHeight = t.Height;
_pendingHexSides = t.HexSides > 0 ? t.HexSides : 5;
DeserializeTiles(t.TilesJson);
DeserializeZones(t.StartingZonesJson);
}
_zonePlayerCount = Math.Clamp(
_zonePlayerCount,
Math.Max(2, _template.MinPlayers),
Math.Max(_template.MinPlayers, _template.MaxPlayers));
_loading = false;
}
// ── Save ──────────────────────────────────────────────────────────────────
private async Task SaveAsync()
{
_saving = true;
_error = null;
try
{
_template.TilesJson = SerializeTiles();
_template.StartingZonesJson = SerializeZones();
_template.UpdatedAt = DateTimeOffset.UtcNow;
if (_isNew)
{
_template.CreatedAt = DateTimeOffset.UtcNow;
GameDb.BoardTemplates.Add(_template);
}
await GameDb.SaveChangesAsync();
_saved = true;
if (_isNew)
Nav.NavigateTo($"/game/board-templates/{_template.Id}");
}
catch (Exception ex)
{
_error = ex.Message;
}
finally
{
_saving = false;
}
}
// ── Board sizing ──────────────────────────────────────────────────────────
private void ApplySize()
{
var w = Math.Clamp(_pendingWidth, 1, 32);
var h = Math.Clamp(_pendingHeight, 1, 32);
_template.Width = w;
_template.Height = h;
var toRemoveTiles = _tiles.Keys
.Where(k => { var p = k.Split(','); return int.Parse(p[0]) >= w || int.Parse(p[1]) >= h; })
.ToList();
foreach (var k in toRemoveTiles) _tiles.Remove(k);
foreach (var seatMap in _zones.Values)
foreach (var tileSet in seatMap.Values)
tileSet.RemoveWhere(k =>
{
var p = k.Split(',');
return int.Parse(p[0]) >= w || int.Parse(p[1]) >= h;
});
}
private void ApplyHexSides()
{
var n = Math.Clamp(_pendingHexSides, 3, 10);
_pendingHexSides = n;
_template.HexSides = n;
int dim = 2 * n - 1;
_template.Width = dim;
_template.Height = dim;
var toRemoveTiles = _tiles.Keys
.Where(k => { var p = k.Split(','); return !IsHexInBounds(int.Parse(p[0]), int.Parse(p[1]), n); })
.ToList();
foreach (var k in toRemoveTiles) _tiles.Remove(k);
foreach (var seatMap in _zones.Values)
foreach (var tileSet in seatMap.Values)
tileSet.RemoveWhere(k =>
{
var p = k.Split(',');
return !IsHexInBounds(int.Parse(p[0]), int.Parse(p[1]), n);
});
}
private void OnGridTypeChanged()
{
_tiles.Clear();
_zones.Clear();
if (_template.GridType == "Hexagon")
{
_template.HexSides = _pendingHexSides;
int dim = 2 * _pendingHexSides - 1;
_template.Width = dim;
_template.Height = dim;
}
else
{
_template.HexSides = 0;
_template.Width = _pendingWidth;
_template.Height = _pendingHeight;
}
}
// ── Hex geometry helpers ──────────────────────────────────────────────────
private static bool IsHexInBounds(int x, int y, int N)
{
int q = x - (N - 1);
int r = y - (N - 1);
int s = -q - r;
return Math.Max(Math.Abs(q), Math.Max(Math.Abs(r), Math.Abs(s))) <= N - 1;
}
private static double HexCellX(int x, int y, int N, double R, double pad)
{
int q = x - (N - 1);
int r = y - (N - 1);
double offsetX = pad + R * Math.Sqrt(3) * (N - 1);
return offsetX + R * Math.Sqrt(3) * q + R * Math.Sqrt(3) / 2.0 * r;
}
private static double HexCellY(int y, int N, double R, double pad)
{
int r = y - (N - 1);
return pad + R * 1.5 * (N - 1) + R * 1.5 * r;
}
private static string HexPolygonPoints(double cx, double cy, double R)
{
var sb = new System.Text.StringBuilder();
for (int i = 0; i < 6; i++)
{
double angle = Math.PI / 180.0 * (60.0 * i - 30.0); // pointy-top
if (i > 0) sb.Append(' ');
sb.Append(FormattableString.Invariant(
$"{cx + R * Math.Cos(angle):F1},{cy + R * Math.Sin(angle):F1}"));
}
return sb.ToString();
}
// ── Cell interactions ─────────────────────────────────────────────────────
private void OnCellMouseDown(int x, int y)
{
_mouseDown = true;
_lastPainted = (x, y);
HandleCell(x, y);
}
private void OnCellMouseEnter(int x, int y)
{
if (!_mouseDown) return;
if (_lastPainted == (x, y)) return;
_lastPainted = (x, y);
HandleCell(x, y);
}
private void HandleCell(int x, int y)
{
if (_editMode == "Paint") PaintCell(x, y);
else ZoneCell(x, y);
}
private void PaintCell(int x, int y)
{
var key = TileKey(x, y);
if (_paintEmpty)
{
// Mark cell as absent — no tile exists at this position.
var tile = GetOrCreateTile(x, y);
tile.IsAbsent = true;
tile.Base1 = Affinity.Void;
tile.Base2 = Affinity.Void;
tile.AffinityOverrideable = false;
return;
}
if (!PaintMap.TryGetValue(_paintAffinity, out var bases)) return;
if (bases.B1 == Affinity.Void && bases.B2 == Affinity.Void)
{
_tiles.Remove(key); // reverts to a valid void tile (also clears absent if present)
}
else
{
var tile = GetOrCreateTile(x, y);
tile.IsAbsent = false; // painting over an absent cell restores it
tile.Base1 = bases.B1;
tile.Base2 = bases.B2;
}
}
private void ZoneCell(int x, int y)
{
// Don't assign zones to absent (no-tile) cells.
if (_tiles.TryGetValue(TileKey(x, y), out var td) && td.IsAbsent) return;
var key = TileKey(x, y);
if (!_zones.ContainsKey(_zonePlayerCount))
_zones[_zonePlayerCount] = new Dictionary<int, HashSet<string>>();
var seatMap = _zones[_zonePlayerCount];
// Remove cell from all seats first (ensures each cell belongs to at most one seat)
foreach (var kv in seatMap) kv.Value.Remove(key);
if (_zoneSeat >= 0)
{
if (!seatMap.ContainsKey(_zoneSeat)) seatMap[_zoneSeat] = new HashSet<string>();
seatMap[_zoneSeat].Add(key);
}
}
// ── Modal ─────────────────────────────────────────────────────────────────
private void OpenTileModal(int x, int y)
{
_modalX = x; _modalY = y;
var tile = GetOrCreateTile(x, y);
_modalBase1Int = (int)tile.Base1;
_modalBase2Int = (int)tile.Base2;
_modalOverrideable = tile.AffinityOverrideable;
_showModal = true;
}
private void ApplyModal()
{
var tile = GetOrCreateTile(_modalX, _modalY);
tile.IsAbsent = false; // applying affinity always restores the cell
tile.Base1 = (Affinity)_modalBase1Int;
tile.Base2 = (Affinity)_modalBase2Int;
tile.AffinityOverrideable = _modalOverrideable;
_showModal = false;
}
private void CloseModal() => _showModal = false;
// ── Color helpers ─────────────────────────────────────────────────────────
private string GetCellColor(int x, int y)
{
var key = TileKey(x, y);
_tiles.TryGetValue(key, out var tile);
// Absent cells always render as empty space, regardless of edit mode.
if (tile is { IsAbsent: true })
return "repeating-linear-gradient(45deg,#444 0px,#444 5px,#222 5px,#222 10px)";
if (_editMode == "ZoneEdit" && _zones.TryGetValue(_zonePlayerCount, out var seatMap))
{
for (int s = 0; s < _zonePlayerCount; s++)
if (seatMap.TryGetValue(s, out var tileSet) && tileSet.Contains(key))
return ZoneColors[s % ZoneColors.Length];
}
if (tile is null)
return AffinityColor[Affinity.PureVoid];
var aff = ComputeDisplayAffinity(tile.Base1, tile.Base2);
return AffinityColor.GetValueOrDefault(aff, "#6c757d");
}
private string GetCellTooltip(int x, int y)
{
var key = TileKey(x, y);
if (!_tiles.TryGetValue(key, out var tile)) return $"({x},{y}) Void";
if (tile.IsAbsent) return $"({x},{y}) Empty (no tile)";
var aff = ComputeDisplayAffinity(tile.Base1, tile.Base2);
var ao = tile.AffinityOverrideable ? " [overrideable]" : "";
return $"({x},{y}) {aff} ({tile.Base1}+{tile.Base2}){ao}";
}
private int GetSeatTileCount(int playerCount, int seat) =>
_zones.TryGetValue(playerCount, out var sm) && sm.TryGetValue(seat, out var ts)
? ts.Count : 0;
// ── Tile helpers ──────────────────────────────────────────────────────────
private static string TileKey(int x, int y) => $"{x},{y}";
private TileDefinition GetOrCreateTile(int x, int y)
{
var key = TileKey(x, y);
if (!_tiles.TryGetValue(key, out var tile))
{
tile = new TileDefinition { X = x, Y = y };
_tiles[key] = tile;
}
return tile;
}
// ── Serialization ─────────────────────────────────────────────────────────
private string SerializeTiles()
{
var nonDefault = _tiles.Values
.Where(t => t.IsAbsent || t.Base1 != Affinity.Void || t.Base2 != Affinity.Void || t.AffinityOverrideable)
.ToList();
return JsonSerializer.Serialize(nonDefault);
}
private void DeserializeTiles(string json)
{
if (string.IsNullOrWhiteSpace(json) || json == "[]") return;
var tiles = JsonSerializer.Deserialize<List<TileDefinition>>(json);
if (tiles is null) return;
_tiles = tiles.ToDictionary(t => TileKey(t.X, t.Y));
}
private string SerializeZones()
{
var dict = _zones.ToDictionary(
o => o.Key,
o => o.Value.ToDictionary(i => i.Key, i => i.Value.ToList()));
return JsonSerializer.Serialize(dict);
}
private void DeserializeZones(string json)
{
if (string.IsNullOrWhiteSpace(json) || json == "{}") return;
var dict = JsonSerializer.Deserialize<Dictionary<int, Dictionary<int, List<string>>>>(json);
if (dict is null) return;
_zones = dict.ToDictionary(
o => o.Key,
o => o.Value.ToDictionary(i => i.Key, i => new HashSet<string>(i.Value)));
}
// ── Affinity display ──────────────────────────────────────────────────────
/// <summary>
/// Mirrors <c>AffinitySystem.Resolve</c> exactly.
/// Base1 = older slot (first pushed), Base2 = newer slot.
/// Gateway tiles have the basic affinity in Base1 and Void in Base2.
/// Single-slot basics are stored with Void in Base1 (e.g. Lake = (Void, Lake)).
/// </summary>
private static Affinity ComputeDisplayAffinity(Affinity b1, Affinity b2)
=> (b1, b2) switch
{
// Void + Void
(Affinity.Void, Affinity.Void) => Affinity.PureVoid,
// Void + basic → tile reads as that basic affinity (Base2 is the active slot)
(Affinity.Void, Affinity.Lake) => Affinity.Lake,
(Affinity.Void, Affinity.Hill) => Affinity.Hill,
(Affinity.Void, Affinity.Forest) => Affinity.Forest,
(Affinity.Void, Affinity.Field) => Affinity.Field,
(Affinity.Void, Affinity.Aether) => Affinity.UnstableAether,
// Gateway: basic in Base1, Void in Base2 (directional)
(Affinity.Lake, Affinity.Void) => Affinity.GatewayLake,
(Affinity.Hill, Affinity.Void) => Affinity.GatewayHill,
(Affinity.Forest, Affinity.Void) => Affinity.GatewayForest,
(Affinity.Field, Affinity.Void) => Affinity.GatewayField,
// Aether combinations
(Affinity.Aether, Affinity.Aether) => Affinity.PerfectAether,
(Affinity.Aether, _) => Affinity.UnstableAether,
(_, Affinity.Aether) => Affinity.UnstableAether,
// Symmetric doubles
(Affinity.Lake, Affinity.Lake) => Affinity.Ocean,
(Affinity.Hill, Affinity.Hill) => Affinity.Mountain,
(Affinity.Field, Affinity.Field) => Affinity.Plains,
(Affinity.Forest, Affinity.Forest) => Affinity.Jungle,
// Asymmetric pairs — commutative
(Affinity.Lake, Affinity.Hill) or (Affinity.Hill, Affinity.Lake) => Affinity.Island,
(Affinity.Lake, Affinity.Field) or (Affinity.Field, Affinity.Lake) => Affinity.Marsh,
(Affinity.Lake, Affinity.Forest) or (Affinity.Forest, Affinity.Lake) => Affinity.Swamp,
(Affinity.Hill, Affinity.Field) or (Affinity.Field, Affinity.Hill) => Affinity.Steppe,
(Affinity.Hill, Affinity.Forest) or (Affinity.Forest, Affinity.Hill) => Affinity.Fort,
(Affinity.Field, Affinity.Forest) or (Affinity.Forest, Affinity.Field) => Affinity.Grove,
_ => Affinity.PureVoid,
};
// ── Static data ───────────────────────────────────────────────────────────
private static readonly Dictionary<Affinity, string> AffinityColor = new()
{
[Affinity.Void] = "#495057",
[Affinity.Aether] = "#9b59b6",
[Affinity.Lake] = "#3498db",
[Affinity.Hill] = "#d4a843",
[Affinity.Forest] = "#27ae60",
[Affinity.Field] = "#f39c12",
[Affinity.Ocean] = "#1565c0",
[Affinity.Island] = "#5dade2",
[Affinity.Marsh] = "#85929e",
[Affinity.Swamp] = "#1a5276",
[Affinity.Mountain] = "#546e7a",
[Affinity.Steppe] = "#d5a229",
[Affinity.Fort] = "#6d4c41",
[Affinity.Plains] = "#f4d03f",
[Affinity.Grove] = "#82e0aa",
[Affinity.Jungle] = "#1b5e20",
[Affinity.UnstableAether] = "#8e44ad",
[Affinity.PerfectAether] = "#d7bde2",
[Affinity.PureVoid] = "#2c3038",
[Affinity.GatewayLake] = "#aed6f1",
[Affinity.GatewayHill] = "#fad7a0",
[Affinity.GatewayForest] = "#a9dfbf",
[Affinity.GatewayField] = "#fde8d8",
};
private static readonly string[] ZoneColors =
{
"#e74c3c", "#3498db", "#27ae60", "#f1c40f",
"#9b59b6", "#e67e22", "#1abc9c", "#e91e63",
"#00bcd4", "#795548"
};
// Palette display order: void / basics / double non-basics / mixed non-basics / aether specials / gateways
private static readonly IReadOnlyList<Affinity> PaletteAffinities = new[]
{
Affinity.PureVoid,
Affinity.Aether,
Affinity.Lake, Affinity.Hill, Affinity.Forest, Affinity.Field,
Affinity.Ocean, Affinity.Mountain, Affinity.Jungle, Affinity.Plains,
Affinity.Island, Affinity.Swamp, Affinity.Marsh,
Affinity.Fort, Affinity.Steppe, Affinity.Grove,
Affinity.UnstableAether, Affinity.PerfectAether,
Affinity.GatewayLake, Affinity.GatewayHill, Affinity.GatewayForest, Affinity.GatewayField,
};
// Maps each palette affinity to the (Base1, Base2) pair that AffinitySystem.Resolve
// will decode back to that same affinity. Matches AffinitySystem.Decompose exactly:
// Basics: (Void, Basic) — Void is the "empty" first slot.
// Gateways: (Basic, Void) — Basic in slot 1, Void in slot 2 (directional).
// Aether / UnstableAether both use (Void, Aether); both resolve to UnstableAether.
private static readonly Dictionary<Affinity, (Affinity B1, Affinity B2)> PaintMap = new()
{
[Affinity.PureVoid] = (Affinity.Void, Affinity.Void),
[Affinity.Aether] = (Affinity.Void, Affinity.Aether), // resolves to UnstableAether
[Affinity.Lake] = (Affinity.Void, Affinity.Lake),
[Affinity.Hill] = (Affinity.Void, Affinity.Hill),
[Affinity.Forest] = (Affinity.Void, Affinity.Forest),
[Affinity.Field] = (Affinity.Void, Affinity.Field),
[Affinity.Ocean] = (Affinity.Lake, Affinity.Lake),
[Affinity.Island] = (Affinity.Lake, Affinity.Hill),
[Affinity.Marsh] = (Affinity.Lake, Affinity.Field),
[Affinity.Swamp] = (Affinity.Lake, Affinity.Forest),
[Affinity.Mountain] = (Affinity.Hill, Affinity.Hill),
[Affinity.Steppe] = (Affinity.Hill, Affinity.Field),
[Affinity.Fort] = (Affinity.Hill, Affinity.Forest),
[Affinity.Plains] = (Affinity.Field, Affinity.Field),
[Affinity.Grove] = (Affinity.Field, Affinity.Forest),
[Affinity.Jungle] = (Affinity.Forest, Affinity.Forest),
[Affinity.UnstableAether] = (Affinity.Void, Affinity.Aether), // canonical per Decompose
[Affinity.PerfectAether] = (Affinity.Aether, Affinity.Aether),
[Affinity.GatewayLake] = (Affinity.Lake, Affinity.Void),
[Affinity.GatewayHill] = (Affinity.Hill, Affinity.Void),
[Affinity.GatewayForest] = (Affinity.Forest, Affinity.Void),
[Affinity.GatewayField] = (Affinity.Field, Affinity.Void),
};
// ── TileDefinition ────────────────────────────────────────────────────────
private sealed class TileDefinition
{
[JsonPropertyName("x")] public int X { get; set; }
[JsonPropertyName("y")] public int Y { get; set; }
[JsonPropertyName("b1")] public Affinity Base1 { get; set; } = Affinity.Void;
[JsonPropertyName("b2")] public Affinity Base2 { get; set; } = Affinity.Void;
[JsonPropertyName("ao")] public bool AffinityOverrideable { get; set; }
[JsonPropertyName("absent")] public bool IsAbsent { get; set; }
}
}