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 <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-04-21 07:34:17 -04:00
co-authored by Claude Happy
parent 95c01cffb5
commit 0e85441fa1
13 changed files with 1102 additions and 29 deletions
@@ -26,6 +26,19 @@ public sealed class AbilityContext
/// Optional payload from the triggering event — available to Triggered ability actions.
/// </summary>
public TriggerEventData? EventData { get; init; }
/// <summary>
/// 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.
/// </summary>
public Models.Action[] ContinuationActions { get; set; } = [];
/// <summary>
/// Activation range propagated from the top-level ExecuteActions call.
/// Available to ExecuteEffect when it needs to store a continuation pause.
/// </summary>
public AbilityRange? ActivationRange { get; set; }
}
/// <summary>
+762 -24
View File
@@ -914,11 +914,28 @@ public static class AbilitySystem
{
// AND: run leaves then recurse into nested groups, flattening all.
var all = new List<Models.Action>(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<Models.Action[]>(
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<ActionGroup[]>(pending.RemainingGroupsJson, _jsonOpts)
: null;
if (remainingGroups is { Length: > 0 })
{
var tempList = new List<Models.Action>(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<Models.Action[]>(
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;
}
/// <summary>
/// Resumes an effect-level pause where the player must pick a specific tile
/// (e.g. CloneSpiritAsToken with DestinationScope=TargetTile).
/// Called by <c>GameTilePickHandler</c>.
/// </summary>
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<FieldCard>()
.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<FieldCard>()
.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<CardInstance>())
.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<Effect>(pending.EffectJson, _jsonOpts) as ChannelCardFromZoneEffect
: null;
// Affinity check.
if (ccze?.IgnoreAffinity != true && Enum.TryParse<Affinity>(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<Models.Action[]>(
pending.ContinuationActionsJson, _jsonOpts) ?? [];
if (continuation.Length > 0)
{
AbilityRange? range = pending.RangeJson is not null
? JsonSerializer.Deserialize<AbilityRange>(pending.RangeJson, _jsonOpts) : null;
DurationModel? forceDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize<DurationModel>(pending.ForceDurationJson, _jsonOpts) : null;
ExecuteActions(continuation, ctx, clientTargets: null, activationRange: range,
forceDuration: forceDuration);
}
return state;
}
/// <summary>
/// Resumes an effect-level pause where the player must pick another player
/// (e.g. ChannelCardFromZoneEffect with UnderControlOf=Choice).
/// Called by <c>GamePlayerPickHandler</c>.
/// </summary>
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<FieldCard>()
.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<CardInstance>())
.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<Effect>(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<Coord?>()
.FirstOrDefault();
}
else
{
ppCoord = ppBoard.Tiles.Values
.Where(t => t.IsEmpty)
.Select(t => t.Coord)
.OrderBy(_ => Random.Shared.Next())
.Cast<Coord?>()
.FirstOrDefault();
}
if (ppCoord is null) break;
// Affinity check.
if (ppCcze?.IgnoreAffinity != true && Enum.TryParse<Affinity>(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<Models.Action[]>(
pending.ContinuationActionsJson, _jsonOpts) ?? [];
if (ppContinuation.Length > 0)
{
AbilityRange? ppRange = pending.RangeJson is not null
? JsonSerializer.Deserialize<AbilityRange>(pending.RangeJson, _jsonOpts) : null;
DurationModel? ppForceDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize<DurationModel>(pending.ForceDurationJson, _jsonOpts) : null;
ExecuteActions(ppContinuation, ppCtx, clientTargets: null, activationRange: ppRange,
forceDuration: ppForceDuration);
}
return state;
}
/// <summary>
/// Resumes an active ability that was paused because a leaf Action had
/// <c>Chooser=Opponent/Ally</c> and needed the non-activating player to supply targets.
/// Called by <c>GameTargetPickHandler</c>.
/// </summary>
public static GameState ResumeTargetPick(
GameState state,
string actorId,
string requestId,
IReadOnlyList<AbilityTarget> 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<Models.Action>(pending.ActionJson, _jsonOpts)
?? throw new GameException("INVALID_TARGET_PICK_STATE");
var continuation = JsonSerializer.Deserialize<Models.Action[]>(
pending.ContinuationActionsJson, _jsonOpts) ?? [];
var source = state.Players.Values
.SelectMany(p => p.Field).OfType<FieldCard>()
.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<AbilityRange>(pending.RangeJson, _jsonOpts) : null;
DurationModel? forceDuration = pending.ForceDurationJson is not null
? JsonSerializer.Deserialize<DurationModel>(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<string>? 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<Coord?>()
.FirstOrDefault();
}
else
{
ccDestCoord = board.Tiles.Values
.Where(t => t.IsEmpty)
.Select(t => t.Coord)
.OrderBy(_ => Random.Shared.Next())
.Cast<Coord?>()
.FirstOrDefault();
}
if (ccDestCoord is null) break;
// Affinity check.
if (!ccze.IgnoreAffinity && Enum.TryParse<Affinity>(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<Coord>().FirstOrDefault()
: (Coord?)null,
"TargetTile" when ctx.ResolvedTargets.Count > 0 &&
ctx.ResolvedTargets.Values.SelectMany(x => x).OfType<Coord>().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<Coord?>()
.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;
}
/// <summary>
/// Returns the InstanceIds of all units currently carrying an <see cref="ObstructMovementTypeEffect"/>
/// active effect that obstructs <paramref name="movType"/>.
/// Used by <see cref="GameEngine"/> to extend pathfinding blocked-sets.
/// </summary>
internal static HashSet<string> GetUnitsObstructingMovementType(GameState state, MovementType movType)
{
var result = new HashSet<string>();
foreach (var ae in state.ActiveEffects)
{
Effect? eff;
try { eff = JsonSerializer.Deserialize<Effect>(ae.EffectJson, _jsonOpts); }
catch { continue; }
if (eff is ObstructMovementTypeEffect omte && omte.MovementType == movType)
result.Add(ae.TargetRef);
}
return result;
}
/// <summary>Find the first card in the given zone ("Hand"|"Deck"|"Discard"|"Any") matching predicate.</summary>
private static CardInstance? FindInZone(PlayerState player, string zone, Func<CardInstance, bool> 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),
};
/// <summary>Remove a card from the specified zone ("Hand"|"Deck"|"Discard"|"Any").</summary>
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<Coord> OrthogonalNeighbours(Coord c)
=>
[
@@ -28,9 +28,16 @@ public sealed class PendingActionGroupPick
/// </summary>
public string ActionGroupJson { get; set; } = "{}";
/// <summary>JSON-serialized Action[] — the full action list to execute AFTER the picked branch finishes.</summary>
/// <summary>JSON-serialized Action[] — the full action list to execute AFTER the picked branch and all remaining groups finish.</summary>
public string ContinuationActionsJson { get; set; } = "[]";
/// <summary>
/// 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.
/// </summary>
public string? RemainingGroupsJson { get; set; }
/// <summary>JSON-serialized AbilityRange? — passed through to ExecuteActions on resume.</summary>
public string? RangeJson { get; set; }
@@ -22,6 +22,18 @@ public sealed class PendingPlayerPick
/// <summary>Account IDs of the valid choices (populated by engine at pause time).</summary>
public List<string> ValidPlayerIds { get; set; } = new();
/// <summary>
/// InstanceId of the primary target that was already resolved before the pick
/// (e.g. the card to channel for ChannelCardFromZoneEffect). Empty when not applicable.
/// </summary>
public string TargetInstanceId { get; set; } = string.Empty;
/// <summary>
/// Serialized Effect JSON — used when the resume handler needs the original effect's parameters
/// (e.g. ChannelCardFromZoneEffect flags). Null when not needed.
/// </summary>
public string? EffectJson { get; set; }
// ── Continuation ─────────────────────────────────────────────────────────
public string ContinuationActionsJson { get; set; } = "[]";
@@ -0,0 +1,42 @@
namespace SOR.Game.Abilities.Models;
/// <summary>
/// Stored in GameState when a leaf Action has <c>TargetSelector.Chooser = Opponent</c> or
/// <c>Ally</c> 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 <c>game.target_pick</c> response.
/// </summary>
public sealed class PendingTargetPick
{
/// <summary>Correlation ID sent to the client so responses can be matched.</summary>
public string RequestId { get; set; } = Guid.NewGuid().ToString("N");
/// <summary>AccountId of the player who activated the ability.</summary>
public string ActorId { get; set; } = string.Empty;
/// <summary>
/// AccountId of the player who must submit the target picks.
/// May differ from <see cref="ActorId"/> for Chooser=Opponent/Ally actions.
/// </summary>
public string ChooserActorId { get; set; } = string.Empty;
/// <summary>InstanceId of the source unit (may be empty for card-triggered abilities).</summary>
public string SourceInstanceId { get; set; } = string.Empty;
/// <summary>
/// JSON-serialized <see cref="Action"/> — the action awaiting target picks.
/// The full TargetSelector (Scope/Type/Ownership/Count/Filters) is embedded so the
/// client can present the correct picker UI.
/// </summary>
public string ActionJson { get; set; } = "{}";
/// <summary>JSON-serialized Action[] — remaining actions to execute after this one resolves.</summary>
public string ContinuationActionsJson { get; set; } = "[]";
/// <summary>JSON-serialized AbilityRange? — passed through to ExecuteActions on resume.</summary>
public string? RangeJson { get; set; }
/// <summary>JSON-serialized DurationModel? — forceDuration applied on resume.</summary>
public string? ForceDurationJson { get; set; }
}
@@ -26,6 +26,25 @@ public sealed class PendingTilePick
/// <summary>Max tiles from source; 0 = unlimited.</summary>
public int MaxRange { get; set; }
/// <summary>
/// InstanceId of the primary target that was already resolved before the pick
/// (e.g. the Spirit to clone for CloneSpiritAsToken). Empty when not applicable.
/// </summary>
public string TargetInstanceId { get; set; } = string.Empty;
/// <summary>
/// For ChannelCardFromZone: AccountId of the player who will control the channeled card.
/// Empty when not applicable.
/// </summary>
public string DestPlayerAccountId { get; set; } = string.Empty;
/// <summary>
/// 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.
/// </summary>
public string? EffectJson { get; set; }
// ── Continuation ─────────────────────────────────────────────────────────
public string ContinuationActionsJson { get; set; } = "[]";
+17 -3
View File
@@ -1475,20 +1475,30 @@ public static class GameEngine
GameState state, string movingUnitId, MovementType? movType)
{
var blocked = new HashSet<Coord>();
// Units that additionally obstruct the moving unit's movement type via active effects.
HashSet<string>? extraObstructors = movType.HasValue
? AbilitySystem.GetUnitsObstructingMovementType(state, movType.Value)
: null;
foreach (var player in state.Players.Values)
{
foreach (var card in player.Field.OfType<FieldCard>())
{
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.
/// </summary>
/// <summary>Internal helper exposed to AbilitySystem for effect-level ArchSpirit swaps.</summary>
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()
{
+39
View File
@@ -910,3 +910,42 @@ public sealed record GameRevealChoicePickRequest(
/// <summary>Acknowledged response for a reveal-choice pick submission.</summary>
public sealed record GameRevealChoicePickResponse(bool Success);
/// <summary>
/// Sent by the chooser (Opponent/Ally) to supply target picks for a paused leaf action.
/// The same <see cref="AbilityTarget"/> shape used by game.activate_ability is reused here.
/// </summary>
public sealed record GameTargetPickRequest(
Guid SessionId,
string RequestId,
IReadOnlyList<AbilityTarget> Targets);
/// <summary>Acknowledged response for a target pick submission.</summary>
public sealed record GameTargetPickResponse(bool Success);
/// <summary>
/// Sent by the chooser to pick a specific tile for an effect that requires one
/// (e.g. CloneSpiritAsToken with DestinationScope=TargetTile).
/// </summary>
public sealed record GameTilePickRequest(
Guid SessionId,
string RequestId,
/// <summary>The chosen tile coordinates.</summary>
int X,
int Y);
/// <summary>Acknowledged response for a tile pick submission.</summary>
public sealed record GameTilePickResponse(bool Success);
/// <summary>
/// Sent by the chooser to pick a specific player for an effect that requires one
/// (e.g. ChannelCardFromZoneEffect with UnderControlOf=Choice).
/// </summary>
public sealed record GamePlayerPickRequest(
Guid SessionId,
string RequestId,
/// <summary>AccountId of the chosen player.</summary>
string PickedPlayerId);
/// <summary>Acknowledged response for a player pick submission.</summary>
public sealed record GamePlayerPickResponse(bool Success);
+9 -1
View File
@@ -148,6 +148,13 @@ public sealed class GameState
/// </summary>
public Abilities.Models.PendingRevealChoicePick? PendingRevealChoicePick { get; set; }
/// <summary>
/// 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 <c>game.target_pick</c> response.
/// </summary>
public Abilities.Models.PendingTargetPick? PendingTargetPick { get; set; }
/// <summary>
/// Returns true when any interactive pause is in effect (ability execution must stop).
/// </summary>
@@ -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
@@ -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;
/// <summary>
/// game.player_pick — player picks a specific player for an effect-level player selection
/// (e.g. ChannelCardFromZoneEffect with UnderControlOf=Choice).
/// </summary>
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<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GamePlayerPickRequest>(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));
}
}
@@ -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;
/// <summary>
/// game.target_pick — opponent or ally submits target picks for a paused leaf action
/// whose <c>TargetSelector.Chooser</c> was <c>Opponent</c> or <c>Ally</c>.
///
/// Resumes execution of the paused action (and its continuation) then broadcasts
/// the updated game state to all players.
/// </summary>
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<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GameTargetPickRequest>(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));
}
}
@@ -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;
/// <summary>
/// game.tile_pick — player picks a specific tile for an effect-level tile selection
/// (e.g. CloneSpiritAsToken with DestinationScope=TargetTile).
/// </summary>
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<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GameTilePickRequest>(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));
}
}
@@ -115,6 +115,15 @@ public static class ServiceRegistration
// Reveal-choice pick (chooser orders revealed cards, e.g. StackDeck interactive)
services.AddTransient<IMessageHandler, GameRevealChoicePickHandler>();
// Target pick (opponent/ally submits targets for a Chooser=Opponent/Ally action)
services.AddTransient<IMessageHandler, GameTargetPickHandler>();
// Tile pick (player selects a tile for an effect-level tile selection)
services.AddTransient<IMessageHandler, GameTilePickHandler>();
// Player pick (player selects a player for an effect-level player selection)
services.AddTransient<IMessageHandler, GamePlayerPickHandler>();
return services;
}
}