From 0e85441fa1b7e9cf3c5fe157d50f52a6ab4096f8 Mon Sep 17 00:00:00 2001 From: dingo Date: Tue, 21 Apr 2026 07:34:17 -0400 Subject: [PATCH] feat(phase10): ChannelCardFromZone, ObstructMovementType, and pause-model completions - Implement ChannelCardFromZoneEffect: zone lookup, dest-player resolution (Self/Target/Opponent/Ally/Random/Choice), channel-range tile selection, affinity check, cost deduction, KeepInZone, TargetTile pause, board placement with aura/passive hooks and Channeled trigger - Add PendingPlayerPick.EffectType="ChannelCardFromZone" dispatch in ResumePlayerPick: random-tile path + chained PendingTilePick for TargetTile=true - Add ResumeTilePick case "ChannelCardFromZone": place card at chosen tile under DestPlayerAccountId, affinity/cost/KeepInZone-aware - Implement ObstructMovementTypeEffect: stores ActiveEffect marker; ApplyReversal is no-op (duration:null guard); BuildBlockedSet extended via AbilitySystem.GetUnitsObstructingMovementType to honour obstructors for pathfinding (e.g. Walk unit blocking Flight paths) - Add PendingTilePick.DestPlayerAccountId and .EffectJson fields - Add PendingPlayerPick.EffectJson field - Thread ctx.ContinuationActions + ctx.ActivationRange through AbilityContext so ExecuteEffect can populate pause models without an extra method parameter Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../src/SOR.Game/Abilities/AbilityContext.cs | 13 + .../src/SOR.Game/Abilities/AbilitySystem.cs | 786 +++++++++++++++++- .../Models/PendingActionGroupPick.cs | 9 +- .../Abilities/Models/PendingPlayerPick.cs | 12 + .../Abilities/Models/PendingTargetPick.cs | 42 + .../Abilities/Models/PendingTilePick.cs | 19 + Server/src/SOR.Game/GameEngine.cs | 20 +- Server/src/SOR.Game/GameMessages.cs | 39 + Server/src/SOR.Game/GameState.cs | 10 +- .../Handlers/GamePlayerPickHandler.cs | 56 ++ .../Handlers/GameTargetPickHandler.cs | 59 ++ .../SOR.Game/Handlers/GameTilePickHandler.cs | 57 ++ Server/src/SOR.Game/ServiceRegistration.cs | 9 + 13 files changed, 1102 insertions(+), 29 deletions(-) create mode 100644 Server/src/SOR.Game/Abilities/Models/PendingTargetPick.cs create mode 100644 Server/src/SOR.Game/Handlers/GamePlayerPickHandler.cs create mode 100644 Server/src/SOR.Game/Handlers/GameTargetPickHandler.cs create mode 100644 Server/src/SOR.Game/Handlers/GameTilePickHandler.cs diff --git a/Server/src/SOR.Game/Abilities/AbilityContext.cs b/Server/src/SOR.Game/Abilities/AbilityContext.cs index 8a9557a..ebdac81 100644 --- a/Server/src/SOR.Game/Abilities/AbilityContext.cs +++ b/Server/src/SOR.Game/Abilities/AbilityContext.cs @@ -26,6 +26,19 @@ public sealed class AbilityContext /// Optional payload from the triggering event — available to Triggered ability actions. /// public TriggerEventData? EventData { get; init; } + + /// + /// Actions remaining after the current one in the parent ExecuteActions loop. + /// Set by ExecuteSingleAction so that effect-level pauses (ChannelCardFromZone, etc.) + /// can store the full continuation for later resume. + /// + public Models.Action[] ContinuationActions { get; set; } = []; + + /// + /// Activation range propagated from the top-level ExecuteActions call. + /// Available to ExecuteEffect when it needs to store a continuation pause. + /// + public AbilityRange? ActivationRange { get; set; } } /// diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index e38cd5a..ac8d7af 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -914,11 +914,28 @@ public static class AbilitySystem { // AND: run leaves then recurse into nested groups, flattening all. var all = new List(ag.Actions); - foreach (var child in ag.Groups) + for (int gi = 0; gi < ag.Groups.Length; gi++) { - var childActions = ResolveActionGroup(child, ctx, abilityIndex, range, + var childActions = ResolveActionGroup(ag.Groups[gi], ctx, abilityIndex, range, forceDuration, continuationActions); - if (childActions is null) return null; // child emitted pending pick + if (childActions is null) + { + // Child emitted PendingActionGroupPick. Patch it to include: + // - `all` (already-flattened preceding actions) prepended to continuation + // - remaining sibling groups stored so ResumeActionGroupPick can process them + if (ctx.State.PendingActionGroupPick is { } pend) + { + var existingCont = JsonSerializer.Deserialize( + pend.ContinuationActionsJson, _jsonOpts) ?? []; + pend.ContinuationActionsJson = JsonSerializer.Serialize( + all.Concat(existingCont).ToArray(), _jsonOpts); + + var remaining = ag.Groups.Skip(gi + 1).ToArray(); + if (remaining.Length > 0) + pend.RemainingGroupsJson = JsonSerializer.Serialize(remaining, _jsonOpts); + } + return null; + } all.AddRange(childActions); } return all.ToArray(); @@ -1008,7 +1025,43 @@ public static class AbilitySystem { chosen = ResolveActionGroup(ag.Groups[choiceIndex - leafCount], ctx, abilityIndex: 0, range, forceDuration, continuation); - if (chosen is null) return state; // nested group triggered another pick + if (chosen is null) + { + // Nested group triggered another pick — prepend any chosen-leaf prefix. + return state; + } + } + + // Process any remaining sibling groups (from a parent AND group that paused here). + ActionGroup[]? remainingGroups = pending.RemainingGroupsJson is not null + ? JsonSerializer.Deserialize(pending.RemainingGroupsJson, _jsonOpts) + : null; + + if (remainingGroups is { Length: > 0 }) + { + var tempList = new List(chosen); + for (int rgi = 0; rgi < remainingGroups.Length; rgi++) + { + var rgActions = ResolveActionGroup(remainingGroups[rgi], ctx, + abilityIndex: 0, range, forceDuration, continuation); + if (rgActions is null) + { + // This remaining group paused — prepend already-resolved actions. + if (ctx.State.PendingActionGroupPick is { } newPend) + { + var existingCont = JsonSerializer.Deserialize( + newPend.ContinuationActionsJson, _jsonOpts) ?? []; + newPend.ContinuationActionsJson = JsonSerializer.Serialize( + tempList.Concat(existingCont).ToArray(), _jsonOpts); + var afterThis = remainingGroups.Skip(rgi + 1).ToArray(); + newPend.RemainingGroupsJson = afterThis.Length > 0 + ? JsonSerializer.Serialize(afterThis, _jsonOpts) : null; + } + return state; + } + tempList.AddRange(rgActions); + } + chosen = tempList.ToArray(); } var allActions = chosen.Concat(continuation).ToArray(); @@ -1073,6 +1126,368 @@ public static class AbilitySystem return state; } + /// + /// Resumes an effect-level pause where the player must pick a specific tile + /// (e.g. CloneSpiritAsToken with DestinationScope=TargetTile). + /// Called by GameTilePickHandler. + /// + public static GameState ResumeTilePick( + GameState state, + string actorId, + string requestId, + Coord pickedTile) + { + var pending = state.PendingTilePick + ?? throw new GameException("NO_PENDING_TILE_PICK"); + + if (pending.RequestId != requestId) + throw new GameException("REQUEST_ID_MISMATCH"); + + var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId) + ? pending.ActorId + : pending.ChooserActorId; + if (expectedChooser != actorId) + throw new GameException("NOT_YOUR_TILE_PICK"); + + state.PendingTilePick = 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 }; + + switch (pending.EffectType) + { + case "CloneSpiritAsToken": + { + var spiritToClone = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == pending.TargetInstanceId); + if (spiritToClone is null || state.Board is null) break; + + var tile = state.Board.GetTile(pickedTile); + if (tile is null || !tile.IsEmpty) throw new GameException("INVALID_TILE"); + + 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, pickedTile); + state.Players[pending.ActorId].Field.Add(tokenField); + state.Board.PlaceUnit(pickedTile, tokenField.InstanceId, pending.ActorId); + EvaluateAurasOnEnter(state, tokenField.InstanceId); + ApplyPassivesForSource(state, tokenField.InstanceId, pending.ActorId); + ApplyPassivesToNewTarget(state, tokenField.InstanceId); + break; + } + + case "ChannelCardFromZone": + { + if (state.Board is null) break; + var board = state.Board; + + // Resolve card and dest player. + var ccCard = state.Players.Values + .SelectMany(p => p.Hand.Concat(p.Deck).Concat(p.Discard).Cast()) + .FirstOrDefault(c => c.InstanceId == pending.TargetInstanceId); + if (ccCard is null) break; + + var ccFromOwner = FindCardOwner(state, pending.TargetInstanceId); + if (ccFromOwner is null) break; + + var ccDestOwnerId = string.IsNullOrEmpty(pending.DestPlayerAccountId) + ? pending.ActorId + : pending.DestPlayerAccountId; + if (!state.Players.TryGetValue(ccDestOwnerId, out var ccDestPlayer)) break; + + var tile = board.GetTile(pickedTile); + if (tile is null || !tile.IsEmpty) throw new GameException("INVALID_TILE"); + + var ccze = pending.EffectJson is not null + ? JsonSerializer.Deserialize(pending.EffectJson, _jsonOpts) as ChannelCardFromZoneEffect + : null; + + // Affinity check. + if (ccze?.IgnoreAffinity != true && Enum.TryParse(ccCard.Affinity, out var tpAffinity)) + { + if (!AffinitySystem.IsAffinityValid(tile, tpAffinity)) + throw new GameException("INVALID_AFFINITY"); + } + + // Cost. + if (ccze?.IgnoreChannelCost != true) + { + ccDestPlayer.CurrentSp -= ccCard.SpCost; + ccDestPlayer.CurrentSt -= ccCard.StCost; + } + + // Remove from zone. + if (ccze?.KeepInZone != true) + RemoveFromZone(ccFromOwner, ccze?.Zone ?? "Hand", ccCard); + + // Place on board. + var tpField = GameEngine.ToFieldCardInternal(ccCard, pickedTile); + ccDestPlayer.Field.Add(tpField); + board.PlaceUnit(pickedTile, tpField.InstanceId, ccDestOwnerId); + + EvaluateAurasOnEnter(state, tpField.InstanceId); + ApplyPassivesForSource(state, tpField.InstanceId, ccDestOwnerId); + ApplyPassivesToNewTarget(state, tpField.InstanceId); + + FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.Channeled, + ActorId = ccDestOwnerId, + CardType = ccCard.CardType, + Data = new TriggerEventData { SourceId = tpField.InstanceId }, + }); + break; + } + } + + // Execute any continuation actions stored at pause time. + var continuation = JsonSerializer.Deserialize( + pending.ContinuationActionsJson, _jsonOpts) ?? []; + if (continuation.Length > 0) + { + 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; + ExecuteActions(continuation, ctx, clientTargets: null, activationRange: range, + forceDuration: forceDuration); + } + return state; + } + + /// + /// Resumes an effect-level pause where the player must pick another player + /// (e.g. ChannelCardFromZoneEffect with UnderControlOf=Choice). + /// Called by GamePlayerPickHandler. + /// + public static GameState ResumePlayerPick( + GameState state, + string actorId, + string requestId, + string pickedPlayerId) + { + var pending = state.PendingPlayerPick + ?? throw new GameException("NO_PENDING_PLAYER_PICK"); + + if (pending.RequestId != requestId) + throw new GameException("REQUEST_ID_MISMATCH"); + + var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId) + ? pending.ActorId + : pending.ChooserActorId; + if (expectedChooser != actorId) + throw new GameException("NOT_YOUR_PLAYER_PICK"); + + if (pending.ValidPlayerIds.Count > 0 && !pending.ValidPlayerIds.Contains(pickedPlayerId)) + throw new GameException("INVALID_PLAYER_PICK"); + + state.PendingPlayerPick = null; + + var ppSource = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); + var ppCtx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = ppSource }; + + // Dispatch per effect type. + switch (pending.EffectType) + { + case "ChannelCardFromZone": + { + if (!state.Players.TryGetValue(pickedPlayerId, out var ppDest)) break; + var ppBoard = state.Board; + if (ppBoard is null) break; + + var ppCard = state.Players.Values + .SelectMany(p => p.Hand.Concat(p.Deck).Concat(p.Discard).Cast()) + .FirstOrDefault(c => c.InstanceId == pending.TargetInstanceId); + if (ppCard is null) break; + + var ppFromOwner = FindCardOwner(state, pending.TargetInstanceId); + if (ppFromOwner is null) break; + + var ppCcze = pending.EffectJson is not null + ? JsonSerializer.Deserialize(pending.EffectJson, _jsonOpts) as ChannelCardFromZoneEffect + : null; + + if (ppCcze?.TargetTile == true) + { + // Chain into a tile pick for the chosen dest player. + state.PendingTilePick = new PendingTilePick + { + ActorId = pending.ActorId, + ChooserActorId = pickedPlayerId, + SourceInstanceId = pending.SourceInstanceId, + EffectType = "ChannelCardFromZone", + TargetInstanceId = pending.TargetInstanceId, + DestPlayerAccountId = pickedPlayerId, + RequireEmpty = true, + EffectJson = pending.EffectJson, + ContinuationActionsJson = pending.ContinuationActionsJson, + RangeJson = pending.RangeJson, + ForceDurationJson = pending.ForceDurationJson, + }; + return state; + } + + // Random tile in channel range. + var ppArch = ppDest.ArchSpirit; + Coord? ppCoord; + if (ppCcze?.IgnoreChannelRange != true && ppArch?.Position.HasValue == true) + { + var maxR = ppCard.MaxChannelRange ?? 2; + var minR = ppCard.MinChannelRange ?? 1; + ppCoord = ppBoard.Tiles.Values + .Where(t => t.IsEmpty) + .Where(t => + { + var d = ppBoard.HexSides > 0 + ? HexGrid.Distance(ppArch.Position!.Value, t.Coord, ppBoard.HexSides) + : ppArch.Position!.Value.ManhattanDistance(t.Coord); + return d >= minR && d <= maxR; + }) + .Select(t => t.Coord) + .OrderBy(_ => Random.Shared.Next()) + .Cast() + .FirstOrDefault(); + } + else + { + ppCoord = ppBoard.Tiles.Values + .Where(t => t.IsEmpty) + .Select(t => t.Coord) + .OrderBy(_ => Random.Shared.Next()) + .Cast() + .FirstOrDefault(); + } + if (ppCoord is null) break; + + // Affinity check. + if (ppCcze?.IgnoreAffinity != true && Enum.TryParse(ppCard.Affinity, out var ppAff)) + { + var ppTile = ppBoard.GetTile(ppCoord.Value); + if (ppTile is null || !AffinitySystem.IsAffinityValid(ppTile, ppAff)) break; + } + + // Cost. + if (ppCcze?.IgnoreChannelCost != true) + { + ppDest.CurrentSp -= ppCard.SpCost; + ppDest.CurrentSt -= ppCard.StCost; + } + + // Remove from zone. + if (ppCcze?.KeepInZone != true) + RemoveFromZone(ppFromOwner, ppCcze?.Zone ?? "Hand", ppCard); + + // Place on board. + var ppField = GameEngine.ToFieldCardInternal(ppCard, ppCoord.Value); + ppDest.Field.Add(ppField); + ppBoard.PlaceUnit(ppCoord.Value, ppField.InstanceId, pickedPlayerId); + + EvaluateAurasOnEnter(state, ppField.InstanceId); + ApplyPassivesForSource(state, ppField.InstanceId, pickedPlayerId); + ApplyPassivesToNewTarget(state, ppField.InstanceId); + + FireTrigger(state, new TriggerOccurrence + { + Kind = TriggerEventKind.Channeled, + ActorId = pickedPlayerId, + CardType = ppCard.CardType, + Data = new TriggerEventData { SourceId = ppField.InstanceId }, + }); + break; + } + + default: + { + // Generic case: store the picked player in resolved targets for continuation use. + if (state.Players.TryGetValue(pickedPlayerId, out var genericPickedPlayer)) + ppCtx.ResolvedTargets[0] = [(object)genericPickedPlayer]; + break; + } + } + + var ppContinuation = JsonSerializer.Deserialize( + pending.ContinuationActionsJson, _jsonOpts) ?? []; + if (ppContinuation.Length > 0) + { + AbilityRange? ppRange = pending.RangeJson is not null + ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) : null; + DurationModel? ppForceDuration = pending.ForceDurationJson is not null + ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) : null; + ExecuteActions(ppContinuation, ppCtx, clientTargets: null, activationRange: ppRange, + forceDuration: ppForceDuration); + } + return state; + } + + /// + /// Resumes an active ability that was paused because a leaf Action had + /// Chooser=Opponent/Ally and needed the non-activating player to supply targets. + /// Called by GameTargetPickHandler. + /// + public static GameState ResumeTargetPick( + GameState state, + string actorId, + string requestId, + IReadOnlyList clientTargets) + { + var pending = state.PendingTargetPick + ?? throw new GameException("NO_PENDING_TARGET_PICK"); + + if (pending.RequestId != requestId) + throw new GameException("REQUEST_ID_MISMATCH"); + + var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId) + ? pending.ActorId + : pending.ChooserActorId; + if (expectedChooser != actorId) + throw new GameException("NOT_YOUR_TARGET_PICK"); + + state.PendingTargetPick = null; + + var action = JsonSerializer.Deserialize(pending.ActionJson, _jsonOpts) + ?? throw new GameException("INVALID_TARGET_PICK_STATE"); + var continuation = JsonSerializer.Deserialize( + pending.ContinuationActionsJson, _jsonOpts) ?? []; + + 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 }; + + 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; + + // Execute the paused action (now with client targets) then run the continuation. + var allActions = new[] { action }.Concat(continuation).ToArray(); + ExecuteActions(allActions, ctx, clientTargets, requireClientTargets: true, + activationRange: range, forceDuration: forceDuration); + + return state; + } + // ── Action execution ────────────────────────────────────────────────────── private static void ExecuteActions( @@ -1090,7 +1505,8 @@ public static class AbilitySystem for (int i = 0; i < actions.Length; i++) { ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i, - requireClientTargets, activationRange, restrictTargets, forceDuration); + requireClientTargets, activationRange, restrictTargets, forceDuration, + continuationActions: actions[(i + 1)..]); // Stop iterating as soon as any interactive pause is set. if (ctx.State.HasPendingInteraction()) break; } @@ -1114,8 +1530,10 @@ public static class AbilitySystem bool requireClientTargets = false, AbilityRange? activationRange = null, HashSet? restrictTargets = null, - DurationModel? forceDuration = null) + DurationModel? forceDuration = null, + Models.Action[] continuationActions = null!) { + continuationActions ??= []; // ChooseOne branch selector: execute the chosen branch's actions instead. if (action.ChooseOne is { Branches.Length: > 0 }) { @@ -1136,9 +1554,6 @@ public static class AbilitySystem && 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, @@ -1146,7 +1561,7 @@ public static class AbilitySystem SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, BranchCount = chooser.Branches.Length, BranchesJson = JsonSerializer.Serialize(chooser.Branches, _jsonOpts), - ContinuationActionsJson = "[]", + ContinuationActionsJson = JsonSerializer.Serialize(continuationActions, _jsonOpts), RangeJson = activationRange is not null ? JsonSerializer.Serialize(activationRange, _jsonOpts) : null, ForceDurationJson = forceDuration is not null @@ -1174,6 +1589,36 @@ public static class AbilitySystem if (cond.Subject != "Target" && !EvaluateCondition(cond, ctx, ctx.Source!)) return; + // If Chooser=Opponent/Ally and we have no client-provided targets, pause for the + // non-activating player to pick. (Chooser=Random is server-resolved in ResolveTargets.) + var sel = action.Target; + if (sel.Chooser is TargetChooser.Opponent or TargetChooser.Ally + && clientTargets is null + && sel.Type != TargetType.Player + && !sel.Count.All) + { + var tpChooser = sel.Chooser == TargetChooser.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; + + ctx.State.PendingTargetPick = new PendingTargetPick + { + ActorId = ctx.ActorId, + ChooserActorId = tpChooser, + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + ActionJson = JsonSerializer.Serialize(action, _jsonOpts), + ContinuationActionsJson = JsonSerializer.Serialize(continuationActions, _jsonOpts), + RangeJson = activationRange is not null + ? JsonSerializer.Serialize(activationRange, _jsonOpts) : null, + ForceDurationJson = forceDuration is not null + ? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null, + }; + return; + } + var resolved = ResolveTargets( action.Target, ctx, clientTargets, actionIndex, requireClientTargets, activationRange, restrictTargets); ctx.ResolvedTargets[actionIndex] = resolved; @@ -1193,6 +1638,10 @@ public static class AbilitySystem if (!passes) continue; } + // Expose continuation context so effect-level pauses can store it. + ctx.ContinuationActions = continuationActions; + ctx.ActivationRange = activationRange; + foreach (var effect in action.Effects) { ExecuteEffect(effect, target, duration, ctx); @@ -2303,13 +2752,92 @@ public static class AbilitySystem // ── §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. + // Find the owner of the target ArchSpirit. + var azeOwner = FindCardOwner(ctx.State, arcAze.InstanceId) + ?? (ctx.State.Players.Values.FirstOrDefault(p => p.ArchSpirit?.InstanceId == arcAze.InstanceId)); + if (azeOwner is null) break; + if (arcAze.Position is null) break; + var coord = arcAze.Position.Value; + int currentTier = arcAze.Tier ?? 1; + + // Find the incoming next-tier ArchSpirit from the specified zone. + var incoming = FindInZone(azeOwner, aze.Zone, + c => c.CardType == "ArchSpirit" + && (c.Tier ?? 1) == currentTier + 1 + && c.PreviousTierId == arcAze.CardDefinitionId); + if (incoming is null) break; + + if (!aze.IgnoreCost) + { + if (azeOwner.CurrentSp < incoming.SpCost || azeOwner.CurrentSt < incoming.StCost) + break; // insufficient resources — skip effect + azeOwner.CurrentSp -= incoming.SpCost; + azeOwner.CurrentSt -= incoming.StCost; + } + + RemoveFromZone(azeOwner, aze.Zone, incoming); + + EvaluateAurasOnLeave(ctx.State, arcAze.InstanceId); + RevokePassivesForSource(ctx.State, arcAze.InstanceId); + ctx.State.Board?.RemoveUnit(arcAze.InstanceId); + azeOwner.Discard.Add(arcAze); + + var newArch = GameEngine.ToFieldCardInternal(incoming, coord, isLeader: true); + azeOwner.ArchSpirit = newArch; + ctx.State.Board?.PlaceUnit(coord, newArch.InstanceId, azeOwner.AccountId); + EvaluateAurasOnEnter(ctx.State, newArch.InstanceId); + ApplyPassivesForSource(ctx.State, newArch.InstanceId, azeOwner.AccountId); + ApplyPassivesToNewTarget(ctx.State, newArch.InstanceId); + + FireTrigger(ctx.State, new TriggerOccurrence + { + Kind = TriggerEventKind.Ascend, + ActorId = azeOwner.AccountId, + Data = new TriggerEventData { SourceId = newArch.InstanceId }, + }); break; } case TransitionFromZoneEffect tze when target is FieldCard arcTze && arcTze.IsLeader: { - // TODO(Phase5-full): full transition requires catalog lookup for same-tier card. + var tzeOwner = FindCardOwner(ctx.State, arcTze.InstanceId) + ?? (ctx.State.Players.Values.FirstOrDefault(p => p.ArchSpirit?.InstanceId == arcTze.InstanceId)); + if (tzeOwner is null) break; + if (arcTze.Position is null) break; + var coord = arcTze.Position.Value; + + // Find a Tier-1 ArchSpirit from the specified zone (transition = replace with T1). + var incoming = FindInZone(tzeOwner, tze.Zone, + c => c.CardType == "ArchSpirit" && (c.Tier ?? 1) == 1); + if (incoming is null) break; + + if (!tze.IgnoreCost) + { + if (tzeOwner.CurrentSp < incoming.SpCost || tzeOwner.CurrentSt < incoming.StCost) + break; + tzeOwner.CurrentSp -= incoming.SpCost; + tzeOwner.CurrentSt -= incoming.StCost; + } + + RemoveFromZone(tzeOwner, tze.Zone, incoming); + + EvaluateAurasOnLeave(ctx.State, arcTze.InstanceId); + RevokePassivesForSource(ctx.State, arcTze.InstanceId); + ctx.State.Board?.RemoveUnit(arcTze.InstanceId); + tzeOwner.Discard.Add(arcTze); + + var newArch = GameEngine.ToFieldCardInternal(incoming, coord, isLeader: true); + tzeOwner.ArchSpirit = newArch; + ctx.State.Board?.PlaceUnit(coord, newArch.InstanceId, tzeOwner.AccountId); + EvaluateAurasOnEnter(ctx.State, newArch.InstanceId); + ApplyPassivesForSource(ctx.State, newArch.InstanceId, tzeOwner.AccountId); + ApplyPassivesToNewTarget(ctx.State, newArch.InstanceId); + + FireTrigger(ctx.State, new TriggerOccurrence + { + Kind = TriggerEventKind.Transition, + ActorId = tzeOwner.AccountId, + Data = new TriggerEventData { SourceId = newArch.InstanceId }, + }); break; } case ModifyChannelRangeEffect mcre when target is FieldCard arcMcr && arcMcr.IsLeader: @@ -2389,12 +2917,138 @@ public static class AbilitySystem // ── §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 + var board = ctx.State.Board; + if (board is null) break; + + // Determine destination player. + PlayerState? ccDestPlayer = ccze.UnderControlOf switch + { + "Target" => ccOwner, + "Opponent" => ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() is { } ccEid + ? ctx.State.Players.GetValueOrDefault(ccEid) : null, + "Ally" => ctx.State.Players.Values.FirstOrDefault(p => + p.AccountId != ctx.ActorId + && ctx.State.AreAllies(p.AccountId, ctx.ActorId)), + "Random" => ctx.State.Players.Values.OrderBy(_ => Random.Shared.Next()).FirstOrDefault(), + "Choice" => null, + _ => ctx.State.Players.GetValueOrDefault(ctx.ActorId), // "Self" + }; + + if (ccze.UnderControlOf == "Choice" && ccDestPlayer is null) + { + // Pause: ask the actor to choose which player controls the card. + ctx.State.PendingPlayerPick = new PendingPlayerPick + { + ActorId = ctx.ActorId, + ChooserActorId = ctx.ActorId, + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + EffectType = "ChannelCardFromZone", + TargetInstanceId = ciCcze.InstanceId, + ValidPlayerIds = ctx.State.Players.Keys.ToList(), + EffectJson = JsonSerializer.Serialize((Effect)ccze, _jsonOpts), + ContinuationActionsJson = JsonSerializer.Serialize(ctx.ContinuationActions, _jsonOpts), + RangeJson = ctx.ActivationRange is not null + ? JsonSerializer.Serialize(ctx.ActivationRange, _jsonOpts) : null, + ForceDurationJson = duration is not null + ? JsonSerializer.Serialize(duration, _jsonOpts) : null, + }; + return; + } + + if (ccDestPlayer is null) break; + + // Destination tile. + if (ccze.TargetTile) + { + ctx.State.PendingTilePick = new PendingTilePick + { + ActorId = ctx.ActorId, + ChooserActorId = ccDestPlayer.AccountId, + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + EffectType = "ChannelCardFromZone", + TargetInstanceId = ciCcze.InstanceId, + DestPlayerAccountId = ccDestPlayer.AccountId, + RequireEmpty = true, + EffectJson = JsonSerializer.Serialize((Effect)ccze, _jsonOpts), + ContinuationActionsJson = JsonSerializer.Serialize(ctx.ContinuationActions, _jsonOpts), + RangeJson = ctx.ActivationRange is not null + ? JsonSerializer.Serialize(ctx.ActivationRange, _jsonOpts) : null, + ForceDurationJson = duration is not null + ? JsonSerializer.Serialize(duration, _jsonOpts) : null, + }; + return; + } + + // Random tile in channel range (or anywhere if IgnoreChannelRange). + var ccArch = ccDestPlayer.ArchSpirit; + Coord? ccDestCoord; + if (!ccze.IgnoreChannelRange && ccArch?.Position.HasValue == true) + { + var maxR = ciCcze.MaxChannelRange ?? 2; + var minR = ciCcze.MinChannelRange ?? 1; + ccDestCoord = board.Tiles.Values + .Where(t => t.IsEmpty) + .Where(t => + { + var d = board.HexSides > 0 + ? HexGrid.Distance(ccArch.Position!.Value, t.Coord, board.HexSides) + : ccArch.Position!.Value.ManhattanDistance(t.Coord); + return d >= minR && d <= maxR; + }) + .Select(t => t.Coord) + .OrderBy(_ => Random.Shared.Next()) + .Cast() + .FirstOrDefault(); + } + else + { + ccDestCoord = board.Tiles.Values + .Where(t => t.IsEmpty) + .Select(t => t.Coord) + .OrderBy(_ => Random.Shared.Next()) + .Cast() + .FirstOrDefault(); + } + if (ccDestCoord is null) break; + + // Affinity check. + if (!ccze.IgnoreAffinity && Enum.TryParse(ciCcze.Affinity, out var ccAffinity)) + { + var ccTile = board.GetTile(ccDestCoord.Value); + if (ccTile is null || !AffinitySystem.IsAffinityValid(ccTile, ccAffinity)) break; + } + + // Cost. + if (!ccze.IgnoreChannelCost) + { + ccDestPlayer.CurrentSp -= ciCcze.SpCost; + ccDestPlayer.CurrentSt -= ciCcze.StCost; + } + + // Remove from zone. + if (!ccze.KeepInZone) + RemoveFromZone(ccOwner, ccze.Zone, ciCcze); + + // Place on board. + var ccField = GameEngine.ToFieldCardInternal(ciCcze, ccDestCoord.Value); + ccDestPlayer.Field.Add(ccField); + board.PlaceUnit(ccDestCoord.Value, ccField.InstanceId, ccDestPlayer.AccountId); + + // Auras / passives. + EvaluateAurasOnEnter(ctx.State, ccField.InstanceId); + ApplyPassivesForSource(ctx.State, ccField.InstanceId, ccDestPlayer.AccountId); + ApplyPassivesToNewTarget(ctx.State, ccField.InstanceId); + + // Trigger. + FireTrigger(ctx.State, new TriggerOccurrence + { + Kind = TriggerEventKind.Channeled, + ActorId = ccDestPlayer.AccountId, + CardType = ciCcze.CardType, + Data = new TriggerEventData { SourceId = ccField.InstanceId }, + }); break; } @@ -2406,9 +3060,10 @@ public static class AbilitySystem // 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, + "TargetTile" when ctx.ResolvedTargets.Count > 0 && + ctx.ResolvedTargets.Values.SelectMany(x => x).OfType().FirstOrDefault() is { } resolvedCoord + => resolvedCoord, + "TargetTile" => null, // no coord yet — will pause below "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)) @@ -2424,7 +3079,23 @@ public static class AbilitySystem .Cast() .FirstOrDefault(), }; - if (dest is null) break; + if (dest is null) + { + // TargetTile: no resolved coord — pause for player to pick a destination tile. + if (cste.DestinationScope == "TargetTile") + { + ctx.State.PendingTilePick = new PendingTilePick + { + ActorId = ctx.ActorId, + ChooserActorId = ctx.ActorId, + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + EffectType = "CloneSpiritAsToken", + TargetInstanceId = spiritToClone.InstanceId, + RequireEmpty = true, + }; + } + break; + } var tokenProto = new CardInstance { @@ -2546,9 +3217,28 @@ public static class AbilitySystem } 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; + if (duration is null) break; // reversal call from ApplyReversal — no-op + + // Store the effect as an active marker. BuildBlockedSet queries ActiveEffects + // for ObstructMovementTypeEffect entries to extend the blocked-set for pathfinding. + // When expired, ApplyReversal calls ExecuteEffect(omte, ..., duration:null) which + // hits the guard above and is a no-op; the entry has already been removed. + var omteDuration = duration.Type is DurationType.Instant or DurationType.PermanentInMatch + ? omte.Duration + : duration; + ctx.State.ActiveEffects.Add(new ActiveEffect + { + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + TargetRef = fcOmte.InstanceId, + EffectJson = JsonSerializer.Serialize((Effect)omte, _jsonOpts), + DurationJson = JsonSerializer.Serialize(new TrackedDuration + { + Duration = omteDuration, + OwnerAccountId = ctx.ActorId, + }, _jsonOpts), + TurnsRemaining = omteDuration.N ?? 0, + Label = $"Obstruct:{omte.MovementType}", + }); break; } @@ -2917,6 +3607,54 @@ public static class AbilitySystem return null; } + /// + /// Returns the InstanceIds of all units currently carrying an + /// active effect that obstructs . + /// Used by to extend pathfinding blocked-sets. + /// + internal static HashSet GetUnitsObstructingMovementType(GameState state, MovementType movType) + { + var result = new HashSet(); + foreach (var ae in state.ActiveEffects) + { + Effect? eff; + try { eff = JsonSerializer.Deserialize(ae.EffectJson, _jsonOpts); } + catch { continue; } + if (eff is ObstructMovementTypeEffect omte && omte.MovementType == movType) + result.Add(ae.TargetRef); + } + return result; + } + + /// Find the first card in the given zone ("Hand"|"Deck"|"Discard"|"Any") matching predicate. + private static CardInstance? FindInZone(PlayerState player, string zone, Func predicate) + => zone switch + { + "Hand" => player.Hand.FirstOrDefault(predicate), + "Deck" => player.Deck.FirstOrDefault(predicate), + "Discard" => player.Discard.FirstOrDefault(predicate), + _ => // "Any": search all zones + player.Hand.FirstOrDefault(predicate) + ?? player.Deck.FirstOrDefault(predicate) + ?? (CardInstance?)player.Discard.FirstOrDefault(predicate), + }; + + /// Remove a card from the specified zone ("Hand"|"Deck"|"Discard"|"Any"). + private static void RemoveFromZone(PlayerState player, string zone, CardInstance card) + { + switch (zone) + { + case "Hand": player.Hand.Remove(card); break; + case "Deck": player.Deck.Remove(card); break; + case "Discard": player.Discard.Remove(card); break; + default: // "Any" + if (!player.Hand.Remove(card)) + if (!player.Deck.Remove(card)) + player.Discard.Remove(card); + break; + } + } + private static IEnumerable OrthogonalNeighbours(Coord c) => [ diff --git a/Server/src/SOR.Game/Abilities/Models/PendingActionGroupPick.cs b/Server/src/SOR.Game/Abilities/Models/PendingActionGroupPick.cs index 7f38310..54b5b2e 100644 --- a/Server/src/SOR.Game/Abilities/Models/PendingActionGroupPick.cs +++ b/Server/src/SOR.Game/Abilities/Models/PendingActionGroupPick.cs @@ -28,9 +28,16 @@ public sealed class PendingActionGroupPick /// public string ActionGroupJson { get; set; } = "{}"; - /// JSON-serialized Action[] — the full action list to execute AFTER the picked branch finishes. + /// JSON-serialized Action[] — the full action list to execute AFTER the picked branch and all remaining groups finish. public string ContinuationActionsJson { get; set; } = "[]"; + /// + /// JSON-serialized ActionGroup[]? — remaining sibling groups (in the parent AND group) + /// to process sequentially after the chosen branch executes. + /// Null when the paused group was not nested inside an AND group. + /// + public string? RemainingGroupsJson { get; set; } + /// JSON-serialized AbilityRange? — passed through to ExecuteActions on resume. public string? RangeJson { get; set; } diff --git a/Server/src/SOR.Game/Abilities/Models/PendingPlayerPick.cs b/Server/src/SOR.Game/Abilities/Models/PendingPlayerPick.cs index ae0ae68..9729fd7 100644 --- a/Server/src/SOR.Game/Abilities/Models/PendingPlayerPick.cs +++ b/Server/src/SOR.Game/Abilities/Models/PendingPlayerPick.cs @@ -22,6 +22,18 @@ public sealed class PendingPlayerPick /// Account IDs of the valid choices (populated by engine at pause time). public List ValidPlayerIds { get; set; } = new(); + /// + /// InstanceId of the primary target that was already resolved before the pick + /// (e.g. the card to channel for ChannelCardFromZoneEffect). Empty when not applicable. + /// + public string TargetInstanceId { get; set; } = string.Empty; + + /// + /// Serialized Effect JSON — used when the resume handler needs the original effect's parameters + /// (e.g. ChannelCardFromZoneEffect flags). Null when not needed. + /// + public string? EffectJson { get; set; } + // ── Continuation ───────────────────────────────────────────────────────── public string ContinuationActionsJson { get; set; } = "[]"; diff --git a/Server/src/SOR.Game/Abilities/Models/PendingTargetPick.cs b/Server/src/SOR.Game/Abilities/Models/PendingTargetPick.cs new file mode 100644 index 0000000..a8982ef --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/PendingTargetPick.cs @@ -0,0 +1,42 @@ +namespace SOR.Game.Abilities.Models; + +/// +/// Stored in GameState when a leaf Action has TargetSelector.Chooser = Opponent or +/// Ally during active ability execution, requiring the non-activating player to pick +/// the targets before the action's effects can execute. +/// +/// The game is paused until the chooser submits a game.target_pick response. +/// +public sealed class PendingTargetPick +{ + /// 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 submit the target picks. + /// May differ from for Chooser=Opponent/Ally actions. + /// + 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 — the action awaiting target picks. + /// The full TargetSelector (Scope/Type/Ownership/Count/Filters) is embedded so the + /// client can present the correct picker UI. + /// + public string ActionJson { get; set; } = "{}"; + + /// JSON-serialized Action[] — remaining actions to execute after this one resolves. + public string ContinuationActionsJson { get; set; } = "[]"; + + /// JSON-serialized AbilityRange? — passed through to ExecuteActions on resume. + public string? RangeJson { get; set; } + + /// JSON-serialized DurationModel? — forceDuration applied on resume. + 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 index 90c7a10..561c9a1 100644 --- a/Server/src/SOR.Game/Abilities/Models/PendingTilePick.cs +++ b/Server/src/SOR.Game/Abilities/Models/PendingTilePick.cs @@ -26,6 +26,25 @@ public sealed class PendingTilePick /// Max tiles from source; 0 = unlimited. public int MaxRange { get; set; } + /// + /// InstanceId of the primary target that was already resolved before the pick + /// (e.g. the Spirit to clone for CloneSpiritAsToken). Empty when not applicable. + /// + public string TargetInstanceId { get; set; } = string.Empty; + + /// + /// For ChannelCardFromZone: AccountId of the player who will control the channeled card. + /// Empty when not applicable. + /// + public string DestPlayerAccountId { get; set; } = string.Empty; + + /// + /// Serialized Effect JSON — used when the resume handler needs the original effect's parameters + /// (e.g. ChannelCardFromZoneEffect flags like IgnoreAffinity, KeepInZone). + /// Null when not needed. + /// + public string? EffectJson { get; set; } + // ── Continuation ───────────────────────────────────────────────────────── public string ContinuationActionsJson { get; set; } = "[]"; diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs index b09c864..d27218f 100644 --- a/Server/src/SOR.Game/GameEngine.cs +++ b/Server/src/SOR.Game/GameEngine.cs @@ -1475,20 +1475,30 @@ public static class GameEngine GameState state, string movingUnitId, MovementType? movType) { var blocked = new HashSet(); + + // Units that additionally obstruct the moving unit's movement type via active effects. + HashSet? extraObstructors = movType.HasValue + ? AbilitySystem.GetUnitsObstructingMovementType(state, movType.Value) + : null; + foreach (var player in state.Players.Values) { foreach (var card in player.Field.OfType()) { if (card.InstanceId == movingUnitId) continue; if (!card.Position.HasValue) continue; - // Flight is blocked only by other Flight units; Walk is blocked by all. - if (movType == MovementType.Flight && card.MovementType != MovementType.Flight) continue; + // Flight is blocked only by other Flight units, or units with ObstructMovementType(Flight). + if (movType == MovementType.Flight + && card.MovementType != MovementType.Flight + && extraObstructors?.Contains(card.InstanceId) != true) continue; blocked.Add(card.Position.Value); } var arch = player.ArchSpirit; if (arch is not null && arch.InstanceId != movingUnitId && arch.Position.HasValue) { - if (movType != MovementType.Flight || arch.MovementType == MovementType.Flight) + if (movType != MovementType.Flight + || arch.MovementType == MovementType.Flight + || extraObstructors?.Contains(arch.InstanceId) == true) blocked.Add(arch.Position.Value); } } @@ -1499,6 +1509,10 @@ public static class GameEngine /// Create a FieldCard from an existing CardInstance, placing it at the given position /// with full HP, Defense, and MP restored. isLeader=true for ArchSpirits. /// + /// Internal helper exposed to AbilitySystem for effect-level ArchSpirit swaps. + internal static FieldCard ToFieldCardInternal(CardInstance source, Coord position, bool isLeader = false) + => ToFieldCard(source, position, isLeader); + private static FieldCard ToFieldCard(CardInstance source, Coord position, bool isLeader = false) => new() { diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index cc75030..e410d57 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -910,3 +910,42 @@ public sealed record GameRevealChoicePickRequest( /// Acknowledged response for a reveal-choice pick submission. public sealed record GameRevealChoicePickResponse(bool Success); + +/// +/// Sent by the chooser (Opponent/Ally) to supply target picks for a paused leaf action. +/// The same shape used by game.activate_ability is reused here. +/// +public sealed record GameTargetPickRequest( + Guid SessionId, + string RequestId, + IReadOnlyList Targets); + +/// Acknowledged response for a target pick submission. +public sealed record GameTargetPickResponse(bool Success); + +/// +/// Sent by the chooser to pick a specific tile for an effect that requires one +/// (e.g. CloneSpiritAsToken with DestinationScope=TargetTile). +/// +public sealed record GameTilePickRequest( + Guid SessionId, + string RequestId, + /// The chosen tile coordinates. + int X, + int Y); + +/// Acknowledged response for a tile pick submission. +public sealed record GameTilePickResponse(bool Success); + +/// +/// Sent by the chooser to pick a specific player for an effect that requires one +/// (e.g. ChannelCardFromZoneEffect with UnderControlOf=Choice). +/// +public sealed record GamePlayerPickRequest( + Guid SessionId, + string RequestId, + /// AccountId of the chosen player. + string PickedPlayerId); + +/// Acknowledged response for a player pick submission. +public sealed record GamePlayerPickResponse(bool Success); diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs index 28f345e..f6e3c2c 100644 --- a/Server/src/SOR.Game/GameState.cs +++ b/Server/src/SOR.Game/GameState.cs @@ -148,6 +148,13 @@ public sealed class GameState /// public Abilities.Models.PendingRevealChoicePick? PendingRevealChoicePick { get; set; } + /// + /// Non-null when a leaf Action has Chooser=Opponent/Ally and the non-activating player + /// must select the targets for that action before its effects execute. + /// Paused until the chooser submits a game.target_pick response. + /// + public Abilities.Models.PendingTargetPick? PendingTargetPick { get; set; } + /// /// Returns true when any interactive pause is in effect (ability execution must stop). /// @@ -158,7 +165,8 @@ public sealed class GameState PendingBranchPick is not null || PendingTilePick is not null || PendingPlayerPick is not null || - PendingRevealChoicePick is not null; + PendingRevealChoicePick is not null || + PendingTargetPick is not null; } public sealed class PlayerState diff --git a/Server/src/SOR.Game/Handlers/GamePlayerPickHandler.cs b/Server/src/SOR.Game/Handlers/GamePlayerPickHandler.cs new file mode 100644 index 0000000..8b7842c --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GamePlayerPickHandler.cs @@ -0,0 +1,56 @@ +namespace SOR.Game.Handlers; + +using System.Text.Json; +using SOR.Database.Contexts; +using SOR.Game.Abilities; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.player_pick — player picks a specific player for an effect-level player selection +/// (e.g. ChannelCardFromZoneEffect with UnderControlOf=Choice). +/// +internal sealed class GamePlayerPickHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GamePlayerPickHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.player_pick"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var actorId = connection.UserId; + + var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct); + var prevStateJson = session.StateJson!; + var state = GameEngine.Deserialize(prevStateJson); + + var newState = AbilitySystem.ResumePlayerPick( + state, actorId, req.RequestId, req.PickedPlayerId); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.player_pick", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson); + + return ServerMessage.Reply("game.player_pick.ack", message.Seq, + new GamePlayerPickResponse(true)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameTargetPickHandler.cs b/Server/src/SOR.Game/Handlers/GameTargetPickHandler.cs new file mode 100644 index 0000000..cf30081 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameTargetPickHandler.cs @@ -0,0 +1,59 @@ +namespace SOR.Game.Handlers; + +using System.Text.Json; +using SOR.Database.Contexts; +using SOR.Game.Abilities; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.target_pick — opponent or ally submits target picks for a paused leaf action +/// whose TargetSelector.Chooser was Opponent or Ally. +/// +/// Resumes execution of the paused action (and its continuation) then broadcasts +/// the updated game state to all players. +/// +internal sealed class GameTargetPickHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameTargetPickHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.target_pick"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var actorId = connection.UserId; + + var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct); + var prevStateJson = session.StateJson!; + var state = GameEngine.Deserialize(prevStateJson); + + var newState = AbilitySystem.ResumeTargetPick( + state, actorId, req.RequestId, req.Targets); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.target_pick", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson); + + return ServerMessage.Reply("game.target_pick.ack", message.Seq, + new GameTargetPickResponse(true)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameTilePickHandler.cs b/Server/src/SOR.Game/Handlers/GameTilePickHandler.cs new file mode 100644 index 0000000..953d766 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameTilePickHandler.cs @@ -0,0 +1,57 @@ +namespace SOR.Game.Handlers; + +using System.Text.Json; +using SOR.Database.Contexts; +using SOR.Game.Abilities; +using SOR.Game.Grid; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.tile_pick — player picks a specific tile for an effect-level tile selection +/// (e.g. CloneSpiritAsToken with DestinationScope=TargetTile). +/// +internal sealed class GameTilePickHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameTilePickHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.tile_pick"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var actorId = connection.UserId; + + var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct); + var prevStateJson = session.StateJson!; + var state = GameEngine.Deserialize(prevStateJson); + + var newState = AbilitySystem.ResumeTilePick( + state, actorId, req.RequestId, new Coord(req.X, req.Y)); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.tile_pick", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson); + + return ServerMessage.Reply("game.tile_pick.ack", message.Seq, + new GameTilePickResponse(true)); + } +} diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs index 4d344a0..e54bf9e 100644 --- a/Server/src/SOR.Game/ServiceRegistration.cs +++ b/Server/src/SOR.Game/ServiceRegistration.cs @@ -115,6 +115,15 @@ public static class ServiceRegistration // Reveal-choice pick (chooser orders revealed cards, e.g. StackDeck interactive) services.AddTransient(); + // Target pick (opponent/ally submits targets for a Chooser=Opponent/Ally action) + services.AddTransient(); + + // Tile pick (player selects a tile for an effect-level tile selection) + services.AddTransient(); + + // Player pick (player selects a player for an effect-level player selection) + services.AddTransient(); + return services; } }