diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index 8b3fd6b..e38cd5a 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -287,11 +287,27 @@ public static class AbilitySystem // If any action needs a human pick, pause and request client input. var effectiveActions = GetEffectiveActions(def, ctx, abilityIndex: 0, def.Range, def.Duration) ?? []; - if (effectiveActions.Any(ActionNeedsClientTargets)) + var pickAction = Array.Find(effectiveActions, ActionNeedsClientTargets); + if (pickAction is not null) { + // Determine which player must actually submit the target picks. + // For Chooser.Opponent/Ally, route the request to the non-activating player. + string chooserActorId = pickAction.Target.Chooser switch + { + TargetChooser.Opponent => + state.GetEnemyIds(ownerId).FirstOrDefault() ?? ownerId, + TargetChooser.Ally => + state.Players.Values + .FirstOrDefault(p => p.AccountId != ownerId + && state.AreAllies(p.AccountId, ownerId)) + ?.AccountId ?? ownerId, + _ => ownerId, // Self or default + }; + state.PendingTriggeredTarget = new PendingTriggeredTarget { ActorId = ownerId, + ChooserActorId = chooserActorId, SourceInstanceId = card.InstanceId, AbilityName = def.Name ?? "Triggered Ability", ActionsJson = JsonSerializer.Serialize(effectiveActions, _jsonOpts), @@ -326,11 +342,6 @@ public static class AbilitySystem { state.PendingDeferredEffects.Remove(pending); - Models.Action[]? deferredActions; - try { deferredActions = JsonSerializer.Deserialize(pending.ActionsJson, _jsonOpts); } - catch { 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); @@ -342,7 +353,26 @@ public static class AbilitySystem if (tgt is not null) dCtx.ResolvedTargets[0] = [tgt]; - ExecuteActions(deferredActions, dCtx, clientTargets: null, requireClientTargets: false); + // Prefer ActionGroupJson (full recursive tree) over legacy flat ActionsJson. + if (pending.ActionGroupJson is not null) + { + Models.ActionGroup? ag; + try { ag = JsonSerializer.Deserialize(pending.ActionGroupJson, _jsonOpts); } + catch { continue; } + if (ag is null) continue; + var resolved = ResolveActionGroup(ag, dCtx, abilityIndex: 0, + range: null, forceDuration: null, continuationActions: []); + if (resolved is not null) + ExecuteActions(resolved, dCtx, clientTargets: null, requireClientTargets: false); + } + else + { + Models.Action[]? deferredActions; + try { deferredActions = JsonSerializer.Deserialize(pending.ActionsJson, _jsonOpts); } + catch { continue; } + if (deferredActions is null || deferredActions.Length == 0) continue; + ExecuteActions(deferredActions, dCtx, clientTargets: null, requireClientTargets: false); + } } return state; @@ -1058,8 +1088,12 @@ public static class AbilitySystem try { for (int i = 0; i < actions.Length; i++) + { ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i, requireClientTargets, activationRange, restrictTargets, forceDuration); + // Stop iterating as soon as any interactive pause is set. + if (ctx.State.HasPendingInteraction()) break; + } } finally { @@ -1160,7 +1194,14 @@ public static class AbilitySystem } foreach (var effect in action.Effects) + { ExecuteEffect(effect, target, duration, ctx); + // Stop as soon as an effect sets an interactive pause. + if (ctx.State.HasPendingInteraction()) return; + } + + // Also stop between targets if a pause was set mid-loop. + if (ctx.State.HasPendingInteraction()) return; } } @@ -1192,6 +1233,10 @@ public static class AbilitySystem if (sel.Count.All) return false; + // Random chooser: server resolves without client input regardless of ownership. + if (sel.Chooser == TargetChooser.Random) + return false; + // These ownerships are auto-resolved: self, random, chained from prior action. return sel.Ownership is not ( TargetOwnership.Self or @@ -1216,7 +1261,12 @@ public static class AbilitySystem if (pending.RequestId != requestId) throw new GameException("REQUEST_ID_MISMATCH"); - if (pending.ActorId != actorId) + // ChooserActorId is who must respond — may be an opponent/ally for Chooser.Opponent/Ally. + // Fall back to ActorId for older records that predate ChooserActorId. + var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId) + ? pending.ActorId + : pending.ChooserActorId; + if (expectedChooser != actorId) throw new GameException("NOT_YOUR_TRIGGER"); // Clear before executing so any nested triggers don't see a stale request. @@ -2515,7 +2565,11 @@ public static class AbilitySystem OwnerAccountId = ctx.ActorId, TriggerJson = JsonSerializer.Serialize(aoe.Trigger, _jsonOpts), TargetRef = targetRef, - ActionsJson = JsonSerializer.Serialize(aoe.Actions, _jsonOpts), + // Store the ActionGroup as the canonical form; ActionsJson is a legacy fallback. + ActionGroupJson = aoe.ActionGroup is not null + ? JsonSerializer.Serialize(aoe.ActionGroup, _jsonOpts) + : null, + ActionsJson = "[]", }); break; } @@ -4230,6 +4284,17 @@ public static class AbilitySystem Data = new TriggerEventData { SourceId = auraUnit.InstanceId, TargetId = targetUnitId }, }); ApplyAuraEffects(state, auraOwnerId, auraUnit, def, targetUnitId); + + // Execute one-shot OnEnterAuraActions (not duration-tracked, fired once on enter). + if (def.OnEnterAuraActions is not null) + { + var ctx = new AbilityContext { State = state, ActorId = auraOwnerId, Source = auraUnit }; + var resolved = ResolveActionGroup(def.OnEnterAuraActions, ctx, abilityIndex: 0, + range: def.AuraRange, forceDuration: null, continuationActions: []); + if (resolved is not null) + ExecuteActions(resolved, ctx, clientTargets: null, + restrictTargets: new HashSet { targetUnitId }); + } } else if (wasIn && !isIn) { @@ -4240,6 +4305,17 @@ public static class AbilitySystem Data = new TriggerEventData { SourceId = auraUnit.InstanceId, TargetId = targetUnitId }, }); HandleAuraLeave(state, auraUnit, def, targetUnitId, auraOwnerId); + + // Execute one-shot OnLeaveAuraActions (fired once on leave, regardless of ClearOnLeave). + if (def.OnLeaveAuraActions is not null) + { + var ctx = new AbilityContext { State = state, ActorId = auraOwnerId, Source = auraUnit }; + var resolved = ResolveActionGroup(def.OnLeaveAuraActions, ctx, abilityIndex: 0, + range: null, forceDuration: null, continuationActions: []); + if (resolved is not null) + ExecuteActions(resolved, ctx, clientTargets: null, + restrictTargets: new HashSet { targetUnitId }); + } } } } diff --git a/Server/src/SOR.Game/Abilities/Models/Effects.cs b/Server/src/SOR.Game/Abilities/Models/Effects.cs index aca2b8e..aa5fbc4 100644 --- a/Server/src/SOR.Game/Abilities/Models/Effects.cs +++ b/Server/src/SOR.Game/Abilities/Models/Effects.cs @@ -465,8 +465,8 @@ public sealed class ApplyOnEventEffect : Effect { public TriggerEvent Trigger { get; set; } = null!; /// - /// Full action tree executed when the trigger fires. Supports chained targeting and - /// nested ActionGroups. Replaces the old flat Effect[] for recursive ability trees. + /// Action tree executed when the trigger fires. Supports chained targeting and + /// nested ActionGroups via recursive ActionGroup. /// - public Action[] Actions { get; set; } = []; + public ActionGroup? ActionGroup { get; set; } } diff --git a/Server/src/SOR.Game/Abilities/Models/PendingTriggeredTarget.cs b/Server/src/SOR.Game/Abilities/Models/PendingTriggeredTarget.cs index 2b0f343..447ae5e 100644 --- a/Server/src/SOR.Game/Abilities/Models/PendingTriggeredTarget.cs +++ b/Server/src/SOR.Game/Abilities/Models/PendingTriggeredTarget.cs @@ -10,9 +10,16 @@ public sealed class PendingTriggeredTarget /// 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 must pick the target. + /// AccountId of the player whose ability triggered (the ability owner). public string ActorId { get; set; } = string.Empty; + /// + /// AccountId of the player who must actually pick the targets. + /// Equals when Chooser == Self; + /// set to an opponent or ally ID when Chooser == Opponent/Ally. + /// + public string ChooserActorId { get; set; } = string.Empty; + /// InstanceId of the unit whose triggered ability is paused. public string SourceInstanceId { get; set; } = string.Empty; diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index 099e0c7..cc75030 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -860,3 +860,53 @@ public sealed record GameCostPickRequest( /// Acknowledged response for a cost pick submission. public sealed record GameCostPickResponse(bool Success); +/// +/// Sent by the chooser to select which CostGroup option to pay when logic is OR/XOR. +/// +public sealed record GameCostGroupPickRequest( + Guid SessionId, + string RequestId, + /// 0-based index of the chosen cost option within the pending group. + int ChoiceIndex); + +/// Acknowledged response for a cost-group pick submission. +public sealed record GameCostGroupPickResponse(bool Success); + +/// +/// Sent by the chooser to select which ActionGroup branch to execute when logic is OR/XOR. +/// +public sealed record GameActionGroupPickRequest( + Guid SessionId, + string RequestId, + /// 0-based index of the chosen child action/group. + int ChoiceIndex); + +/// Acknowledged response for an action-group pick submission. +public sealed record GameActionGroupPickResponse(bool Success); + +/// +/// Sent by the chooser (Opponent/Ally) to pick a ChooseOne branch. +/// +public sealed record GameBranchPickRequest( + Guid SessionId, + string RequestId, + /// 0-based index of the chosen branch. + int BranchIndex); + +/// Acknowledged response for a branch pick submission. +public sealed record GameBranchPickResponse(bool Success); + +/// +/// Sent by the chooser to order the revealed cards (e.g. StackDeckEffect interactive). +/// +public sealed record GameRevealChoicePickRequest( + Guid SessionId, + string RequestId, + /// + /// 0-based indices of the revealed cards in the desired top-to-bottom order. + /// Cards not listed are placed at the bottom of the deck. + /// + int[] OrderedIndices); + +/// Acknowledged response for a reveal-choice pick submission. +public sealed record GameRevealChoicePickResponse(bool Success); diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs index 156eef7..28f345e 100644 --- a/Server/src/SOR.Game/GameState.cs +++ b/Server/src/SOR.Game/GameState.cs @@ -147,6 +147,18 @@ public sealed class GameState /// Paused until the chooser submits a game.reveal_choice_pick response. /// public Abilities.Models.PendingRevealChoicePick? PendingRevealChoicePick { get; set; } + + /// + /// Returns true when any interactive pause is in effect (ability execution must stop). + /// + public bool HasPendingInteraction() => + PendingCostPick is not null || + PendingCostGroupPick is not null || + PendingActionGroupPick is not null || + PendingBranchPick is not null || + PendingTilePick is not null || + PendingPlayerPick is not null || + PendingRevealChoicePick is not null; } public sealed class PlayerState @@ -422,8 +434,17 @@ public sealed class PendingDeferredEffect /// InstanceId (card) or AccountId (player) of the entity to apply effects to. public string TargetRef { get; set; } = string.Empty; - /// Serialized Action[] JSON — actions executed when the trigger fires. + /// + /// Serialized Action[] JSON — actions executed when the trigger fires. + /// Kept for backward-compatibility; superseded by when present. + /// public string ActionsJson { get; set; } = "[]"; + + /// + /// Serialized ActionGroup? JSON — full recursive action tree. When non-null, used in + /// preference to . + /// + public string? ActionGroupJson { get; set; } } /// diff --git a/Server/src/SOR.Game/Handlers/GameActionGroupPickHandler.cs b/Server/src/SOR.Game/Handlers/GameActionGroupPickHandler.cs new file mode 100644 index 0000000..1752c79 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameActionGroupPickHandler.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.action_group_pick — chooser selects which ActionGroup child to execute when +/// logic is OR/XOR. +/// +internal sealed class GameActionGroupPickHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameActionGroupPickHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.action_group_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.ResumeActionGroupPick( + state, actorId, req.RequestId, req.ChoiceIndex); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.action_group_pick", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson); + + return ServerMessage.Reply("game.action_group_pick.ack", message.Seq, + new GameActionGroupPickResponse(true)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameBranchPickHandler.cs b/Server/src/SOR.Game/Handlers/GameBranchPickHandler.cs new file mode 100644 index 0000000..015906e --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameBranchPickHandler.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.branch_pick — the non-activating player (Opponent/Ally chooser) selects which +/// ChooseOne branch to execute. +/// +internal sealed class GameBranchPickHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameBranchPickHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.branch_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.ResumeBranchPick( + state, actorId, req.RequestId, req.BranchIndex); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.branch_pick", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson); + + return ServerMessage.Reply("game.branch_pick.ack", message.Seq, + new GameBranchPickResponse(true)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameCostGroupPickHandler.cs b/Server/src/SOR.Game/Handlers/GameCostGroupPickHandler.cs new file mode 100644 index 0000000..5fba489 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameCostGroupPickHandler.cs @@ -0,0 +1,57 @@ +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.cost_group_pick — chooser selects which cost option to pay when a CostGroup +/// has OR/XOR logic requiring an interactive decision. +/// Resumes cost payment and then executes the ability actions. +/// +internal sealed class GameCostGroupPickHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameCostGroupPickHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.cost_group_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.ResumeCostGroupPick( + state, actorId, req.RequestId, req.ChoiceIndex); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.cost_group_pick", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson); + + return ServerMessage.Reply("game.cost_group_pick.ack", message.Seq, + new GameCostGroupPickResponse(true)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs index 80cdea6..e1d23b1 100644 --- a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs +++ b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs @@ -265,7 +265,11 @@ internal abstract class GameHandlerBase ? JsonSerializer.Serialize(firstClientPickAction) : pending.ActionsJson; // fallback: send raw actions list - await clientPush.PushAsync(pending.ActorId, + // Route to ChooserActorId (may be opponent/ally for Chooser.Opponent/Ally abilities). + var targetPlayer = string.IsNullOrEmpty(pending.ChooserActorId) + ? pending.ActorId + : pending.ChooserActorId; + await clientPush.PushAsync(targetPlayer, ServerMessage.Push("game.ability.triggered_target_request", new TriggeredTargetRequestPush( pending.RequestId, diff --git a/Server/src/SOR.Game/Handlers/GameRevealChoicePickHandler.cs b/Server/src/SOR.Game/Handlers/GameRevealChoicePickHandler.cs new file mode 100644 index 0000000..d6d370b --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameRevealChoicePickHandler.cs @@ -0,0 +1,57 @@ +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.reveal_choice_pick — the chooser submits the desired ordering of revealed +/// cards (e.g. StackDeckEffect interactive path). +/// Cards not listed in OrderedIndices are placed at the bottom of the deck. +/// +internal sealed class GameRevealChoicePickHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameRevealChoicePickHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.reveal_choice_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.ResumeRevealChoicePick( + state, actorId, req.RequestId, req.OrderedIndices); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.reveal_choice_pick", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson); + + return ServerMessage.Reply("game.reveal_choice_pick.ack", message.Seq, + new GameRevealChoicePickResponse(true)); + } +} diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs index 6ff7853..4d344a0 100644 --- a/Server/src/SOR.Game/ServiceRegistration.cs +++ b/Server/src/SOR.Game/ServiceRegistration.cs @@ -103,6 +103,18 @@ public static class ServiceRegistration // Interactive cost pick response (player submits card/unit selections for an interactive cost) services.AddTransient(); + // Interactive cost-group pick (chooser selects which OR/XOR cost option to pay) + services.AddTransient(); + + // Interactive action-group pick (chooser selects which OR/XOR action branch to execute) + services.AddTransient(); + + // ChooseOne branch pick (Opponent/Ally chooser selects a branch) + services.AddTransient(); + + // Reveal-choice pick (chooser orders revealed cards, e.g. StackDeck interactive) + services.AddTransient(); + return services; } }