From 80b92b17b9ba023af3d88ee29711b3223415eae6 Mon Sep 17 00:00:00 2001 From: dingo Date: Mon, 20 Apr 2026 20:27:20 -0400 Subject: [PATCH] feat(phase8): complete remaining 3 gaps -- pending types, StackDeck interactive, canvas builder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pending interaction coverage: - Add PendingTilePick model (tile-select pause for effects like CloneSpiritAsToken TargetTile) - Add PendingPlayerPick model (player-select pause for ChannelCardFromZone UnderControlOf: Choice) - Add PendingRevealChoicePick model (reveal-and-order pause for StackDeck interactive path) - Add all three as nullable properties on GameState StackDeckEffect interactive flow: - Replace random-shuffle fallback with chooser-aware branching - Self/Opponent chooser: remove top N from deck, emit PendingRevealChoicePick pause - Random/empty chooser: random shuffle fallback (unchanged) - Add ResumeRevealChoicePick(): restore deck in chooser's ordered indices; unspecified cards placed beneath chosen cards preserving relative order Canvas AbilityBuilder (Phase 4 spec): - Add @inject IJSRuntime + @implements IAsyncDisposable to AbilityBuilder.razor - Add sorAdmin.abilityBuilder JS shim in admin.js: non-passive wheel listener (zoom), pinch-to-zoom via touch distance delta, cleanup on dispose - Canvas mode toggle button in form toolbar ("Visual Canvas") - Full canvas layout: left panel (ability list + node palette), main canvas, right inspector - Dark canvas background (#111827), CSS transform pan+zoom (translate then scale) - SVG bezier edge overlay connecting node flow (Meta→Range/Trigger→Cost→Cond→ActionGroup →Actions→Effects, ActionGroup→SubGroups→their Actions→their Effects) - Node types: Meta (blue), Range (teal), Trigger (purple), Cost (amber), Conditions (yellow), ActionGroup (dark green), Action (green), Effect (red), SubGroup (dark green), SubGroupAction, SubGroupEffect -- each draggable, click-to-select - Inspector panel: inline editing for all node types (type/name/desc, range fields, trigger event, group logic op, action target selector, effect type picker) - AutoLayoutAbility() positions nodes on first focus; SetPos() preserves drag positions - Zoom/pan: toolbar +/- buttons + scroll wheel (via JS) + middle-mouse drag - OnCanvasWheel [JSInvokable] + DisposeAsync cleanup - Form view toggle restores full form; JSON preview always visible Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../Pages/Cards/AbilityBuilder.razor | 836 +++++++++++++++++- Server/src/SOR.Admin/wwwroot/admin.js | 55 ++ .../src/SOR.Game/Abilities/AbilitySystem.cs | 100 ++- .../Abilities/Models/PendingPlayerPick.cs | 30 + .../Models/PendingRevealChoicePick.cs | 39 + .../Abilities/Models/PendingTilePick.cs | 34 + Server/src/SOR.Game/GameState.cs | 21 + 7 files changed, 1099 insertions(+), 16 deletions(-) create mode 100644 Server/src/SOR.Game/Abilities/Models/PendingPlayerPick.cs create mode 100644 Server/src/SOR.Game/Abilities/Models/PendingRevealChoicePick.cs create mode 100644 Server/src/SOR.Game/Abilities/Models/PendingTilePick.cs diff --git a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor b/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor index 058666a..7971649 100644 --- a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor +++ b/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor @@ -1,12 +1,17 @@ @* AbilityBuilder.razor — structured UI for AbilityDefinition[] / Action[] JSON *@ @using Microsoft.AspNetCore.Components.Rendering @using Microsoft.EntityFrameworkCore +@using Microsoft.JSInterop @using SOR.Database.Contexts @using SOR.Database.Entities.Catalog @using SOR.Database.Enums @inject CatalogDbContext CatalogDb +@inject IJSRuntime JS +@implements IAsyncDisposable
+ @if (!_canvasMode) + { @if (_abilities.Count == 0) {

No abilities defined. Click "Add Ability" to start.

@@ -865,14 +870,487 @@ } } -
- - -
+
+ + + +
+ } + + @* ── Canvas mode ──────────────────────────────────────────────────────────── *@ + @if (_canvasMode) + { + + +
+ + + Canvas · @_abilities.Count abilit@(_abilities.Count == 1 ? "y" : "ies") · scroll=zoom · middle-drag=pan +
+ +
+ + @* ── Left panel: ability list + node palette ── *@ +
+
Abilities
+ @for (int cai = 0; cai < _abilities.Count; cai++) + { + int aidx = cai; + var aitem = _abilities[aidx]; +
+ + +
+ } + + + @if (_focusedAbility >= 0 && _focusedAbility < _abilities.Count) + { + var fabpal = _abilities[_focusedAbility]; +
+
Add Node
+ + + + + } +
+ + @* ── Canvas area ── *@ +
+ + @* Canvas toolbar *@ +
+ + + + @((_zoom * 100).ToString("F0"))% +
+ + @* Transform wrapper *@ +
+ + @* SVG edge layer *@ + + @foreach (var (efrom, eto) in GetEdges()) + { + @if (_nodePos.TryGetValue(efrom, out var efp) && _nodePos.TryGetValue(eto, out var etp)) + { + var (efx, efy) = GetOutputPort(efrom); + var (etx, ety) = GetInputPort(eto); + + } + } + + + @* Nodes layer (re-enable pointer-events) *@ +
+ @if (_focusedAbility >= 0 && _focusedAbility < _abilities.Count) + { + var fabi = _abilities[_focusedAbility]; + int fai = _focusedAbility; + + @* Meta *@ + var mk = $"meta-{fai}"; + var mp = _nodePos.GetValueOrDefault(mk, (80.0, 80.0)); +
+
+ @fabi.TypeStr + @(string.IsNullOrEmpty(fabi.Name)?"(unnamed)":fabi.Name) +
+
@fabi.Description
+
+ + @* Range (Active) *@ + @if (fabi.TypeStr == "Active") + { + var rk = $"range-{fai}"; var rp = _nodePos.GetValueOrDefault(rk,(320,80)); +
+
Range
+
+ R @(fabi.RangeMin??1)–@(fabi.RangeMax??1) + @if (fabi.RangeRequiresLos){LOS} + @if (fabi.RangeLinearOnly){Lin} + @if (fabi.UsesPerTurn!=1){
×@fabi.UsesPerTurn/turn
} +
+
+ } + + @* Trigger (Triggered) *@ + @if (fabi.TypeStr == "Triggered") + { + var tk = $"trigger-{fai}"; var tp = _nodePos.GetValueOrDefault(tk,(320,80)); +
+
Trigger
+
@(string.IsNullOrEmpty(fabi.TriggerType)?"(none)":fabi.TriggerType)
+
+ } + + @* Cost *@ + @if (fabi.Costs.Count > 0) + { + var ck = $"cost-{fai}"; var cp = _nodePos.GetValueOrDefault(ck,(560,80)); +
+
+ Cost + @fabi.Costs.Count +
+ @foreach (var ce in fabi.Costs.Take(3)) + { +
@ce.TypeStr @(ce.Amount>0?ce.Amount:"")
+ } + @if (fabi.Costs.Count > 3){
+@(fabi.Costs.Count-3) more…
} +
+ } + + @* Conditions *@ + @if (fabi.Conditions.Count > 0) + { + var condK = $"cond-{fai}"; var condP = _nodePos.GetValueOrDefault(condK,(760,80)); +
+
+ Conditions + @fabi.Conditions.Count +
+
+ } + + @* ActionGroup *@ + var agk = $"group-{fai}"; + var agp = _nodePos.GetValueOrDefault(agk, (960.0, 80.0)); +
+
+ Actions + @fabi.ActionGroupLogicOp +
+
+ @fabi.Actions.Count act@(fabi.Actions.Count==1?"":"s") + @if(fabi.SubGroups.Count>0){, @fabi.SubGroups.Count grp@(fabi.SubGroups.Count==1?"":"s")} + @if(fabi.ActionGroupLogicOp!="And"){
Chooser: @fabi.ActionGroupChooserRole
} +
+
+ + @* Action nodes *@ + @for (int cj = 0; cj < fabi.Actions.Count; cj++) + { + int jidx = cj; + var act = fabi.Actions[jidx]; + var actK = $"action-{fai}-{jidx}"; + var actP = _nodePos.GetValueOrDefault(actK,(960+jidx*250,260)); +
+
+ Action @(jidx+1) + +
+
+ → @act.Ownership @act.TargetType + @if(act.All){All} + else{ ×@act.Count} +
@act.Scope
+
+
+ + @* Effect nodes for this action *@ + @for (int ck = 0; ck < act.Effects.Count; ck++) + { + int kidx = ck; + var eff = act.Effects[kidx]; + var effK = $"effect-{fai}-{jidx}-{kidx}"; + var effP = _nodePos.GetValueOrDefault(effK,(960+jidx*250,260+(kidx+1)*160)); +
+
+ + @eff.TypeKey + +
+
@EffectSummary(eff)
+
+ } + } + + @* Sub-group nodes *@ + @for (int csgi = 0; csgi < fabi.SubGroups.Count; csgi++) + { + int sgiIdx = csgi; + var sg = fabi.SubGroups[sgiIdx]; + var sgK = $"subgroup-{fai}-{sgiIdx}"; + var sgP = _nodePos.GetValueOrDefault(sgK,(960+(fabi.Actions.Count+sgiIdx)*250,260)); +
+
+ Sub-Group @(sgiIdx+1) + @sg.LogicOp + +
+
@sg.Actions.Count act@(sg.Actions.Count==1?"":"s")
+
+ + @for (int sgj = 0; sgj < sg.Actions.Count; sgj++) + { + int sgjIdx = sgj; + var sgAct = sg.Actions[sgjIdx]; + var sgActK = $"subgroupaction-{fai}-{sgiIdx}-{sgjIdx}"; + var sgActP = _nodePos.GetValueOrDefault(sgActK,(960+(fabi.Actions.Count+sgiIdx)*250,260+(sgjIdx+1)*160)); +
+
+ SG@(sgiIdx+1) · Act @(sgjIdx+1) +
+
+ → @sgAct.Ownership @sgAct.TargetType +
+
+ + @for (int sgk = 0; sgk < sgAct.Effects.Count; sgk++) + { + int sgkIdx = sgk; + var sgEff = sgAct.Effects[sgkIdx]; + var sgEffK = $"subgroupeffect-{fai}-{sgiIdx}-{sgjIdx}-{sgkIdx}"; + var sgEffP = _nodePos.GetValueOrDefault(sgEffK,(960+(fabi.Actions.Count+sgiIdx)*250,260+(sgjIdx+1)*160+(sgkIdx+1)*160)); +
+
+ + @sgEff.TypeKey +
+
@EffectSummary(sgEff)
+
+ } + } + } + } +
+
+
+ + @* ── Right panel: inspector ── *@ +
+
Inspector
+ @if (_selectedNode == null || _focusedAbility < 0 || _focusedAbility >= _abilities.Count) + { +

Click a node to inspect.

+ } + else + { + ParseNodeKey(_selectedNode, out var inKind, out var inAi, out var inJ, out var inK, out var inL); + @if (inAi >= 0 && inAi < _abilities.Count) + { + var inAb = _abilities[inAi]; + @if (inKind == "meta") + { + + + + + + + } + else if (inKind == "range") + { + + + + +
+ + +
+
+ + +
+ + + } + else if (inKind == "trigger") + { + + + + + } + else if (inKind == "group") + { + + + @if (inAb.ActionGroupLogicOp != "And") + { + + + } + } + else if (inKind == "subgroup" && inJ >= 0 && inJ < inAb.SubGroups.Count) + { + var inSg = inAb.SubGroups[inJ]; + + + @if (inSg.LogicOp != "And") + { + + + } + } + else if ((inKind == "action" || inKind == "sgaction") && inJ >= 0) + { + ActionDraft? inAct = null; + if (inKind == "action" && inJ < inAb.Actions.Count) + inAct = inAb.Actions[inJ]; + else if (inKind == "sgaction" && inJ < inAb.SubGroups.Count && inK >= 0 && inK < inAb.SubGroups[inJ].Actions.Count) + inAct = inAb.SubGroups[inJ].Actions[inK]; + + @if (inAct != null) + { + + + + + + + + +
+ + +
+ @if (!inAct.All) + { + + + } + } + } + else if ((inKind == "effect" || inKind == "sgeffect") && inJ >= 0) + { + EffectDraft? inEff = null; + if (inKind == "effect" && inJ < inAb.Actions.Count && inK >= 0 && inK < inAb.Actions[inJ].Effects.Count) + inEff = inAb.Actions[inJ].Effects[inK]; + else if (inKind == "sgeffect" && inJ < inAb.SubGroups.Count && inK >= 0 && inK < inAb.SubGroups[inJ].Actions.Count && inL >= 0 && inL < inAb.SubGroups[inJ].Actions[inK].Effects.Count) + inEff = inAb.SubGroups[inJ].Actions[inK].Effects[inL]; + + @if (inEff != null) + { + + +

Switch to Form View for full effect parameters.

+ } + } + } + } +
+ +
+ }
@@ -1093,6 +1571,39 @@ private bool _showRaw; private bool _showHelp; + // ── Canvas mode state ───────────────────────────────────────────────────── + + private bool _canvasMode = false; + private bool _needsJsInit = false; + private int _focusedAbility = 0; + private double _zoom = 1.0, _panX = 60, _panY = 60; + private bool _isPanning; + private double _lastMouseX, _lastMouseY; + + // Node positions: key → (X, Y) canvas coords + private readonly Dictionary _nodePos = new(); + + // Drag state + private string? _draggingNode; + + // Inspector selection + private string? _selectedNode; + + // JS cleanup + private DotNetObjectReference? _jsRef; + private readonly string _canvasId = $"ab-canvas-{Guid.NewGuid():N}"; + + // Canvas node width constants (px in canvas-space) + private const double META_W = 200; + private const double RANGE_W = 200; + private const double COST_W = 200; + private const double TRIGGER_W = 200; + private const double COND_W = 180; + private const double GROUP_W = 220; + private const double ACTION_W = 210; + private const double EFFECT_W = 200; + private const double NODE_H = 34.0; // node header height for port midpoint + // ── Spirit card list for "Existing Card" token mode ─────────────────────── private sealed record SpiritCardEntry(Guid Id, string Name, string Affinity, @@ -3192,6 +3703,315 @@ Compile(); } + // ── Canvas mode methods ─────────────────────────────────────────────────── + + private async Task EnterCanvasMode() + { + _canvasMode = true; + _focusedAbility = Math.Max(0, Math.Min(_focusedAbility, _abilities.Count - 1)); + AutoLayoutAbility(_focusedAbility); + _needsJsInit = true; + await Task.CompletedTask; + } + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (_needsJsInit && _canvasMode) + { + _needsJsInit = false; + _jsRef ??= DotNetObjectReference.Create(this); + try { await JS.InvokeVoidAsync("sorAdmin.abilityBuilder.init", _canvasId, _jsRef); } + catch { /* JS not loaded in pre-render */ } + } + } + + [JSInvokable] + public void OnCanvasWheel(double factor) + { + _zoom = Math.Clamp(_zoom * factor, 0.2, 3.0); + StateHasChanged(); + } + + public async ValueTask DisposeAsync() + { + if (_jsRef != null) + { + try { await JS.InvokeVoidAsync("sorAdmin.abilityBuilder.dispose", _canvasId); } + catch { /* ignore during dispose */ } + _jsRef.Dispose(); + _jsRef = null; + } + } + + private void FocusAbility(int ai) + { + _focusedAbility = ai; + _selectedNode = null; + AutoLayoutAbility(ai); + } + + private void AutoLayoutAbility(int ai) + { + if (ai < 0 || ai >= _abilities.Count) return; + var ab = _abilities[ai]; + double x = 80, y = 80; + + SetPos($"meta-{ai}", x, y); x += META_W + 60; + + if (ab.TypeStr == "Active") { SetPos($"range-{ai}", x, y); x += RANGE_W + 60; } + if (ab.TypeStr == "Triggered"){ SetPos($"trigger-{ai}", x, y); x += TRIGGER_W + 60; } + if (ab.Costs.Count > 0) { SetPos($"cost-{ai}", x, y); x += COST_W + 60; } + if (ab.Conditions.Count > 0) { SetPos($"cond-{ai}", x, y); x += COND_W + 60; } + + double groupX = x; + SetPos($"group-{ai}", groupX, y); + + for (int j = 0; j < ab.Actions.Count; j++) + { + double ax = groupX + j * (ACTION_W + 50); + SetPos($"action-{ai}-{j}", ax, y + 220); + for (int k = 0; k < ab.Actions[j].Effects.Count; k++) + SetPos($"effect-{ai}-{j}-{k}", ax, y + 220 + (k + 1) * 170); + } + + for (int sgi = 0; sgi < ab.SubGroups.Count; sgi++) + { + double sgx = groupX + (ab.Actions.Count + sgi) * (ACTION_W + 50); + SetPos($"subgroup-{ai}-{sgi}", sgx, y + 220); + var sg = ab.SubGroups[sgi]; + for (int j = 0; j < sg.Actions.Count; j++) + { + SetPos($"subgroupaction-{ai}-{sgi}-{j}", sgx, y + 220 + (j + 1) * 170); + for (int k = 0; k < sg.Actions[j].Effects.Count; k++) + SetPos($"subgroupeffect-{ai}-{sgi}-{j}-{k}", sgx, y + 220 + (j + 1) * 170 + (k + 1) * 160); + } + } + } + + /// Only sets position if not already placed (preserves user-drag positions). + private void SetPos(string key, double x, double y) + { + if (!_nodePos.ContainsKey(key)) + _nodePos[key] = (x, y); + } + + /// Sets position unconditionally — used for newly-added nodes. + private void AutoPositionNew(string key, string kind) + { + // Drop new nodes near the center-bottom of any sibling group + _nodePos[key] = kind switch + { + "action" => (960, 260), + _ => (200, 200), + }; + } + + private void AddEffectToSelected() + { + if (_selectedNode is null) return; + ParseNodeKey(_selectedNode, out var kind, out var ai, out var j, out _, out _); + if (ai < 0 || ai >= _abilities.Count) return; + + ActionDraft? act = null; + string newEffKey; + if (kind == "action" && j >= 0 && j < _abilities[ai].Actions.Count) + { + act = _abilities[ai].Actions[j]; + newEffKey = $"effect-{ai}-{j}-{act.Effects.Count}"; + } + else return; + + act.Effects.Add(new EffectDraft()); + AutoPositionNew(newEffKey, "effect"); + Compile(); + } + + private void OnNodeMouseDown(MouseEventArgs e, string nodeId) + { + if (e.Button != 0) return; + _draggingNode = nodeId; + _lastMouseX = e.ClientX; + _lastMouseY = e.ClientY; + _selectedNode = nodeId; + } + + private void OnCanvasMouseMove(MouseEventArgs e) + { + double dx = e.ClientX - _lastMouseX; + double dy = e.ClientY - _lastMouseY; + _lastMouseX = e.ClientX; + _lastMouseY = e.ClientY; + + if (_isPanning) + { + _panX += dx; + _panY += dy; + } + else if (_draggingNode != null && _nodePos.ContainsKey(_draggingNode)) + { + var (ox, oy) = _nodePos[_draggingNode]; + _nodePos[_draggingNode] = (ox + dx / _zoom, oy + dy / _zoom); + } + } + + private void OnCanvasMouseUp(MouseEventArgs e) + { + _draggingNode = null; + _isPanning = false; + } + + private void OnCanvasMouseDown(MouseEventArgs e) + { + _lastMouseX = e.ClientX; + _lastMouseY = e.ClientY; + if (e.Button == 1) // middle mouse = pan + _isPanning = true; + else if (e.Button == 0) + _selectedNode = null; // click canvas background = deselect + } + + private void ResetCanvas() + { + _zoom = 1.0; _panX = 60; _panY = 60; + // Remove node positions so AutoLayout re-fires + _nodePos.Clear(); + AutoLayoutAbility(_focusedAbility); + } + + // ── Canvas edge helpers ─────────────────────────────────────────────────── + + private IEnumerable<(string From, string To)> GetEdges() + { + int ai = _focusedAbility; + if (ai < 0 || ai >= _abilities.Count) yield break; + var ab = _abilities[ai]; + + string prev = $"meta-{ai}"; + + if (ab.TypeStr == "Active") { yield return (prev, $"range-{ai}"); prev = $"range-{ai}"; } + if (ab.TypeStr == "Triggered"){ yield return (prev, $"trigger-{ai}"); prev = $"trigger-{ai}"; } + if (ab.Costs.Count > 0) { yield return (prev, $"cost-{ai}"); prev = $"cost-{ai}"; } + if (ab.Conditions.Count > 0) { yield return (prev, $"cond-{ai}"); prev = $"cond-{ai}"; } + + yield return (prev, $"group-{ai}"); + + for (int j = 0; j < ab.Actions.Count; j++) + { + yield return ($"group-{ai}", $"action-{ai}-{j}"); + for (int k = 0; k < ab.Actions[j].Effects.Count; k++) + yield return (k == 0 ? $"action-{ai}-{j}" : $"effect-{ai}-{j}-{k-1}", + $"effect-{ai}-{j}-{k}"); + } + + for (int sgi = 0; sgi < ab.SubGroups.Count; sgi++) + { + yield return ($"group-{ai}", $"subgroup-{ai}-{sgi}"); + var sg = ab.SubGroups[sgi]; + for (int j = 0; j < sg.Actions.Count; j++) + { + yield return ($"subgroup-{ai}-{sgi}", $"subgroupaction-{ai}-{sgi}-{j}"); + for (int k = 0; k < sg.Actions[j].Effects.Count; k++) + yield return (k == 0 ? $"subgroupaction-{ai}-{sgi}-{j}" : $"subgroupeffect-{ai}-{sgi}-{j}-{k-1}", + $"subgroupeffect-{ai}-{sgi}-{j}-{k}"); + } + } + } + + private (double X, double Y) GetOutputPort(string nodeId) + { + var (x, y) = _nodePos.GetValueOrDefault(nodeId, (0, 0)); + return (x + GetNodeWidth(nodeId), y + NODE_H / 2); + } + + private (double X, double Y) GetInputPort(string nodeId) + { + var (x, y) = _nodePos.GetValueOrDefault(nodeId, (0, 0)); + return (x, y + NODE_H / 2); + } + + private static double GetNodeWidth(string nodeId) + { + if (nodeId.StartsWith("meta-")) return META_W; + if (nodeId.StartsWith("range-")) return RANGE_W; + if (nodeId.StartsWith("cost-")) return COST_W; + if (nodeId.StartsWith("trigger-")) return TRIGGER_W; + if (nodeId.StartsWith("cond-")) return COND_W; + if (nodeId.StartsWith("subgroupaction-") || nodeId.StartsWith("action-")) return ACTION_W; + if (nodeId.StartsWith("subgroupeffect-") || nodeId.StartsWith("effect-")) return EFFECT_W; + return GROUP_W; // group- and subgroup- + } + + private static string BezierPath(double fx, double fy, double tx, double ty) + { + var ic = System.Globalization.CultureInfo.InvariantCulture; + double c = Math.Abs(tx - fx) * 0.5; + return $"M {fx.ToString("F0",ic)} {fy.ToString("F0",ic)} " + + $"C {(fx+c).ToString("F0",ic)} {fy.ToString("F0",ic)}, " + + $"{(tx-c).ToString("F0",ic)} {ty.ToString("F0",ic)}, " + + $"{tx.ToString("F0",ic)} {ty.ToString("F0",ic)}"; + } + + // ── Canvas style helpers ────────────────────────────────────────────────── + + private static string NS((double X, double Y) pos, double w) + { + var ic = System.Globalization.CultureInfo.InvariantCulture; + return $"position:absolute;left:{pos.X.ToString("F0",ic)}px;top:{pos.Y.ToString("F0",ic)}px;" + + $"width:{w.ToString("F0",ic)}px;"; + } + + private static string Px(double v) + { + return v.ToString("F0", System.Globalization.CultureInfo.InvariantCulture) + "px"; + } + + private static string Pf(double v) + { + return v.ToString("F3", System.Globalization.CultureInfo.InvariantCulture); + } + + // ── Node key parsing ────────────────────────────────────────────────────── + + private static void ParseNodeKey(string? key, + out string kind, out int ai, out int j, out int k, out int l) + { + kind = "none"; ai = j = k = l = -1; + if (key is null) return; + var p = key.Split('-'); + if (p.Length < 2) return; + kind = p[0]; + int.TryParse(p[1], out ai); + if (p.Length >= 3) int.TryParse(p[2], out j); + if (p.Length >= 4) int.TryParse(p[3], out k); + if (p.Length >= 5) int.TryParse(p[4], out l); + } + + // ── Effect summary (canvas node body) ──────────────────────────────────── + + private static string EffectSummary(EffectDraft d) => d.TypeKey switch + { + "DealDamage" or "DealDamagePlusStat" or "DOT" + => $"dmg {(string.IsNullOrEmpty(d.AmountRef) ? d.Amount.ToString() : "@" + d.AmountRef)}", + "RestoreHealth" or "HOT" => $"heal {d.Amount}", + "ModifyStat" or "ModifyMaxStat" + => $"{d.StatTarget} {d.Stat} {(d.Amount >= 0 ? "+" : "")}{d.Amount}", + "DrawCards" => $"draw {d.N}", + "DiscardCards" => $"discard {d.N}", + "GainSP" or "SpendSP" or "ModifySPAccumulation" + => $"SP {(d.Amount >= 0 ? "+" : "")}{d.Amount}", + "GainST" or "SpendST" + => $"ST {(d.Amount >= 0 ? "+" : "")}{d.Amount}", + "MoveUnit" => $"move {d.Tiles} tiles", + "PushUnit" => $"push {d.Tiles}", + "PullUnit" => $"pull {d.Tiles}", + "SummonToken" => "summon token", + "DestroyToken" => "destroy token", + "KillUnit" or "DestroyUnit" => "kill", + "SkipTurn" => "skip turn", + "DrawCards_Player" => $"draw {d.N} ({d.Player})", + _ => "", + }; + private void ApplyRawJson() { ParseJson(_compiledJson); diff --git a/Server/src/SOR.Admin/wwwroot/admin.js b/Server/src/SOR.Admin/wwwroot/admin.js index c6de9a5..4032f4f 100644 --- a/Server/src/SOR.Admin/wwwroot/admin.js +++ b/Server/src/SOR.Admin/wwwroot/admin.js @@ -2,6 +2,61 @@ window.sorAdmin = { getTheme: function () { return localStorage.getItem('sor-admin-theme') || 'light'; }, + + // ── Ability Builder canvas wheel/pan JS shim ────────────────────────────── + // Registers a non-passive wheel listener so we can prevent page scroll and + // forward zoom deltas to the Blazor component via JSInvokable. + abilityBuilder: { + _refs: {}, + + init(canvasId, dotnetRef) { + this.dispose(canvasId); + const el = document.getElementById(canvasId); + if (!el) return; + + const onWheel = e => { + e.preventDefault(); + const factor = e.deltaY > 0 ? 0.9 : 1.1; + dotnetRef.invokeMethodAsync('OnCanvasWheel', factor); + }; + + // Pinch zoom via touch (two-finger). + let lastPinchDist = 0; + const onTouchStart = e => { + if (e.touches.length === 2) + lastPinchDist = Math.hypot( + e.touches[0].clientX - e.touches[1].clientX, + e.touches[0].clientY - e.touches[1].clientY); + }; + const onTouchMove = e => { + if (e.touches.length === 2) { + e.preventDefault(); + const d = Math.hypot( + e.touches[0].clientX - e.touches[1].clientX, + e.touches[0].clientY - e.touches[1].clientY); + if (lastPinchDist > 0) { + const factor = d / lastPinchDist; + dotnetRef.invokeMethodAsync('OnCanvasWheel', factor); + } + lastPinchDist = d; + } + }; + + el.addEventListener('wheel', onWheel, { passive: false }); + el.addEventListener('touchstart', onTouchStart, { passive: true }); + el.addEventListener('touchmove', onTouchMove, { passive: false }); + this._refs[canvasId] = { el, onWheel, onTouchStart, onTouchMove }; + }, + + dispose(canvasId) { + const r = this._refs[canvasId]; + if (!r) return; + r.el.removeEventListener('wheel', r.onWheel); + r.el.removeEventListener('touchstart', r.onTouchStart); + r.el.removeEventListener('touchmove', r.onTouchMove); + delete this._refs[canvasId]; + } + }, setTheme: function (theme) { localStorage.setItem('sor-admin-theme', theme); document.documentElement.setAttribute('data-bs-theme', theme); diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index 1e6d65d..8b3fd6b 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -987,6 +987,62 @@ public static class AbilitySystem return state; } + /// + /// Resumes execution after the chooser has responded to a game.reveal_choice_pick. + /// is the chooser's desired ordering of the revealed cards + /// (0-based indices into ). + /// Unspecified cards are placed beneath the chosen cards in their original relative order. + /// + public static GameState ResumeRevealChoicePick( + GameState state, + string actorId, + string requestId, + int[] orderedIndices) + { + var pending = state.PendingRevealChoicePick + ?? throw new GameException("NO_PENDING_REVEAL_CHOICE_PICK"); + + if (pending.RequestId != requestId) + throw new GameException("REQUEST_ID_MISMATCH"); + + if (actorId != pending.ActorId && actorId != pending.ChooserActorId) + throw new GameException("NOT_YOUR_REVEAL_CHOICE_PICK"); + + state.PendingRevealChoicePick = null; + + if (pending.EffectType == "StackDeck") + { + var revealed = JsonSerializer.Deserialize( + pending.RevealedCardsJson, _jsonOpts) ?? []; + + if (!state.Players.TryGetValue(pending.TargetPlayerAccountId, out var ps)) + return state; + + // Validate indices (deduplicate, clamp to valid range). + var validIndices = orderedIndices + .Where(i => i >= 0 && i < revealed.Length) + .Distinct() + .ToArray(); + + var usedSet = new HashSet(validIndices); + + // Unspecified cards go at the bottom of the returned block (drawn last). + var bottom = Enumerable.Range(0, revealed.Length) + .Where(i => !usedSet.Contains(i)) + .Select(i => revealed[i]) + .ToList(); + + // Specified cards go on top (drawn first) in the chooser's order. + var top = validIndices.Select(i => revealed[i]).ToList(); + + // Deck is stored with index 0 = bottom; top of deck is last element. + ps.Deck.AddRange(bottom); + ps.Deck.AddRange(top); + } + + return state; + } + // ── Action execution ────────────────────────────────────────────────────── private static void ExecuteActions( @@ -2358,17 +2414,45 @@ public static class AbilitySystem // ── §5.18 Zone operations ────────────────────────────────────────── case StackDeckEffect stkDe when target is PlayerState stackPs: { - // TODO(Phase5-full): requires PendingRevealChoicePick interactive pause. - // For now: shuffle top N randomly as a non-interactive fallback. int n = Math.Min(stkDe.Count, stackPs.Deck.Count); - var topN = stackPs.Deck.TakeLast(n).ToList(); - for (int si = topN.Count - 1; si > 0; si--) + if (n == 0) break; + + // Determine chooser account id. + string chooserAccountId = stkDe.Chooser switch { - int sj = Random.Shared.Next(si + 1); - (topN[si], topN[sj]) = (topN[sj], topN[si]); + "Opponent" => ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId, + "Random" => "", + _ => ctx.ActorId, // "Self" + }; + + if (stkDe.Chooser == "Random" || string.IsNullOrEmpty(chooserAccountId)) + { + // Non-interactive: shuffle top N randomly. + var topN = stackPs.Deck.TakeLast(n).ToList(); + for (int si = topN.Count - 1; si > 0; si--) + { + int sj = Random.Shared.Next(si + 1); + (topN[si], topN[sj]) = (topN[sj], topN[si]); + } + for (int si = 0; si < n; si++) + stackPs.Deck[stackPs.Deck.Count - n + si] = topN[si]; + break; } - for (int si = 0; si < n; si++) - stackPs.Deck[stackPs.Deck.Count - n + si] = topN[si]; + + // Interactive: remove top N from deck and pause for chooser to order them. + var revealed = stackPs.Deck.TakeLast(n).ToList(); + stackPs.Deck.RemoveRange(stackPs.Deck.Count - n, n); + + ctx.State.PendingRevealChoicePick = new Models.PendingRevealChoicePick + { + ActorId = ctx.ActorId, + ChooserActorId = chooserAccountId, + SourceInstanceId = ctx.Source?.InstanceId ?? "", + EffectType = "StackDeck", + RevealedCardsJson = JsonSerializer.Serialize(revealed, _jsonOpts), + Count = n, + TargetPlayerAccountId = stackPs.AccountId, + }; break; } case SearchAndPlaceEffect sape when target is PlayerState sapPs: diff --git a/Server/src/SOR.Game/Abilities/Models/PendingPlayerPick.cs b/Server/src/SOR.Game/Abilities/Models/PendingPlayerPick.cs new file mode 100644 index 0000000..ae0ae68 --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/PendingPlayerPick.cs @@ -0,0 +1,30 @@ +namespace SOR.Game.Abilities.Models; + +/// +/// Pauses execution when an effect needs a human to select a player +/// (e.g. ChannelCardFromZoneEffect with UnderControlOf: Choice). +/// Resumed by game.player_pick message. +/// +public sealed class PendingPlayerPick +{ + public string RequestId { get; set; } = Guid.NewGuid().ToString("N"); + public string ActorId { get; set; } = string.Empty; + public string ChooserActorId { get; set; } = string.Empty; + public string SourceInstanceId { get; set; } = string.Empty; + + /// Discriminator used by ResumeXxx to know what to do with the picked player. + public string EffectType { get; set; } = string.Empty; + + // ── Candidate pool (sent to client for display) ─────────────────────────── + + /// "Self" | "Opponent" | "Any" — ownership filter on valid player choices. + public string Ownership { get; set; } = "Any"; + /// Account IDs of the valid choices (populated by engine at pause time). + public List ValidPlayerIds { get; set; } = new(); + + // ── Continuation ───────────────────────────────────────────────────────── + + public string ContinuationActionsJson { get; set; } = "[]"; + public string? RangeJson { get; set; } + public string? ForceDurationJson { get; set; } +} diff --git a/Server/src/SOR.Game/Abilities/Models/PendingRevealChoicePick.cs b/Server/src/SOR.Game/Abilities/Models/PendingRevealChoicePick.cs new file mode 100644 index 0000000..225b3e4 --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/PendingRevealChoicePick.cs @@ -0,0 +1,39 @@ +namespace SOR.Game.Abilities.Models; + +/// +/// Pauses execution when cards are revealed face-up and a player must choose +/// an ordering or selection from them (e.g. StackDeckEffect chooser). +/// Resumed by game.reveal_choice_pick message carrying an ordered array of indices. +/// +public sealed class PendingRevealChoicePick +{ + public string RequestId { get; set; } = Guid.NewGuid().ToString("N"); + public string ActorId { get; set; } = string.Empty; + public string ChooserActorId { get; set; } = string.Empty; + public string SourceInstanceId { get; set; } = string.Empty; + + /// Discriminator: "StackDeck" | future uses. + public string EffectType { get; set; } = string.Empty; + + // ── Revealed card set ───────────────────────────────────────────────────── + + /// + /// Serialized CardInstance[] — the revealed cards the chooser sees and orders. + /// Temporarily removed from the deck while this state is pending. + /// + public string RevealedCardsJson { get; set; } = "[]"; + + /// How many cards the chooser must include in their response ordering. + public int Count { get; set; } = 1; + + // ── Context ─────────────────────────────────────────────────────────────── + + /// AccountId of the player whose deck receives the ordered cards. + public string TargetPlayerAccountId { get; set; } = string.Empty; + + // ── Continuation ───────────────────────────────────────────────────────── + + public string ContinuationActionsJson { get; set; } = "[]"; + public string? RangeJson { get; set; } + public string? ForceDurationJson { get; set; } +} diff --git a/Server/src/SOR.Game/Abilities/Models/PendingTilePick.cs b/Server/src/SOR.Game/Abilities/Models/PendingTilePick.cs new file mode 100644 index 0000000..90c7a10 --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/PendingTilePick.cs @@ -0,0 +1,34 @@ +namespace SOR.Game.Abilities.Models; + +/// +/// Pauses execution when an effect needs a human to select a specific tile +/// (e.g. CloneSpiritAsToken with TargetTile destination, RelocateRuin). +/// Resumed by game.tile_pick message. +/// +public sealed class PendingTilePick +{ + public string RequestId { get; set; } = Guid.NewGuid().ToString("N"); + public string ActorId { get; set; } = string.Empty; + public string ChooserActorId { get; set; } = string.Empty; + public string SourceInstanceId { get; set; } = string.Empty; + + /// Discriminator used by ResumeXxx to know what to do with the picked tile. + public string EffectType { get; set; } = string.Empty; + + // ── Tile constraints (sent to client for validation) ───────────────────── + + /// Tile must be empty (no occupant). + public bool RequireEmpty { get; set; } + /// Tile must have an occupant. + public bool RequireOccupied { get; set; } + /// "Owner" | "Ally" | "Enemy" | "Any" — ownership of occupant when RequireOccupied. + public string? OccupantOwnership { get; set; } + /// Max tiles from source; 0 = unlimited. + public int MaxRange { get; set; } + + // ── Continuation ───────────────────────────────────────────────────────── + + public string ContinuationActionsJson { get; set; } = "[]"; + public string? RangeJson { get; set; } + public string? ForceDurationJson { get; set; } +} diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs index d6a5c1a..156eef7 100644 --- a/Server/src/SOR.Game/GameState.cs +++ b/Server/src/SOR.Game/GameState.cs @@ -126,6 +126,27 @@ public sealed class GameState /// player must select a branch. Paused until chooser submits a game.branch_pick. /// public Abilities.Models.PendingBranchPick? PendingBranchPick { get; set; } + + /// + /// Non-null when an effect needs a human to select a specific tile + /// (e.g. CloneSpiritAsToken TargetTile destination, RelocateRuin). + /// Paused until the chooser submits a game.tile_pick response. + /// + public Abilities.Models.PendingTilePick? PendingTilePick { get; set; } + + /// + /// Non-null when an effect needs a human to select a player + /// (e.g. ChannelCardFromZone with UnderControlOf: Choice). + /// Paused until the chooser submits a game.player_pick response. + /// + public Abilities.Models.PendingPlayerPick? PendingPlayerPick { get; set; } + + /// + /// Non-null when cards have been revealed face-up and a player must choose their + /// ordering (e.g. StackDeckEffect interactive path). + /// Paused until the chooser submits a game.reveal_choice_pick response. + /// + public Abilities.Models.PendingRevealChoicePick? PendingRevealChoicePick { get; set; } } public sealed class PlayerState