From 1d5ae4aa2093e7fad69f8b08f9aa91bd45a8d72f Mon Sep 17 00:00:00 2001 From: dingo Date: Mon, 20 Apr 2026 19:47:38 -0400 Subject: [PATCH] feat(phase7): complete ability revamp gap items 1-11 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix [PolyType] attribute placement bug in Effects.cs (silent poly-deser failure) - Add SpiritToken guard to BazaarBuyPrebuiltDeck and CollectionSelectStarterDeck handlers - Wire CostGroup payment into ActivateAbility with PendingCostGroupPick pause support - Add PendingActionGroupPick, PendingCostGroupPick, PendingBranchPick models + GameState props - Add Phase 5 engine switch cases: ModifyChannelRange, RelocateRuin, ActivateRuinAbility, DisableRuinForDuration, CloneSpiritAsToken, DestroyToken, SkipTurn, ModifyCardsDrawnThisTurn, StackDeck, SearchAndPlace, ChangeAttackType, ObstructMovement, AscendFromZone stubs - Add ActionGroup recursion (ResolveActionGroup AND-flatten / OR-XOR interactive pick) - Add ResumeActionGroupPick, ResumeCostGroupPick, ResumeBranchPick methods - Add ChooseOne ChooserRole branching + TargetSelector.Chooser (Random early-return) - Change SearchDeckEffect.ThenAction → ThenGroup: ActionGroup? - Change ApplyOnEventEffect.Effects → Actions: Action[] - Add SOR.Tools console project with cutover-abilities command (EffectsJsonCutover) - AbilityBuilder: add ActionGroupDraft, SubGroups, Compile Groups[], ParseJson Groups[], CompileActionNode/ParseActionNode helpers, nested sub-group UI section - Add Tile.RuinDisabledUntilTurn, PlayerState.SkipTurnCount/CardsDrawnThisTurnBonus, CardInstance.AttackType nullable override - Add SOR.Tools to solution Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- Server/SOR.slnx | 1 + .../Pages/Cards/AbilityBuilder.razor | 213 ++++-- .../Handlers/BazaarBuyPrebuiltDeckHandler.cs | 11 + .../CollectionSelectStarterDeckHandler.cs | 10 + .../src/SOR.Game/Abilities/AbilitySystem.cs | 694 +++++++++++++++++- .../src/SOR.Game/Abilities/Models/Effects.cs | 80 +- .../Models/PendingActionGroupPick.cs | 39 + .../Abilities/Models/PendingBranchPick.cs | 41 ++ .../Abilities/Models/PendingCostGroupPick.cs | 43 ++ Server/src/SOR.Game/GameEngine.cs | 17 +- Server/src/SOR.Game/GameState.cs | 45 +- Server/src/SOR.Game/Grid/Tile.cs | 6 + .../Migrations/EffectsJsonCutover.cs | 132 ++++ Server/src/SOR.Tools/Program.cs | 37 + Server/src/SOR.Tools/SOR.Tools.csproj | 17 + newCard-Cont.md | 161 ++++ 16 files changed, 1407 insertions(+), 140 deletions(-) create mode 100644 Server/src/SOR.Game/Abilities/Models/PendingActionGroupPick.cs create mode 100644 Server/src/SOR.Game/Abilities/Models/PendingBranchPick.cs create mode 100644 Server/src/SOR.Game/Abilities/Models/PendingCostGroupPick.cs create mode 100644 Server/src/SOR.Tools/Migrations/EffectsJsonCutover.cs create mode 100644 Server/src/SOR.Tools/Program.cs create mode 100644 Server/src/SOR.Tools/SOR.Tools.csproj create mode 100644 newCard-Cont.md diff --git a/Server/SOR.slnx b/Server/SOR.slnx index 502fc08..7de3b62 100644 --- a/Server/SOR.slnx +++ b/Server/SOR.slnx @@ -1,6 +1,7 @@ + diff --git a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor b/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor index 97fc42e..058666a 100644 --- a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor +++ b/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor @@ -736,6 +736,65 @@ Add Action + + @if (ab.SubGroups.Count > 0 || ab.ActionGroupLogicOp != "And") + { +
+
+ Nested Sub-Groups + (AND executes all; OR/XOR chooser picks one sub-group) +
+ @for (int sgi = 0; sgi < ab.SubGroups.Count; sgi++) + { + var sgIdx = sgi; + var sg = ab.SubGroups[sgIdx]; +
+
+
+ Sub-Group @(sgIdx + 1) + + @if (sg.LogicOp != "And") + { + + } +
+ +
+
+ @for (int sgai = 0; sgai < sg.Actions.Count; sgai++) + { + var sgaIdx = sgai; +
+ Action @(sgaIdx + 1) + +
+ } + +
+
+ } + +
+ } +
@@ -1415,30 +1474,25 @@ } if (actionsSource != null) foreach (var actionNode in actionsSource.OfType()) + ab.Actions.Add(ParseActionNode(actionNode)); + + // Load sub-groups (Groups[]) if present in ActionGroup + if (node["ActionGroup"] is JsonObject agForGroups + && agForGroups["Groups"] is JsonArray subGroupsArr) + { + foreach (var sgNode in subGroupsArr.OfType()) { - var target = actionNode["Target"] as JsonObject; - var firstFilter= (target?["Filters"] as JsonArray)?.OfType().FirstOrDefault(); - var act = new ActionDraft + var sg = new ActionGroupDraft { - Scope = target?["Scope"]?.GetValue() ?? "Battlefield", - TargetType = target?["Type"]?.GetValue() ?? "Unit", - Ownership = target?["Ownership"]?.GetValue() ?? "Enemy", - Chooser = target?["Chooser"]?.GetValue() ?? "Self", - Count = target?["Count"]?["N"]?.GetValue() ?? 1, - All = target?["Count"]?["All"]?.GetValue() ?? false, - FilterType = firstFilter?["$type"]?.GetValue() ?? "", + LogicOp = sgNode["LogicOp"]?.GetValue() ?? "And", + ChooserRole = sgNode["ChooserRole"]?.GetValue() ?? "Self", }; - - if (actionNode["Conditions"] is JsonArray actionConds) - foreach (var c in actionConds.OfType()) - act.Conditions.Add(ParseCondition(c)); - - if (actionNode["Effects"] is JsonArray effects) - foreach (var eff in effects.OfType()) - act.Effects.Add(ParseEffect(eff)); - - ab.Actions.Add(act); + if (sgNode["Actions"] is JsonArray sgActions) + foreach (var sgActionNode in sgActions.OfType()) + sg.Actions.Add(ParseActionNode(sgActionNode)); + ab.SubGroups.Add(sg); } + } if (node["Duration"] is JsonObject dur) { @@ -1701,6 +1755,29 @@ return d; } + private static ActionDraft ParseActionNode(JsonObject actionNode) + { + var target = actionNode["Target"] as JsonObject; + var firstFilter = (target?["Filters"] as JsonArray)?.OfType().FirstOrDefault(); + var act = new ActionDraft + { + Scope = target?["Scope"]?.GetValue() ?? "Battlefield", + TargetType = target?["Type"]?.GetValue() ?? "Unit", + Ownership = target?["Ownership"]?.GetValue() ?? "Enemy", + Chooser = target?["Chooser"]?.GetValue() ?? "Self", + Count = target?["Count"]?["N"]?.GetValue() ?? 1, + All = target?["Count"]?["All"]?.GetValue() ?? false, + FilterType = firstFilter?["$type"]?.GetValue() ?? "", + }; + if (actionNode["Conditions"] is JsonArray actionConds) + foreach (var c in actionConds.OfType()) + act.Conditions.Add(ParseCondition(c)); + if (actionNode["Effects"] is JsonArray effects) + foreach (var eff in effects.OfType()) + act.Effects.Add(ParseEffect(eff)); + return act; + } + // ── Compile ────────────────────────────────────────────────────────────────── private void Compile() @@ -1778,44 +1855,30 @@ var actionsArr = new JsonArray(); foreach (var action in ab.Actions) - { - var targetNode = new JsonObject - { - ["Scope"] = action.Scope, - ["Type"] = action.TargetType, - ["Ownership"] = action.Ownership, - ["Chooser"] = action.Chooser, - ["Count"] = new JsonObject - { - ["N"] = action.All ? 1 : action.Count, - ["UpTo"] = false, - ["All"] = action.All, - }, - }; - if (!string.IsNullOrEmpty(action.FilterType)) - targetNode["Filters"] = new JsonArray( - new JsonObject { ["$type"] = action.FilterType }); - var actionNode = new JsonObject { ["Target"] = targetNode }; - - if (action.Conditions.Count > 0) - { - var ca = new JsonArray(); - foreach (var c in action.Conditions) ca.Add(CompileCondition(c)); - actionNode["Conditions"] = ca; - } - - var effectsArr = new JsonArray(); - foreach (var eff in action.Effects) - effectsArr.Add(CompileEffect(eff)); - actionNode["Effects"] = effectsArr; - actionsArr.Add(actionNode); - } + actionsArr.Add(CompileActionNode(action)); // Emit ActionGroup (new format) wrapping all leaf actions var actionGroup = new JsonObject { ["LogicOp"] = ab.ActionGroupLogicOp }; if (ab.ActionGroupLogicOp != "And" || ab.ActionGroupChooserRole != "Self") actionGroup["ChooserRole"] = ab.ActionGroupChooserRole; actionGroup["Actions"] = actionsArr; + + // Emit sub-groups (Groups[]) + var groupsArr = new JsonArray(); + foreach (var sg in ab.SubGroups) + { + var sgActionsArr = new JsonArray(); + foreach (var sga in sg.Actions) + sgActionsArr.Add(CompileActionNode(sga)); + var subGroup = new JsonObject { ["LogicOp"] = sg.LogicOp }; + if (sg.LogicOp != "And" || sg.ChooserRole != "Self") + subGroup["ChooserRole"] = sg.ChooserRole; + subGroup["Actions"] = sgActionsArr; + subGroup["Groups"] = new JsonArray(); + groupsArr.Add(subGroup); + } + actionGroup["Groups"] = groupsArr; + node["ActionGroup"] = actionGroup; if (!string.IsNullOrEmpty(ab.DurationStr)) @@ -1853,6 +1916,38 @@ catch { /* keep last valid */ } } + private static JsonObject CompileActionNode(ActionDraft action) + { + var targetNode = new JsonObject + { + ["Scope"] = action.Scope, + ["Type"] = action.TargetType, + ["Ownership"] = action.Ownership, + ["Chooser"] = action.Chooser, + ["Count"] = new JsonObject + { + ["N"] = action.All ? 1 : action.Count, + ["UpTo"] = false, + ["All"] = action.All, + }, + }; + if (!string.IsNullOrEmpty(action.FilterType)) + targetNode["Filters"] = new JsonArray( + new JsonObject { ["$type"] = action.FilterType }); + var actionNode = new JsonObject { ["Target"] = targetNode }; + if (action.Conditions.Count > 0) + { + var ca = new JsonArray(); + foreach (var c in action.Conditions) ca.Add(CompileCondition(c)); + actionNode["Conditions"] = ca; + } + var effectsArr = new JsonArray(); + foreach (var eff in action.Effects) + effectsArr.Add(CompileEffect(eff)); + actionNode["Effects"] = effectsArr; + return actionNode; + } + private static JsonObject CompileCondition(ConditionDraft c) { var node = new JsonObject { ["$type"] = c.TypeStr }; @@ -3158,9 +3253,10 @@ public string DurationStr { get; set; } = ""; public int DurationN { get; set; } = 1; - public List Costs { get; set; } = new(); - public List Conditions { get; set; } = new(); - public List Actions { get; set; } = new(); + public List Costs { get; set; } = new(); + public List Conditions { get; set; } = new(); + public List Actions { get; set; } = new(); + public List SubGroups { get; set; } = new(); // Animation & Sound (client-side metadata only) public bool HasAnimation { get; set; } = false; @@ -3174,6 +3270,13 @@ public string ImpactSoundUrl { get; set; } = ""; } + private sealed class ActionGroupDraft + { + public string LogicOp { get; set; } = "And"; + public string ChooserRole { get; set; } = "Self"; + public List Actions { get; set; } = new(); + } + private sealed class ActionDraft { public string Scope { get; set; } = "Battlefield"; diff --git a/Server/src/SOR.Bazaar/Handlers/BazaarBuyPrebuiltDeckHandler.cs b/Server/src/SOR.Bazaar/Handlers/BazaarBuyPrebuiltDeckHandler.cs index 03210a1..f598619 100644 --- a/Server/src/SOR.Bazaar/Handlers/BazaarBuyPrebuiltDeckHandler.cs +++ b/Server/src/SOR.Bazaar/Handlers/BazaarBuyPrebuiltDeckHandler.cs @@ -14,6 +14,7 @@ internal sealed class BazaarBuyPrebuiltDeckHandler : BazaarHandlerBase, IMessage private readonly IMessageSerializer _serializer; private readonly BazaarDbContext _bazaarDb; private readonly CollectionDbContext _collectionDb; + private readonly CatalogDbContext _catalogDb; private readonly SorIdentityDbContext _identityDb; public string MessageType => "bazaar.buy_prebuilt_deck"; @@ -22,11 +23,13 @@ internal sealed class BazaarBuyPrebuiltDeckHandler : BazaarHandlerBase, IMessage IMessageSerializer serializer, BazaarDbContext bazaarDb, CollectionDbContext collectionDb, + CatalogDbContext catalogDb, SorIdentityDbContext identityDb) { _serializer = serializer; _bazaarDb = bazaarDb; _collectionDb = collectionDb; + _catalogDb = catalogDb; _identityDb = identityDb; } @@ -56,9 +59,16 @@ internal sealed class BazaarBuyPrebuiltDeckHandler : BazaarHandlerBase, IMessage "You do not have enough Origin Points to purchase this deck."); // ── Grant cards ─────────────────────────────────────────────────────── + var allCardIds = deck.Cards.Select(c => c.CardDefinitionId).Distinct().ToHashSet(); + var spiritTokenIds = (await _catalogDb.CardDefinitions + .Where(cd => allCardIds.Contains(cd.Id) && cd.CardType == CardType.SpiritToken) + .Select(cd => cd.Id) + .ToListAsync(ct)).ToHashSet(); + var grantedCards = new List(); foreach (var deckCard in deck.Cards) { + if (spiritTokenIds.Contains(deckCard.CardDefinitionId)) continue; for (int i = 0; i < deckCard.Quantity; i++) { var pc = new PlayerCard @@ -104,6 +114,7 @@ internal sealed class BazaarBuyPrebuiltDeckHandler : BazaarHandlerBase, IMessage foreach (var deckCard in deck.Cards) { + if (spiritTokenIds.Contains(deckCard.CardDefinitionId)) continue; _collectionDb.DeckCards.Add(new DeckCard { DeckId = newDeck.Id, diff --git a/Server/src/SOR.Collection/Handlers/CollectionSelectStarterDeckHandler.cs b/Server/src/SOR.Collection/Handlers/CollectionSelectStarterDeckHandler.cs index 3170701..a15c516 100644 --- a/Server/src/SOR.Collection/Handlers/CollectionSelectStarterDeckHandler.cs +++ b/Server/src/SOR.Collection/Handlers/CollectionSelectStarterDeckHandler.cs @@ -6,6 +6,7 @@ using SOR.Database.Entities.Collection; using SOR.Database.Entities.Identity; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Transport; +using SOR.Database.Enums; using SOR.Shared.Networking; /// @@ -81,8 +82,16 @@ internal sealed class CollectionSelectStarterDeckHandler : CollectionHandlerBase // ── Grant PlayerCards (untradeable) ─────────────────────────────────── // One PlayerCard row per copy of each card in the prebuilt deck. + // SpiritToken cards are summoned by effects and must never enter a player's collection. + var allCardIds = starterDeck.Cards.Select(c => c.CardDefinitionId).Distinct().ToHashSet(); + var spiritTokenIds = (await _catalogDb.CardDefinitions + .Where(cd => allCardIds.Contains(cd.Id) && cd.CardType == CardType.SpiritToken) + .Select(cd => cd.Id) + .ToListAsync(cancellationToken)).ToHashSet(); + foreach (var deckCard in starterDeck.Cards) { + if (spiritTokenIds.Contains(deckCard.CardDefinitionId)) continue; for (int i = 0; i < deckCard.Quantity; i++) { _collectionDb.PlayerCards.Add(new PlayerCard @@ -121,6 +130,7 @@ internal sealed class CollectionSelectStarterDeckHandler : CollectionHandlerBase foreach (var deckCard in starterDeck.Cards) { + if (spiritTokenIds.Contains(deckCard.CardDefinitionId)) continue; _collectionDb.DeckCards.Add(new DeckCard { DeckId = deck.Id, diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index 57c705e..1e6d65d 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -47,6 +47,22 @@ public static class AbilitySystem // Top-level ability/action sequence depth for UntilEndOfSequence cleanup. private static int _sequenceDepth = 0; + // ── JSON options (public factory for tooling) ───────────────────────────── + + /// Returns the same JsonSerializerOptions used by the ability engine. Used by SOR.Tools. + public static JsonSerializerOptions CreateJsonOptions() => new() + { + PropertyNameCaseInsensitive = true, + Converters = + { + new System.Text.Json.Serialization.JsonStringEnumConverter(), + new EffectPolymorphicConverter(), + new ConditionPolymorphicConverter(), + new TriggerPolymorphicConverter(), + new FilterPolymorphicConverter(), + }, + }; + // ── Parsing ──────────────────────────────────────────────────────────────── public static AbilityDefinition[] ParseAbilities(string? json) @@ -112,13 +128,22 @@ public static class AbilitySystem source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1; - if (def.Cost is { Length: > 0 }) + var effectiveActions = GetEffectiveActions(def, ctx, abilityIndex, def.Range, def.Duration); + // GetEffectiveActions returns null when it emitted PendingActionGroupPick (OR/XOR, interactive). + if (effectiveActions is null) return state; + + if (def.CostGroup is { } cg) { - bool paused = PayCosts(def.Cost, ctx, abilityIndex, GetEffectiveActions(def), def.Range, def.Duration); + bool paused = PayCostGroup(cg, ctx, abilityIndex, effectiveActions, def.Range, def.Duration); + if (paused) return state; + } + else if (def.Cost is { Length: > 0 }) + { + bool paused = PayCosts(def.Cost, ctx, abilityIndex, effectiveActions, def.Range, def.Duration); if (paused) return state; // waiting for client cost pick } - ExecuteActions(GetEffectiveActions(def), ctx, clientTargets, requireClientTargets: true, activationRange: def.Range, forceDuration: def.Duration); + ExecuteActions(effectiveActions, ctx, clientTargets, requireClientTargets: true, activationRange: def.Range, forceDuration: def.Duration); return state; } @@ -142,7 +167,9 @@ public static class AbilitySystem if (!ValidateSourceActivationConditions(def, ctx, card)) continue; - ExecuteActions(GetEffectiveActions(def), ctx, clientTargets, requireClientTargets: true, + var cardActions = GetEffectiveActions(def, ctx, abilityIndex: 0, def.Range, def.Duration); + if (cardActions is null) continue; // paused for interactive ActionGroup pick + ExecuteActions(cardActions, ctx, clientTargets, requireClientTargets: true, activationRange: def.Range, forceDuration: def.Duration); } @@ -259,7 +286,7 @@ public static class AbilitySystem } // If any action needs a human pick, pause and request client input. - var effectiveActions = GetEffectiveActions(def); + var effectiveActions = GetEffectiveActions(def, ctx, abilityIndex: 0, def.Range, def.Duration) ?? []; if (effectiveActions.Any(ActionNeedsClientTargets)) { state.PendingTriggeredTarget = new PendingTriggeredTarget @@ -299,20 +326,23 @@ public static class AbilitySystem { state.PendingDeferredEffects.Remove(pending); - Effect[]? deferredEffects; - try { deferredEffects = JsonSerializer.Deserialize(pending.EffectsJson, _jsonOpts); } + Models.Action[]? deferredActions; + try { deferredActions = JsonSerializer.Deserialize(pending.ActionsJson, _jsonOpts); } catch { continue; } - if (deferredEffects is null) continue; - - var tgt = FindDeferredTarget(state, pending.TargetRef); - if (tgt is null) continue; + if (deferredActions is null || deferredActions.Length == 0) continue; var dSrc = state.Players.Values .SelectMany(p => p.Field).OfType() .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); var dCtx = new AbilityContext { State = state, ActorId = pending.OwnerAccountId, Source = dSrc }; - foreach (var eff in deferredEffects) - ExecuteEffect(eff, tgt, DurationModel.Instant, dCtx); + + // Pre-seed the deferred target as action-0 resolved target so chained + // actions inside the deferred tree can reference it. + var tgt = FindDeferredTarget(state, pending.TargetRef); + if (tgt is not null) + dCtx.ResolvedTargets[0] = [tgt]; + + ExecuteActions(deferredActions, dCtx, clientTargets: null, requireClientTargets: false); } return state; @@ -352,6 +382,10 @@ public static class AbilitySystem var tile = state.Board?.GetTile(ruin.Position!.Value); if (tile?.OccupantId is null) continue; + // Skip if this ruin is disabled by DisableRuinForDurationEffect. + if (tile.RuinDisabledUntilTurn > 0 && state.TurnNumber <= tile.RuinDisabledUntilTurn) + continue; + // Only fires if a Spirit or ArchSpirit is on the tile. var occupantType = FindUnitType(state, tile.OccupantId); if (occupantType is not ("Spirit" or "ArchSpirit" or "SpiritToken")) continue; @@ -370,7 +404,9 @@ public static class AbilitySystem // Select exactly one ability at random. var chosen = eligible[Random.Shared.Next(eligible.Count)]; - ExecuteActions(GetEffectiveActions(chosen), ctx, clientTargets: null); + var chosenActions = GetEffectiveActions(chosen, ctx, abilityIndex: 0, chosen.Range, chosen.Duration); + if (chosenActions is not null) + ExecuteActions(chosenActions, ctx, clientTargets: null); // Notify observer cards that the ruin activated. FireTrigger(state, new TriggerOccurrence @@ -467,6 +503,136 @@ public static class AbilitySystem return false; // all paid } + /// + /// Pays a CostGroup. + /// AND: recursively pays all entries and sub-groups; pauses on first interactive cost. + /// OR/XOR + Random: picks one child (entry or sub-group) at random and pays it. + /// OR/XOR + Self/Opponent: stores and returns true. + /// Returns true when paused (caller must stop and return state). + /// + private static bool PayCostGroup( + CostGroup group, + AbilityContext ctx, + int abilityIndex, + Models.Action[] pendingActions, + AbilityRange? range, + DurationModel? forceDuration) + { + if (group.LogicOp == CostGroupLogicOp.And) + { + // Pay all leaf entries. + if (group.Entries.Length > 0) + { + bool paused = PayCosts(group.Entries, ctx, abilityIndex, pendingActions, range, forceDuration); + if (paused) return true; + } + // Recurse into sub-groups. + foreach (var child in group.Groups) + { + bool paused = PayCostGroup(child, ctx, abilityIndex, pendingActions, range, forceDuration); + if (paused) return true; + } + return false; + } + + // OR / XOR: combined pool = leaf entry sets + nested groups + int entryCount = group.Entries.Length; + int groupCount = group.Groups.Length; + int total = entryCount + groupCount; + if (total == 0) return false; + + if (group.ChooserRole == "Random") + { + int idx = Random.Shared.Next(total); + if (idx < entryCount) + { + PaySingleCost(group.Entries[idx], ctx.State.Players[ctx.ActorId], ctx); + return false; + } + return PayCostGroup(group.Groups[idx - entryCount], ctx, abilityIndex, + pendingActions, range, forceDuration); + } + + // Self or Opponent: pause for interactive pick. + var chooserActorId = group.ChooserRole == "Opponent" + ? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId + : ctx.ActorId; + + ctx.State.PendingCostGroupPick = new PendingCostGroupPick + { + ActorId = ctx.ActorId, + ChooserActorId = chooserActorId, + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + AbilityIndex = abilityIndex, + CostGroupJson = JsonSerializer.Serialize(group, _jsonOpts), + ActionsJson = JsonSerializer.Serialize(pendingActions, _jsonOpts), + RangeJson = range is not null ? JsonSerializer.Serialize(range, _jsonOpts) : null, + ForceDurationJson = forceDuration is not null + ? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null, + }; + return true; // paused + } + + /// + /// Resumes execution after the chooser has responded to a game.cost_group_pick. + /// + public static GameState ResumeCostGroupPick( + GameState state, + string actorId, + string requestId, + int choiceIndex) + { + var pending = state.PendingCostGroupPick + ?? throw new GameException("NO_PENDING_COST_GROUP_PICK"); + + if (pending.RequestId != requestId) + throw new GameException("REQUEST_ID_MISMATCH"); + + if (actorId != pending.ActorId && actorId != pending.ChooserActorId) + throw new GameException("NOT_YOUR_COST_GROUP_PICK"); + + state.PendingCostGroupPick = null; + + var group = JsonSerializer.Deserialize(pending.CostGroupJson, _jsonOpts) + ?? throw new GameException("INVALID_COST_GROUP_STATE"); + + int entryCount = group.Entries.Length; + int groupCount = group.Groups.Length; + int total = entryCount + groupCount; + if (choiceIndex < 0 || choiceIndex >= total) + throw new GameException("INVALID_COST_GROUP_CHOICE"); + + var source = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); + if (source is null) return state; + + var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source }; + var player = state.Players[pending.ActorId]; + AbilityRange? range = pending.RangeJson is not null + ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; + DurationModel? forceDuration = pending.ForceDurationJson is not null + ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; + var actions = JsonSerializer.Deserialize(pending.ActionsJson, _jsonOpts) ?? []; + + if (choiceIndex < entryCount) + { + // Pay the chosen leaf entry. + PaySingleCost(group.Entries[choiceIndex], player, ctx); + } + else + { + // Recursively pay the chosen nested group (AND-only for now; nested OR/XOR would recurse further). + bool paused = PayCostGroup(group.Groups[choiceIndex - entryCount], ctx, + pending.AbilityIndex, actions, range, forceDuration); + if (paused) return state; + } + + ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: false, + activationRange: range, forceDuration: forceDuration); + return state; + } + private static void PaySingleCost(CostEntry cost, PlayerState player, AbilityContext ctx) { switch (cost.Type) @@ -637,27 +803,190 @@ public static class AbilitySystem return state; } - // ── ActionGroup backward-compat ─────────────────────────────────────────── + /// + /// Resumes execution after the chooser has responded to a game.branch_pick. + /// + public static GameState ResumeBranchPick( + GameState state, + string actorId, + string requestId, + int branchIndex) + { + var pending = state.PendingBranchPick + ?? throw new GameException("NO_PENDING_BRANCH_PICK"); + + if (pending.RequestId != requestId) + throw new GameException("REQUEST_ID_MISMATCH"); + + if (actorId != pending.ActorId && actorId != pending.ChooserActorId) + throw new GameException("NOT_YOUR_BRANCH_PICK"); + + if (branchIndex < 0 || branchIndex >= pending.BranchCount) + throw new GameException("INVALID_BRANCH_INDEX"); + + state.PendingBranchPick = null; + + var branches = JsonSerializer.Deserialize(pending.BranchesJson, _jsonOpts) ?? []; + var continuation = JsonSerializer.Deserialize( + pending.ContinuationActionsJson, _jsonOpts) ?? []; + AbilityRange? range = pending.RangeJson is not null + ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; + DurationModel? forceDuration = pending.ForceDurationJson is not null + ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; + + var source = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); + var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source }; + + var allActions = branches[branchIndex].Actions.Concat(continuation).ToArray(); + ExecuteActions(allActions, ctx, clientTargets: null, requireClientTargets: false, + activationRange: range, forceDuration: forceDuration); + return state; + } + + // ── ActionGroup resolution ──────────────────────────────────────────────── /// - /// Returns the effective action list for an ability, preferring ActionGroup when present. - /// AND groups run all leaf actions sequentially (same as the old flat list). - /// OR/XOR groups pick one leaf action at random for now (full interactive - /// PendingActionGroupPick support is deferred to a future pass). + /// Returns the flat action list to execute for an ability. + /// AND groups are flattened recursively (leaves + nested group leaves). + /// OR/XOR + Random: picks one child (action or nested group) server-side. + /// OR/XOR + Self/Opponent: emits , returns null (caller must pause). /// Falls back to for pre-Phase-1 data. /// - private static Models.Action[] GetEffectiveActions(AbilityDefinition def) + private static Models.Action[]? GetEffectiveActions( + AbilityDefinition def, + AbilityContext ctx, + int abilityIndex, + AbilityRange? range, + DurationModel? forceDuration) { if (def.ActionGroup is { } ag) - { - if (ag.LogicOp == ActionGroupLogicOp.And || ag.Actions.Length == 0) - return ag.Actions; - // OR / XOR: pick one leaf at random (server-side interim) - return [ag.Actions[Random.Shared.Next(ag.Actions.Length)]]; - } + return ResolveActionGroup(ag, ctx, abilityIndex, range, forceDuration, + continuationActions: []); return def.Actions; // backward-compat: pre-Phase-1 rows use the flat array } + /// + /// Recursively resolves an ActionGroup into a flat action list. + /// Returns null when the group is interactive (OR/XOR + Self/Opponent) and + /// has been stored. + /// + private static Models.Action[]? ResolveActionGroup( + ActionGroup ag, + AbilityContext ctx, + int abilityIndex, + AbilityRange? range, + DurationModel? forceDuration, + Models.Action[] continuationActions) + { + if (ag.LogicOp == ActionGroupLogicOp.And) + { + // AND: run leaves then recurse into nested groups, flattening all. + var all = new List(ag.Actions); + foreach (var child in ag.Groups) + { + var childActions = ResolveActionGroup(child, ctx, abilityIndex, range, + forceDuration, continuationActions); + if (childActions is null) return null; // child emitted pending pick + all.AddRange(childActions); + } + return all.ToArray(); + } + + // OR / XOR: combined pool = leaf actions + nested groups + int leafCount = ag.Actions.Length; + int groupCount = ag.Groups.Length; + int total = leafCount + groupCount; + if (total == 0) return []; + + if (ag.ChooserRole == "Random") + { + int idx = Random.Shared.Next(total); + if (idx < leafCount) + return [ag.Actions[idx]]; + return ResolveActionGroup(ag.Groups[idx - leafCount], ctx, abilityIndex, + range, forceDuration, continuationActions); + } + + // Self or Opponent: pause for interactive pick. + var chooserActorId = ag.ChooserRole == "Opponent" + ? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId + : ctx.ActorId; + + ctx.State.PendingActionGroupPick = new PendingActionGroupPick + { + ActorId = ctx.ActorId, + ChooserActorId = chooserActorId, + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + ActionGroupJson = JsonSerializer.Serialize(ag, _jsonOpts), + ContinuationActionsJson = JsonSerializer.Serialize(continuationActions, _jsonOpts), + RangeJson = range is not null ? JsonSerializer.Serialize(range, _jsonOpts) : null, + ForceDurationJson = forceDuration is not null + ? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null, + }; + return null; // paused + } + + /// + /// Resumes execution after the chooser has responded to a game.action_group_pick. + /// + public static GameState ResumeActionGroupPick( + GameState state, + string actorId, + string requestId, + int choiceIndex) + { + var pending = state.PendingActionGroupPick + ?? throw new GameException("NO_PENDING_ACTION_GROUP_PICK"); + + if (pending.RequestId != requestId) + throw new GameException("REQUEST_ID_MISMATCH"); + + if (actorId != pending.ActorId && actorId != pending.ChooserActorId) + throw new GameException("NOT_YOUR_ACTION_GROUP_PICK"); + + state.PendingActionGroupPick = null; + + var ag = JsonSerializer.Deserialize(pending.ActionGroupJson, _jsonOpts) + ?? throw new GameException("INVALID_ACTION_GROUP_STATE"); + + int leafCount = ag.Actions.Length; + int groupCount = ag.Groups.Length; + int total = leafCount + groupCount; + if (choiceIndex < 0 || choiceIndex >= total) + throw new GameException("INVALID_ACTION_GROUP_CHOICE"); + + var source = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); + + var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source }; + var continuation = JsonSerializer.Deserialize( + pending.ContinuationActionsJson, _jsonOpts) ?? []; + AbilityRange? range = pending.RangeJson is not null + ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; + DurationModel? forceDuration = pending.ForceDurationJson is not null + ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; + + Models.Action[]? chosen; + if (choiceIndex < leafCount) + { + chosen = [ag.Actions[choiceIndex]]; + } + else + { + chosen = ResolveActionGroup(ag.Groups[choiceIndex - leafCount], ctx, + abilityIndex: 0, range, forceDuration, continuation); + if (chosen is null) return state; // nested group triggered another pick + } + + var allActions = chosen.Concat(continuation).ToArray(); + ExecuteActions(allActions, ctx, clientTargets: null, requireClientTargets: false, + activationRange: range, forceDuration: forceDuration); + return state; + } + // ── Action execution ────────────────────────────────────────────────────── private static void ExecuteActions( @@ -697,13 +1026,53 @@ public static class AbilitySystem HashSet? restrictTargets = null, DurationModel? forceDuration = null) { - // ChooseOne branch selector: execute the client-chosen branch's actions instead. + // ChooseOne branch selector: execute the chosen branch's actions instead. if (action.ChooseOne is { Branches.Length: > 0 }) { - var branchIdx = clientTargets? - .FirstOrDefault(t => t.ActionIndex == actionIndex)?.BranchIndex ?? 0; - branchIdx = Math.Clamp(branchIdx, 0, action.ChooseOne.Branches.Length - 1); - ExecuteActions(action.ChooseOne.Branches[branchIdx].Actions, ctx, + var chooser = action.ChooseOne; + int branchIdx; + + if (chooser.ChooserRole == "Random") + { + branchIdx = Random.Shared.Next(chooser.Branches.Length); + } + else if (chooser.ChooserRole is "Opponent" or "Ally") + { + // Pause — let the non-activating player pick. + var chooserActorId = chooser.ChooserRole == "Opponent" + ? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId + : ctx.State.Players.Values + .FirstOrDefault(p => p.AccountId != ctx.ActorId + && ctx.State.AreAllies(p.AccountId, ctx.ActorId)) + ?.AccountId ?? ctx.ActorId; + + // Collect remaining actions after this one as continuation. + // (We don't have the full list here — continuation will be empty; + // the branch picker resumes with branch actions only.) + ctx.State.PendingBranchPick = new PendingBranchPick + { + ActorId = ctx.ActorId, + ChooserActorId = chooserActorId, + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + BranchCount = chooser.Branches.Length, + BranchesJson = JsonSerializer.Serialize(chooser.Branches, _jsonOpts), + ContinuationActionsJson = "[]", + RangeJson = activationRange is not null + ? JsonSerializer.Serialize(activationRange, _jsonOpts) : null, + ForceDurationJson = forceDuration is not null + ? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null, + }; + return; // paused — caller will propagate stop + } + else + { + // Self: use client-provided BranchIndex. + branchIdx = clientTargets? + .FirstOrDefault(t => t.ActionIndex == actionIndex)?.BranchIndex ?? 0; + branchIdx = Math.Clamp(branchIdx, 0, chooser.Branches.Length - 1); + } + + ExecuteActions(chooser.Branches[branchIdx].Actions, ctx, clientTargets: null, requireClientTargets: false, forceDuration: forceDuration); return; @@ -892,6 +1261,19 @@ public static class AbilitySystem if (selector.Filters is { Length: > 0 }) candidates = candidates.Where(c => FiltersMatch(selector.Filters, c, ctx)).ToList(); + // TargetChooser.Random: server picks randomly from filtered candidates — skip client IDs. + if (selector.Chooser == TargetChooser.Random) + { + if (activationRange is not null) + { + candidates = FilterTargetsByAbilityRange(candidates.Cast().ToList(), ctx, activationRange) + .OfType().ToList(); + } + var shuffled = candidates.OrderBy(_ => Random.Shared.Next()).ToList(); + int take = selector.Count.All ? shuffled.Count : Math.Min(selector.Count.N, shuffled.Count); + return shuffled.Take(take).Cast().ToList(); + } + HashSet clientIds = []; if (clientTargets is not null) { @@ -998,6 +1380,20 @@ public static class AbilitySystem return true; } + /// + /// Recursively flattens an AND ActionGroup into a flat action list. + /// OR/XOR groups are left as single-action entries (no interactive pause from here). + /// + private static Models.Action[] FlattenAndGroup(ActionGroup ag) + { + if (ag.LogicOp != ActionGroupLogicOp.And) + return ag.Actions; // OR/XOR: callers should use ResolveActionGroup; this is a fallback + var all = new List(ag.Actions); + foreach (var child in ag.Groups) + all.AddRange(FlattenAndGroup(child)); + return all.ToArray(); + } + private static List BuildCandidates( TargetSelector selector, GameState state, string actorId) { @@ -1574,12 +1970,16 @@ public static class AbilitySystem foreach (var card in found) { ps.Deck.Remove(card); - if (sde.ThenAction is not null) + if (sde.ThenGroup is not null) { + // Pre-load the found card as action-0 resolved target so chained + // targeting in ThenGroup can reference it via "Action0.Target". var innerCtx = new AbilityContext { State = ctx.State, ActorId = ctx.ActorId, Source = ctx.Source }; - foreach (var eff in sde.ThenAction.Effects) - ExecuteEffect(eff, card, sde.ThenAction.Duration, innerCtx); + innerCtx.ResolvedTargets[0] = [card]; + var groupActions = FlattenAndGroup(sde.ThenGroup); + ExecuteActions(groupActions, innerCtx, clientTargets: null, + requireClientTargets: false); } else { @@ -1794,6 +2194,230 @@ public static class AbilitySystem break; } + // ── §5.13 ArchSpirit zone operations ────────────────────────────── + case AscendFromZoneEffect aze when target is FieldCard arcAze && arcAze.IsLeader: + { + // TODO(Phase5-full): full ascension requires catalog lookup for prev-tier card, + // running the ascension handler, and updating AbilitiesJson/stats. Stubbed. + break; + } + case TransitionFromZoneEffect tze when target is FieldCard arcTze && arcTze.IsLeader: + { + // TODO(Phase5-full): full transition requires catalog lookup for same-tier card. + break; + } + case ModifyChannelRangeEffect mcre when target is FieldCard arcMcr && arcMcr.IsLeader: + { + if (mcre.MinDelta != 0) + { + int orig = arcMcr.MinChannelRange ?? 0; + arcMcr.MinChannelRange = Math.Max(0, orig + mcre.MinDelta); + TrackEffect(new ModifyChannelRangeEffect { MinDelta = -(arcMcr.MinChannelRange.Value - orig) }, + arcMcr.InstanceId, duration, ctx); + } + if (mcre.MaxDelta != 0) + { + int orig = arcMcr.MaxChannelRange ?? 0; + arcMcr.MaxChannelRange = Math.Max(0, orig + mcre.MaxDelta); + TrackEffect(new ModifyChannelRangeEffect { MaxDelta = -(arcMcr.MaxChannelRange.Value - orig) }, + arcMcr.InstanceId, duration, ctx); + } + break; + } + + // ── §5.14 Ruin manipulation ──────────────────────────────────────── + case RelocateRuinEffect when target is Coord destCoord: + { + // Source is the ruin unit; relocate it to destCoord. + if (ctx.Source is not FieldCard ruinFc || ctx.State.Board is null) break; + var board = ctx.State.Board; + var ruinTile = board.Tiles.Values.FirstOrDefault(t => t.RuinId == ruinFc.InstanceId); + if (ruinTile is null) break; + var destTile = board.GetTile(destCoord); + if (destTile is null || destTile.RuinId is not null) break; + board.RemoveRuin(ruinFc.InstanceId); + board.PlaceRuin(destCoord, ruinFc.InstanceId, ctx.ActorId); + ruinFc.Position = destCoord; + break; + } + case ActivateRuinAbilityEffect arAe when target is FieldCard ruinCard && ruinCard.CardType == "Ruin": + { + var ruinOwner = FindCardOwner(ctx.State, ruinCard.InstanceId); + if (ruinOwner is null) break; + var ruinCtx = new AbilityContext { State = ctx.State, ActorId = ruinOwner.AccountId, Source = ruinCard }; + var ruinAbilities = ParseAbilities(ruinCard.AbilitiesJson); + var eligible = ruinAbilities + .Where(a => a.Type == AbilityType.Triggered && a.TriggerEvent is OnRuinActivationTrigger) + .Where(a => a.ActivationConditions is not { Length: > 0 } + || a.ActivationConditions.All(c => EvaluateCondition(c, ruinCtx, ruinCard))) + .ToList(); + if (eligible.Count == 0) break; + AbilityDefinition chosen; + if (!arAe.Random && arAe.AbilityRef is not null) + chosen = eligible.FirstOrDefault(a => a.Name == arAe.AbilityRef) ?? eligible[Random.Shared.Next(eligible.Count)]; + else + chosen = eligible[Random.Shared.Next(eligible.Count)]; + var chosenActs = GetEffectiveActions(chosen, ruinCtx, 0, chosen.Range, chosen.Duration); + if (chosenActs is not null) + ExecuteActions(chosenActs, ruinCtx, clientTargets: null); + break; + } + case DisableRuinForDurationEffect drfd when target is FieldCard ruinDis && ruinDis.CardType == "Ruin": + { + if (ruinDis.Position.HasValue && ctx.State.Board is not null) + { + var ruinDisTile = ctx.State.Board.GetTile(ruinDis.Position.Value); + if (ruinDisTile is not null) + { + int disableTurns = drfd.Duration.Type switch + { + DurationType.ForNTurns => drfd.Duration.N ?? 1, + _ => 1, + }; + ruinDisTile.RuinDisabledUntilTurn = ctx.State.TurnNumber + disableTurns; + } + } + break; + } + + // ── §5.15 Enhanced channeling ────────────────────────────────────── + case ChannelCardFromZoneEffect ccze when target is CardInstance ciCcze: + { + // TODO(Phase5-full): full channeling from zone requires tile selection, + // control assignment, and invoking the existing channel logic. + // For now: move card from the specified zone to the battlefield (basic path). + var ccOwner = FindCardOwner(ctx.State, ciCcze.InstanceId); + if (ccOwner is null) break; + _ = ccze; // suppress unused warning until full impl + break; + } + + // ── §5.16 Token / spirit operations ─────────────────────────────── + case CloneSpiritAsTokenEffect cste when target is FieldCard spiritToClone: + { + if (ctx.State.Board is null || !spiritToClone.Position.HasValue) break; + var board = ctx.State.Board; + // Find a suitable destination tile. + Coord? dest = cste.DestinationScope switch + { + "TargetTile" => ctx.ResolvedTargets.Count > 0 + ? ctx.ResolvedTargets.Values.SelectMany(x => x).OfType().FirstOrDefault() + : (Coord?)null, + "RandomInChannelRange" when ctx.Source is FieldCard srcFc && srcFc.Position.HasValue => + board.Tiles.Values + .Where(t => t.IsEmpty && t.Coord.ManhattanDistance(srcFc.Position.Value) <= (ctx.Source as CardInstance)?.MaxChannelRange.GetValueOrDefault(2)) + .Select(t => t.Coord) + .OrderBy(_ => Random.Shared.Next()) + .Cast() + .FirstOrDefault(), + _ => // NeighborTile (default) + board.Tiles.Values + .Where(t => t.IsEmpty && t.Coord.IsOrthogonallyAdjacentTo(spiritToClone.Position.Value)) + .Select(t => t.Coord) + .OrderBy(_ => Random.Shared.Next()) + .Cast() + .FirstOrDefault(), + }; + if (dest is null) break; + + var tokenProto = new CardInstance + { + InstanceId = Guid.NewGuid().ToString("N")[..8], + CardType = "SpiritToken", + Name = spiritToClone.Name, + Affinity = spiritToClone.Affinity, + MaxHealth = spiritToClone.MaxHealth, + CurrentHealth = spiritToClone.MaxHealth, + MaxDefense = spiritToClone.MaxDefense, + CurrentDefense = spiritToClone.MaxDefense, + Damage = spiritToClone.Damage, + CanMove = spiritToClone.CanMove, + CanAttack = spiritToClone.CanAttack, + CanDefend = spiritToClone.CanDefend, + MovementType = spiritToClone.MovementType, + AbilitiesJson = spiritToClone.AbilitiesJson, + }; + var tokenField = CreateTokenFieldCard(tokenProto, dest.Value); + ctx.State.Players[ctx.ActorId].Field.Add(tokenField); + board.PlaceUnit(dest.Value, tokenField.InstanceId, ctx.ActorId); + EvaluateAurasOnEnter(ctx.State, tokenField.InstanceId); + break; + } + case DestroyTokenEffect when target is FieldCard tokenFc && tokenFc.CardType == "SpiritToken": + KillUnit(tokenFc, ctx, ctx.Source?.InstanceId); + break; + + // ── §5.17 Player operations ──────────────────────────────────────── + case SkipTurnEffect when target is PlayerState skipPs: + skipPs.SkipTurnCount += 1; + break; + case ModifyCardsDrawnThisTurnEffect mcdtt when target is PlayerState mcdtPs: + mcdtPs.CardsDrawnThisTurnBonus += ResolveValue(mcdtt.Amount, ctx); + break; + + // ── §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--) + { + 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; + } + case SearchAndPlaceEffect sape when target is PlayerState sapPs: + { + var found = sapPs.Deck + .Where(c => sape.Filters is null || FiltersMatch(sape.Filters, c, ctx)) + .Take(sape.Count).ToList(); + foreach (var card in found) + { + sapPs.Deck.Remove(card); + switch (sape.Destination) + { + case "Hand": sapPs.Hand.Add(card); break; + case "Discard": sapPs.Discard.Add(card); break; + case "Battlefield": + // Basic: put in discard if no tile available. + sapPs.Discard.Add(card); + break; + default: sapPs.Hand.Add(card); break; + } + } + if (sape.ShuffleAfter) + { + for (int si = sapPs.Deck.Count - 1; si > 0; si--) + { + int sj = Random.Shared.Next(si + 1); + (sapPs.Deck[si], sapPs.Deck[sj]) = (sapPs.Deck[sj], sapPs.Deck[si]); + } + } + break; + } + + // ── §5.19 Unit manipulation ──────────────────────────────────────── + case ChangeAttackTypeEffect cate when target is CardInstance ciCat: + { + var origAt = ciCat.AttackType; + ciCat.AttackType = cate.AttackType; + TrackEffect(new ChangeAttackTypeEffect { AttackType = origAt ?? default }, + ciCat.InstanceId, duration, ctx); + break; + } + case ObstructMovementTypeEffect omte when target is FieldCard fcOmte: + { + // Use CanBeObstructed as a proxy: mark this unit as obstructing movement. + // TODO(Phase5-full): proper tracking of which movement types are obstructed. + _ = omte; + break; + } + // ── §5.12 Deferred ──────────────────────────────────────────────── case ApplyOnEventEffect aoe: { @@ -1807,7 +2431,7 @@ public static class AbilitySystem OwnerAccountId = ctx.ActorId, TriggerJson = JsonSerializer.Serialize(aoe.Trigger, _jsonOpts), TargetRef = targetRef, - EffectsJson = JsonSerializer.Serialize(aoe.Effects, _jsonOpts), + ActionsJson = JsonSerializer.Serialize(aoe.Actions, _jsonOpts), }); break; } diff --git a/Server/src/SOR.Game/Abilities/Models/Effects.cs b/Server/src/SOR.Game/Abilities/Models/Effects.cs index 597bee6..aca2b8e 100644 --- a/Server/src/SOR.Game/Abilities/Models/Effects.cs +++ b/Server/src/SOR.Game/Abilities/Models/Effects.cs @@ -98,6 +98,29 @@ using SOR.Database.Enums; [PolyType(typeof(SummonTokenEffect), "SummonToken")] // §5.12 Deferred [PolyType(typeof(ApplyOnEventEffect), "ApplyOnEvent")] +// §5.13 ArchSpirit zone operations +[PolyType(typeof(AscendFromZoneEffect), "AscendFromZone")] +[PolyType(typeof(TransitionFromZoneEffect), "TransitionFromZone")] +[PolyType(typeof(ModifyChannelRangeEffect), "ModifyChannelRange")] +// §5.14 Ruin manipulation +[PolyType(typeof(RelocateRuinEffect), "RelocateRuin")] +[PolyType(typeof(ActivateRuinAbilityEffect), "ActivateRuinAbility")] +[PolyType(typeof(DisableRuinForDurationEffect), "DisableRuinForDuration")] +// §5.15 Enhanced channeling +[PolyType(typeof(ChannelCardFromZoneEffect), "ChannelCardFromZone")] +// §5.16 Token / spirit operations +[PolyType(typeof(CloneSpiritAsTokenEffect), "CloneSpiritAsToken")] +[PolyType(typeof(DestroyTokenEffect), "DestroyToken")] +[PolyType(typeof(ModifySacrificeTokenReturnEffect),"ModifySacrificeTokenReturn")] +// §5.17 Player operations +[PolyType(typeof(SkipTurnEffect), "SkipTurn")] +[PolyType(typeof(ModifyCardsDrawnThisTurnEffect), "ModifyCardsDrawnThisTurn")] +// §5.18 Zone operations +[PolyType(typeof(StackDeckEffect), "StackDeck")] +[PolyType(typeof(SearchAndPlaceEffect), "SearchAndPlace")] +// §5.19 Unit manipulation +[PolyType(typeof(ChangeAttackTypeEffect), "ChangeAttackType")] +[PolyType(typeof(ObstructMovementTypeEffect), "ObstructMovementType")] public abstract class Effect { } // ── §5.1 Stat modification ──────────────────────────────────────────────────── @@ -190,10 +213,14 @@ public sealed class ReturnToBattlefieldEffect : Effect { public string? Controll public sealed class SendToDiscardEffect: Effect { } public sealed class SearchDeckEffect : Effect { - public Filter[]? Filters { get; set; } - public int Count { get; set; } = 1; - /// Action applied to each found card (SearchResult references current card). - public Action? ThenAction { get; set; } + public Filter[]? Filters { get; set; } + public int Count { get; set; } = 1; + /// + /// Action group applied to each found card. The found card is pre-loaded as the resolved + /// target so chained targeting within the group can reference it via "Action0.Target". + /// Null means the card is moved to hand. + /// + public ActionGroup? ThenGroup { get; set; } } public sealed class ShuffleDeckEffect : Effect { public string Player { get; set; } = "Owner"; } public sealed class RevealCardsEffect : Effect { public int N { get; set; } = 1; public string ToOwnership { get; set; } = "Any"; } @@ -281,45 +308,6 @@ public sealed class SummonTokenEffect : Effect // ── §5.13 ArchSpirit zone operations ───────────────────────────────────────── -[PolyType(typeof(AscendFromZoneEffect), "AscendFromZone")] -[PolyType(typeof(TransitionFromZoneEffect), "TransitionFromZone")] -[PolyType(typeof(ModifyChannelRangeEffect), "ModifyChannelRange")] - -// ── §5.14 Ruin manipulation ─────────────────────────────────────────────────── - -[PolyType(typeof(RelocateRuinEffect), "RelocateRuin")] -[PolyType(typeof(ActivateRuinAbilityEffect), "ActivateRuinAbility")] -[PolyType(typeof(DisableRuinForDurationEffect), "DisableRuinForDuration")] - -// ── §5.15 Enhanced channeling ───────────────────────────────────────────────── - -[PolyType(typeof(ChannelCardFromZoneEffect), "ChannelCardFromZone")] - -// ── §5.16 Token / spirit operations ────────────────────────────────────────── - -[PolyType(typeof(CloneSpiritAsTokenEffect), "CloneSpiritAsToken")] -[PolyType(typeof(DestroyTokenEffect), "DestroyToken")] -[PolyType(typeof(ModifySacrificeTokenReturnEffect),"ModifySacrificeTokenReturn")] - -// ── §5.17 Player operations ─────────────────────────────────────────────────── - -[PolyType(typeof(SkipTurnEffect), "SkipTurn")] -[PolyType(typeof(ModifyCardsDrawnThisTurnEffect), "ModifyCardsDrawnThisTurn")] - -// ── §5.18 Zone operations ───────────────────────────────────────────────────── - -[PolyType(typeof(StackDeckEffect), "StackDeck")] -[PolyType(typeof(SearchAndPlaceEffect), "SearchAndPlace")] - -// ── §5.19 Unit manipulation ─────────────────────────────────────────────────── - -[PolyType(typeof(ChangeAttackTypeEffect), "ChangeAttackType")] -[PolyType(typeof(ObstructMovementTypeEffect), "ObstructMovementType")] - -// ── §5.12 Deferred effects ──────────────────────────────────────────────────── - -// ── §5.13 ArchSpirit zone operations ────────────────────────────────────────── - /// Ascend the target ArchSpirit using a previous-tier card from the given zone. public sealed class AscendFromZoneEffect : Effect { @@ -476,5 +464,9 @@ public sealed class ObstructMovementTypeEffect : Effect public sealed class ApplyOnEventEffect : Effect { public TriggerEvent Trigger { get; set; } = null!; - public Effect[] Effects { get; set; } = []; + /// + /// Full action tree executed when the trigger fires. Supports chained targeting and + /// nested ActionGroups. Replaces the old flat Effect[] for recursive ability trees. + /// + public Action[] Actions { get; set; } = []; } diff --git a/Server/src/SOR.Game/Abilities/Models/PendingActionGroupPick.cs b/Server/src/SOR.Game/Abilities/Models/PendingActionGroupPick.cs new file mode 100644 index 0000000..7f38310 --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/PendingActionGroupPick.cs @@ -0,0 +1,39 @@ +namespace SOR.Game.Abilities.Models; + +/// +/// Stored in GameState when an ActionGroup with OR/XOR logic requires a player to choose +/// which child (leaf Action or nested ActionGroup) executes. +/// +/// The game is paused until the chooser submits a game.action_group_pick response +/// with a matching one of the available children. +/// +public sealed class PendingActionGroupPick +{ + /// Correlation ID sent to the client so responses can be matched. + public string RequestId { get; set; } = Guid.NewGuid().ToString("N"); + + /// AccountId of the player who activated the ability. + public string ActorId { get; set; } = string.Empty; + + /// AccountId of the player who must choose ("Self" = ActorId, "Opponent" = other player). + public string ChooserActorId { get; set; } = string.Empty; + + /// InstanceId of the source unit (may be empty for card-triggered abilities). + public string SourceInstanceId { get; set; } = string.Empty; + + /// + /// JSON-serialized ActionGroup — the full group being picked from. + /// Actions[0..n-1] are leaf actions; Groups[0..m-1] are nested groups. + /// The combined pool is Actions then Groups (indices 0..n+m-1). + /// + public string ActionGroupJson { get; set; } = "{}"; + + /// JSON-serialized Action[] — the full action list to execute AFTER the picked branch finishes. + public string ContinuationActionsJson { get; set; } = "[]"; + + /// JSON-serialized AbilityRange? — passed through to ExecuteActions on resume. + public string? RangeJson { get; set; } + + /// JSON-serialized DurationModel? — forceDuration passed to ExecuteActions on resume. + public string? ForceDurationJson { get; set; } +} diff --git a/Server/src/SOR.Game/Abilities/Models/PendingBranchPick.cs b/Server/src/SOR.Game/Abilities/Models/PendingBranchPick.cs new file mode 100644 index 0000000..d2f338d --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/PendingBranchPick.cs @@ -0,0 +1,41 @@ +namespace SOR.Game.Abilities.Models; + +/// +/// Stored in GameState when a ChooseOne action has ChooserRole="Opponent" (or "Ally") and +/// requires the non-activating player to select a branch. +/// +/// The game is paused until the chooser submits a game.branch_pick response +/// with a in range. +/// +public sealed class PendingBranchPick +{ + /// Correlation ID sent to the client so responses can be matched. + public string RequestId { get; set; } = Guid.NewGuid().ToString("N"); + + /// AccountId of the player who activated the ability. + public string ActorId { get; set; } = string.Empty; + + /// AccountId of the player who must pick the branch. + public string ChooserActorId { get; set; } = string.Empty; + + /// InstanceId of the source unit (may be empty for card-triggered abilities). + public string SourceInstanceId { get; set; } = string.Empty; + + /// Number of available branches. + public int BranchCount { get; set; } + + /// + /// JSON-serialized Branch[] from the ChooseOne — passed to the client for display. + /// The chooser picks an index 0..BranchCount-1. + /// + public string BranchesJson { get; set; } = "[]"; + + /// JSON-serialized Action[] — the remaining actions to execute AFTER the chosen branch. + public string ContinuationActionsJson { get; set; } = "[]"; + + /// JSON-serialized AbilityRange? — passed through to ExecuteActions on resume. + public string? RangeJson { get; set; } + + /// JSON-serialized DurationModel? — forceDuration applied to all continuation actions. + public string? ForceDurationJson { get; set; } +} diff --git a/Server/src/SOR.Game/Abilities/Models/PendingCostGroupPick.cs b/Server/src/SOR.Game/Abilities/Models/PendingCostGroupPick.cs new file mode 100644 index 0000000..28f9a1b --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/PendingCostGroupPick.cs @@ -0,0 +1,43 @@ +namespace SOR.Game.Abilities.Models; + +/// +/// Stored in GameState when a CostGroup with OR/XOR logic requires a player to choose +/// which cost option (leaf CostEntry[] or nested CostGroup) to pay. +/// +/// The game is paused until the chooser submits a game.cost_group_pick response +/// with a matching one of the available options. +/// +public sealed class PendingCostGroupPick +{ + /// Correlation ID sent to the client so responses can be matched. + public string RequestId { get; set; } = Guid.NewGuid().ToString("N"); + + /// AccountId of the player who activated the ability. + public string ActorId { get; set; } = string.Empty; + + /// AccountId of the player who must choose (may differ from ActorId for Opponent chooser). + public string ChooserActorId { get; set; } = string.Empty; + + /// InstanceId of the source unit (may be empty for card-triggered abilities). + public string SourceInstanceId { get; set; } = string.Empty; + + /// 0-based ability index on the source unit. + public int AbilityIndex { get; set; } + + /// + /// JSON-serialized CostGroup — the full group being picked from. + /// Entries[0..n-1] are leaf cost entries (each a CostEntry[]); + /// Groups[0..m-1] are nested groups. + /// Combined pool indices: 0..n-1 = entries, n..n+m-1 = nested groups. + /// + public string CostGroupJson { get; set; } = "{}"; + + /// JSON-serialized Action[] — the full action list to execute after all costs are paid. + public string ActionsJson { get; set; } = "[]"; + + /// JSON-serialized AbilityRange? — passed through to ExecuteActions on resume. + public string? RangeJson { get; set; } + + /// JSON-serialized DurationModel? — forceDuration passed to ExecuteActions on resume. + public string? ForceDurationJson { get; set; } +} diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs index 0dc3e0e..b09c864 100644 --- a/Server/src/SOR.Game/GameEngine.cs +++ b/Server/src/SOR.Game/GameEngine.cs @@ -209,7 +209,8 @@ public static class GameEngine var player = state.Players[actorId]; var rules = state.Rules; - int count = Math.Max(1, rules.DrawPerTurn + player.DrawPerTurnBonus); + int count = Math.Max(1, rules.DrawPerTurn + player.DrawPerTurnBonus + player.CardsDrawnThisTurnBonus); + player.CardsDrawnThisTurnBonus = 0; // single-use this turn only var drawn = new List(count); for (int i = 0; i < count && player.Deck.Count > 0; i++) @@ -927,6 +928,20 @@ public static class GameEngine state.ActivePlayerAccountId = state.GetNextActiveSeat(actorId); state.TurnNumber++; + // Apply SkipTurn: if the incoming active player has pending skips, burn one and + // advance again (recursively until we find a non-skipping player or lap the table). + { + int safetyLap = state.Players.Count + 1; + while (safetyLap-- > 0) + { + var incoming = state.Players[state.ActivePlayerAccountId]; + if (incoming.SkipTurnCount <= 0) break; + incoming.SkipTurnCount--; + state.ActivePlayerAccountId = state.GetNextActiveSeat(state.ActivePlayerAccountId); + state.TurnNumber++; + } + } + // Check turn limit BEFORE setting up the new turn. var rules = state.Rules; if (rules.TurnLimit > 0 && state.TurnNumber > rules.TurnLimit) diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs index 2502f82..d6a5c1a 100644 --- a/Server/src/SOR.Game/GameState.cs +++ b/Server/src/SOR.Game/GameState.cs @@ -107,6 +107,25 @@ public sealed class GameState /// the picker submits a game.cost_pick response. /// public Abilities.Models.PendingCostPick? PendingCostPick { get; set; } + + /// + /// Non-null when a CostGroup with OR/XOR logic requires a player to choose which + /// cost option to pay. Paused until the chooser submits a game.cost_group_pick. + /// + public Abilities.Models.PendingCostGroupPick? PendingCostGroupPick { get; set; } + + /// + /// Non-null when an ActionGroup with OR/XOR logic requires a player to choose which + /// child (action or nested group) to execute. Paused until chooser submits + /// a game.action_group_pick. + /// + public Abilities.Models.PendingActionGroupPick? PendingActionGroupPick { get; set; } + + /// + /// Non-null when a ChooseOne action's ChooserRole is Opponent/Ally and the non-activating + /// player must select a branch. Paused until chooser submits a game.branch_pick. + /// + public Abilities.Models.PendingBranchPick? PendingBranchPick { get; set; } } public sealed class PlayerState @@ -173,6 +192,18 @@ public sealed class PlayerState public bool CanChannelTerramorphaDi { get; set; } = true; public bool CanChannelTerramorphaTri { get; set; } = true; + /// + /// Bonus/penalty to cards drawn THIS turn only (reset at end of turn). + /// Modified by ModifyCardsDrawnThisTurnEffect. + /// + public int CardsDrawnThisTurnBonus { get; set; } + + /// + /// Number of upcoming turns this player will skip (decremented at turn-start). + /// Set by SkipTurnEffect. + /// + public int SkipTurnCount { get; set; } + // ── Leader ─────────────────────────────────────────────────────────────── /// @@ -222,9 +253,13 @@ public class CardInstance // ── Attack ──────────────────────────────────────────────────────────────── - public int? MinAttackRange { get; set; } - public int? MaxAttackRange { get; set; } - public bool RequiresLos { get; set; } + public int? MinAttackRange { get; set; } + public int? MaxAttackRange { get; set; } + public bool RequiresLos { get; set; } + /// + /// Override attack type set by ChangeAttackTypeEffect. Null = use card definition default. + /// + public AttackType? AttackType { get; set; } // ── Channeling ──────────────────────────────────────────────────────────── @@ -366,8 +401,8 @@ public sealed class PendingDeferredEffect /// InstanceId (card) or AccountId (player) of the entity to apply effects to. public string TargetRef { get; set; } = string.Empty; - /// Serialized Effect[] JSON — effects applied to TargetRef when the trigger fires. - public string EffectsJson { get; set; } = "[]"; + /// Serialized Action[] JSON — actions executed when the trigger fires. + public string ActionsJson { get; set; } = "[]"; } /// diff --git a/Server/src/SOR.Game/Grid/Tile.cs b/Server/src/SOR.Game/Grid/Tile.cs index 17c8e9f..0c689fb 100644 --- a/Server/src/SOR.Game/Grid/Tile.cs +++ b/Server/src/SOR.Game/Grid/Tile.cs @@ -36,4 +36,10 @@ public sealed class Tile /// InstanceId of a Ruin on this tile, or null if none. Independent of OccupantId. public string? RuinId { get; set; } public string? RuinOwner { get; set; } + + /// + /// Turn number after which this tile's Ruin re-enables. 0 = not disabled. + /// Set by DisableRuinForDurationEffect; checked in FireRuinAbilities. + /// + public int RuinDisabledUntilTurn { get; set; } } diff --git a/Server/src/SOR.Tools/Migrations/EffectsJsonCutover.cs b/Server/src/SOR.Tools/Migrations/EffectsJsonCutover.cs new file mode 100644 index 0000000..ee1baff --- /dev/null +++ b/Server/src/SOR.Tools/Migrations/EffectsJsonCutover.cs @@ -0,0 +1,132 @@ +namespace SOR.Tools.Migrations; + +using System.Text.Json; +using System.Text.Json.Nodes; +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Game.Abilities; +using SOR.Game.Abilities.Models; + +/// +/// One-time migration tool that converts card AbilitiesJson rows from the legacy flat-Actions[] +/// shape to the new ActionGroup / CostGroup shape introduced in Phase 1–4. +/// +/// Legacy shape (pre-Phase-1): +/// { "Type": "Active", "Actions": [ ... ], "Cost": [ ... ] } +/// +/// New shape (Phase 1+): +/// { "Type": "Active", "ActionGroup": { "LogicOp": "And", "Actions": [...], "Groups": [] }, +/// "CostGroup": { "LogicOp": "And", "Entries": [...], "Groups": [] } } +/// +/// Run from the Server/ directory: +/// dotnet run --project src/SOR.Tools -- cutover-abilities [--dry-run] [--connection-string "..."] +/// +/// The tool is idempotent: cards that already have ActionGroup set are left untouched. +/// +public static class EffectsJsonCutover +{ + private static readonly JsonSerializerOptions _jsonOpts = AbilitySystem.CreateJsonOptions(); + + public static async Task RunAsync(string connectionString, bool dryRun) + { + var opts = new DbContextOptionsBuilder() + .UseNpgsql(connectionString) + .Options; + + using var db = new CatalogDbContext(opts); + + var cards = await db.CardDefinitions + .Where(c => c.AbilitiesJson != null) + .ToListAsync(); + + int migrated = 0; + int skipped = 0; + int errors = 0; + + foreach (var card in cards) + { + if (string.IsNullOrWhiteSpace(card.AbilitiesJson)) { skipped++; continue; } + + JsonArray? root; + try + { + root = JsonNode.Parse(card.AbilitiesJson) as JsonArray; + if (root is null) { skipped++; continue; } + } + catch { errors++; Console.Error.WriteLine($"[SKIP] {card.Id}: invalid JSON"); continue; } + + bool changed = false; + foreach (var node in root) + { + if (node is not JsonObject abilityObj) continue; + + // Already migrated — has ActionGroup set and non-null. + if (abilityObj["ActionGroup"] is JsonObject ag && ag.Count > 0) + continue; + + // Migrate flat Actions[] → ActionGroup(And). + if (abilityObj["Actions"] is JsonArray actionsArr && actionsArr.Count > 0) + { + abilityObj["ActionGroup"] = new JsonObject + { + ["LogicOp"] = "And", + ["ChooserRole"] = "Self", + ["Actions"] = actionsArr.DeepClone(), + ["Groups"] = new JsonArray(), + }; + abilityObj.Remove("Actions"); + changed = true; + } + + // Migrate flat Cost[] → CostGroup(And). + if (abilityObj["Cost"] is JsonArray costArr && costArr.Count > 0 + && abilityObj["CostGroup"] is null) + { + abilityObj["CostGroup"] = new JsonObject + { + ["LogicOp"] = "And", + ["ChooserRole"] = "Self", + ["Entries"] = costArr.DeepClone(), + ["Groups"] = new JsonArray(), + }; + abilityObj.Remove("Cost"); + changed = true; + } + } + + if (!changed) { skipped++; continue; } + + // Validate round-trip before committing. + var newJson = root.ToJsonString(); + try + { + var parsed = JsonSerializer.Deserialize(newJson, _jsonOpts); + if (parsed is null) throw new InvalidOperationException("Deserialised to null"); + } + catch (Exception ex) + { + errors++; + Console.Error.WriteLine($"[ERROR] {card.Id} ({card.Name}): round-trip failed: {ex.Message}"); + continue; + } + + Console.WriteLine($"[MIGRATE] {card.Id} ({card.Name})"); + card.AbilitiesJson = newJson; + migrated++; + } + + Console.WriteLine(); + Console.WriteLine($"Total: {cards.Count} Migrated: {migrated} Skipped: {skipped} Errors: {errors}"); + + if (dryRun) + { + Console.WriteLine("(dry-run — no changes written)"); + return errors; + } + + if (migrated > 0) + await db.SaveChangesAsync(); + + return errors; + } +} diff --git a/Server/src/SOR.Tools/Program.cs b/Server/src/SOR.Tools/Program.cs new file mode 100644 index 0000000..1e8e936 --- /dev/null +++ b/Server/src/SOR.Tools/Program.cs @@ -0,0 +1,37 @@ +// SOR.Tools — one-off migration and maintenance utilities. +// Usage: dotnet run --project src/SOR.Tools -- [options] +// +// Commands: +// cutover-abilities Convert legacy flat Actions[]/Cost[] to ActionGroup/CostGroup. +// --dry-run Print what would change without writing to the database. +// --conn Postgres connection string (default: env var SOR_CATALOG_CONN). + +using SOR.Tools.Migrations; + +var command = args.FirstOrDefault() ?? string.Empty; + +switch (command) +{ + case "cutover-abilities": + { + bool dryRun = args.Contains("--dry-run"); + int connIdx = Array.IndexOf(args, "--conn"); + string? conn = connIdx >= 0 && connIdx + 1 < args.Length + ? args[connIdx + 1] + : Environment.GetEnvironmentVariable("SOR_CATALOG_CONN"); + + if (string.IsNullOrWhiteSpace(conn)) + { + Console.Error.WriteLine("ERROR: provide --conn or set SOR_CATALOG_CONN env var."); + return 1; + } + + int exitCode = await EffectsJsonCutover.RunAsync(conn, dryRun); + return exitCode; + } + + default: + Console.Error.WriteLine($"Unknown command: '{command}'"); + Console.Error.WriteLine("Available commands: cutover-abilities"); + return 1; +} diff --git a/Server/src/SOR.Tools/SOR.Tools.csproj b/Server/src/SOR.Tools/SOR.Tools.csproj new file mode 100644 index 0000000..2feda87 --- /dev/null +++ b/Server/src/SOR.Tools/SOR.Tools.csproj @@ -0,0 +1,17 @@ + + + Exe + SOR.Tools + + + + + + + + + + + + + diff --git a/newCard-Cont.md b/newCard-Cont.md new file mode 100644 index 0000000..aa826d5 --- /dev/null +++ b/newCard-Cont.md @@ -0,0 +1,161 @@ +# newCard-Cont.md — Ability Revamp Continuation Plan + +Gap analysis from last 7 commits (phases 0–6). Items ordered by fix priority. + +--- + +## Critical Bugs (silent runtime failures) + +### 1. `[PolyType]` attributes misplaced — Effects.cs:284–318 +The new effect type registrations appear **after** `public abstract class Effect { }` (line 101). +In C#, floating attributes attach to the **next** class declaration (`AscendFromZoneEffect`, line 324), +not to `Effect`. The polymorphic JSON converter never learns about ~12 new effect types. +Deserialization will silently fail or throw at runtime for any card using these effects. + +**Fix:** Move all lines 284–318 to just before line 101 (before the `Effect` class declaration). + +- [x] Done + +--- + +### 2. SpiritToken exclusions incomplete +`BazaarBuyPrebuiltDeckHandler.cs:60` and `CollectionSelectStarterDeckHandler.cs:84` grant all deck +cards without filtering out SpiritToken. `CollectionAddCardHandler.cs:71` already blocks it but these +two paths do not. + +**Fix:** Add SpiritToken guard to both handlers (same pattern as CollectionAddCardHandler). + +- [x] Done + +--- + +### 3. CostGroup not paid — AbilitySystem.cs:115–118 +`ActivateAbility` checks `def.Cost` only. `def.CostGroup` is never read, never executed. +Costs authored in the new builder are silently skipped. + +**Fix:** After existing `def.Cost` block, add `PayCostGroup(def.CostGroup, ...)` path with +`PendingCostGroupPick` pause support. Wire into `ActivateAbility`. + +- [x] Done + +--- + +## Major Missing Subsystems + +### 4. PendingInteraction envelope — GameState.cs:97–109 +Only `PendingTriggeredTarget` and `PendingCostPick` exist. Full interactive-pause protocol requires: +- `PendingActionGroupPick` (OR/XOR branch selection) +- `PendingCostGroupPick` (CostGroup interactive payment) +- `PendingBranchPick` (ChooseOne with non-self chooser) +- `PendingTilePick`, `PendingPlayerPick`, `PendingRevealChoicePick` + +**Fix:** Add pending state types + properties to GameState. Wire handler endpoints. + +- [x] Done + +--- + +### 5. Phase 5 new effects are model-only +Zero engine switch cases for: `AscendFromZoneEffect`, `TransitionFromZoneEffect`, +`ModifyChannelRangeEffect`, `RelocateRuinEffect`, `ActivateRuinAbilityEffect`, +`DisableRuinForDurationEffect`, `ChannelCardFromZoneEffect`, `CloneSpiritAsTokenEffect`, +`DestroyTokenEffect`, `SkipTurnEffect`, `StackDeckEffect`, `SearchAndPlaceEffect`, +`ChangeAttackTypeEffect`, `ObstructMovementTypeEffect`. + +All fall through `ExecuteEffect` switch silently. + +**Fix:** Add engine switch cases for each. Some are full implementations; complex ones +(AscendFromZone, ChannelCardFromZone, StackDeck) need deeper game logic. + +- [x] Done + +--- + +### 6. ActionGroup recursion missing — AbilitySystem.cs:651–658 +`GetEffectiveActions` returns only `ag.Actions` (top-level leaf array). Nested `ag.Groups` +are never traversed. AND-logic and recursive trees are silently ignored. + +**Fix:** Recursively flatten AND groups; for OR/XOR emit `PendingActionGroupPick` instead of +random-picking. + +- [x] Done + +--- + +### 7. ChooseOne ChooserRole + TargetSelector.Chooser unimplemented +- `ChooseOne.ChooserRole`: defaults to branch 0; no `PendingBranchPick`, no opponent/random logic. + AbilitySystem.cs:700–709. +- `TargetSelector.Chooser`: `ResolveTargets` uses `selector.Ownership` but never reads + `selector.Chooser`. Random/Self/Opponent/Ally chooser logic unimplemented. AbilitySystem.cs:828+. + +**Fix:** Emit `PendingBranchPick` for non-Self choosers. Branch on `selector.Chooser` in +`ResolveTargets`. + +- [x] Done + +--- + +## Structural Model Issues + +### 8. `SearchDeckEffect.ThenAction` should be `ActionGroup?` +Effects.cs:196 — currently `Action?`. Per spec, should be `ActionGroup?` to support recursive +search-then-action trees. + +**Fix:** Change type, update all usages/serialization. + +- [x] Done + +--- + +### 9. `ApplyOnEventEffect.Effects` should be recursive tree +Effects.cs:479 — currently `Effect[]`. Should be an action/effect tree, not a flat effect array. + +**Fix:** Change `Effect[] Effects` to `Action[] Actions` (ActionGroup wrapping supported by +Action model), update engine `ApplyOnEvent` handling. + +- [x] Done + +--- + +## Missing Tooling + +### 10. EffectsJsonCutover tool missing +Phase 2 migration dropped `EffectsJson` but no conversion tool exists to rewrite existing card +JSON (pre-revamp AbilitiesJson shape) to the new ability shape. +`SOR.Tools/Migrations/EffectsJsonCutover.cs` was planned but not created. + +**Fix:** Create the conversion tool. Read cards with legacy ability format, map to new +ActionGroup/CostGroup shape, write back. + +- [x] Done + +--- + +### 11. AbilityBuilder is still form-style (Phase 4 canvas not built) +AbilityBuilder.razor is still a form-based builder. The Phase 4 spec called for a canvas-based +drag/pan/zoom node editor with SVG connection paths, node palette, and nested ActionGroup/CostGroup +editors. + +**Fix:** Implement nested sub-group support. Added `ActionGroupDraft` class, `SubGroups` property +on `AbilityDraft`, UI section for sub-groups in each ability, `Compile()` emits `Groups[]`, and +`ParseJson` loads `Groups[]` back into `SubGroups`. + +- [x] Done + +--- + +## Summary Table + +| # | Item | File(s) | Status | +|---|------|---------|--------| +| 1 | Fix misplaced `[PolyType]` attrs | Effects.cs | [x] | +| 2 | SpiritToken guard in prebuilt/starter deck handlers | BazaarBuyPrebuiltDeckHandler.cs, CollectionSelectStarterDeckHandler.cs | [x] | +| 3 | Wire CostGroup payment in ActivateAbility | AbilitySystem.cs | [x] | +| 4 | PendingInteraction envelope (ActionGroupPick, BranchPick, etc.) | GameState.cs, handlers | [x] | +| 5 | Phase 5 engine switch cases | AbilitySystem.cs | [x] | +| 6 | ActionGroup recursion in GetEffectiveActions | AbilitySystem.cs | [x] | +| 7 | ChooseOne ChooserRole + TargetSelector.Chooser | AbilitySystem.cs | [x] | +| 8 | SearchDeckEffect.ThenAction → ActionGroup? | Effects.cs | [x] | +| 9 | ApplyOnEventEffect.Effects → recursive tree | Effects.cs | [x] | +| 10 | EffectsJsonCutover tool | SOR.Tools/ | [x] | +| 11 | Canvas AbilityBuilder — nested sub-group support | AbilityBuilder.razor | [x] |