feat(phase5+6): engine ActionGroup compat, new conditions, Ruin bug fixes

Phase 5.1a — ActionGroup backward-compat in AbilitySystem:
- Add GetEffectiveActions(def): prefers ActionGroup.Actions (AND=sequential,
  OR/XOR=random pick); falls back to obsolete def.Actions for pre-Phase-1 rows.
- Wire all FireAbility, FireCardEffects, FireTrigger, FireRuinAbilities call
  sites to use GetEffectiveActions instead of def.Actions directly.

Phase 5.9 — 12 new EvaluateCondition cases (§6.6):
UnitTypeIs, OwnershipIs, IsThisCard, UnitPropertyCompare, PlayerPropertyCompare,
HandContainsCount, CardDefinitionCountInZone, IsInRangeOfUnit, TileOccupant,
SurroundingTile, SPAccumulationCompare, CostOfCardsInHand.
Add CompareInt(Comparator, int, int) helper to DRY up comparator switch.

Phase 6-D — Fix double-fire of source Ruin's OnRuinActivation abilities:
Insert source-skip guard in FireTrigger after TriggerMatches check:
skip OnRuinActivationTrigger on the card whose InstanceId == occurrence.Data.SourceId.
FireRuinAbilities already executed the chosen ability directly; the subsequent
FireTrigger is only for observer cards.

Phase 6-C — Ruin tile placement must not overwrite existing Ruins (GameEngine.cs):
Add `&& t.RuinId == null` to the validTiles Where clause.
Change error code NO_VALID_TILE → NO_VALID_RUIN_TILE for this path.

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-20 13:57:15 -04:00
co-authored by Claude Happy
parent da220f353d
commit 178f5612a8
2 changed files with 195 additions and 9 deletions
+192 -7
View File
@@ -114,11 +114,11 @@ public static class AbilitySystem
if (def.Cost is { Length: > 0 })
{
bool paused = PayCosts(def.Cost, ctx, abilityIndex, def.Actions, def.Range, def.Duration);
bool paused = PayCosts(def.Cost, ctx, abilityIndex, GetEffectiveActions(def), def.Range, def.Duration);
if (paused) return state; // waiting for client cost pick
}
ExecuteActions(def.Actions, ctx, clientTargets, requireClientTargets: true, activationRange: def.Range, forceDuration: def.Duration);
ExecuteActions(GetEffectiveActions(def), ctx, clientTargets, requireClientTargets: true, activationRange: def.Range, forceDuration: def.Duration);
return state;
}
@@ -142,7 +142,7 @@ public static class AbilitySystem
if (!ValidateSourceActivationConditions(def, ctx, card))
continue;
ExecuteActions(def.Actions, ctx, clientTargets, requireClientTargets: true,
ExecuteActions(GetEffectiveActions(def), ctx, clientTargets, requireClientTargets: true,
activationRange: def.Range, forceDuration: def.Duration);
}
@@ -216,6 +216,14 @@ public static class AbilitySystem
if (!TriggerMatches(def.TriggerEvent, occurrence, state, ownerId,
card is FieldCard fc3 ? fc3 : null)) continue;
// 6-D: Prevent double-firing the source Ruin's own OnRuinActivation abilities.
// FireRuinAbilities already executed one chosen ability directly; the subsequent
// FireTrigger call is only for observer cards. Skip the source Ruin itself.
if (occurrence.Kind == TriggerEventKind.RuinActivation
&& def.TriggerEvent is OnRuinActivationTrigger
&& card.InstanceId == occurrence.Data?.SourceId)
continue;
var ctx = new AbilityContext
{
State = state,
@@ -251,14 +259,15 @@ public static class AbilitySystem
}
// If any action needs a human pick, pause and request client input.
if (def.Actions.Any(ActionNeedsClientTargets))
var effectiveActions = GetEffectiveActions(def);
if (effectiveActions.Any(ActionNeedsClientTargets))
{
state.PendingTriggeredTarget = new PendingTriggeredTarget
{
ActorId = ownerId,
SourceInstanceId = card.InstanceId,
AbilityName = def.Name ?? "Triggered Ability",
ActionsJson = JsonSerializer.Serialize(def.Actions, _jsonOpts),
ActionsJson = JsonSerializer.Serialize(effectiveActions, _jsonOpts),
RangeJson = def.Range is not null
? JsonSerializer.Serialize(def.Range, _jsonOpts)
: null,
@@ -270,7 +279,7 @@ public static class AbilitySystem
return state;
}
ExecuteActions(def.Actions, ctx, clientTargets: null, forceDuration: def.Duration);
ExecuteActions(effectiveActions, ctx, clientTargets: null, forceDuration: def.Duration);
}
}
}
@@ -361,7 +370,7 @@ public static class AbilitySystem
// Select exactly one ability at random.
var chosen = eligible[Random.Shared.Next(eligible.Count)];
ExecuteActions(chosen.Actions, ctx, clientTargets: null);
ExecuteActions(GetEffectiveActions(chosen), ctx, clientTargets: null);
// Notify observer cards that the ruin activated.
FireTrigger(state, new TriggerOccurrence
@@ -628,6 +637,27 @@ public static class AbilitySystem
return state;
}
// ── ActionGroup backward-compat ───────────────────────────────────────────
/// <summary>
/// Returns the effective action list for an ability, preferring ActionGroup when present.
/// AND groups run all leaf actions sequentially (same as the old flat list).
/// OR/XOR groups pick one leaf action at random for now (full interactive
/// PendingActionGroupPick support is deferred to a future pass).
/// Falls back to <see cref="AbilityDefinition.Actions"/> for pre-Phase-1 data.
/// </summary>
private static Models.Action[] GetEffectiveActions(AbilityDefinition def)
{
if (def.ActionGroup is { } ag)
{
if (ag.LogicOp == ActionGroupLogicOp.And || ag.Actions.Length == 0)
return ag.Actions;
// OR / XOR: pick one leaf at random (server-side interim)
return [ag.Actions[Random.Shared.Next(ag.Actions.Length)]];
}
return def.Actions; // backward-compat: pre-Phase-1 rows use the flat array
}
// ── Action execution ──────────────────────────────────────────────────────
private static void ExecuteActions(
@@ -2332,11 +2362,166 @@ public static class AbilitySystem
};
}
// ── §6.6 Extended unit / player conditions ───────────────────────────
case UnitTypeIsCondition uti when subject is CardInstance utiCard:
return utiCard.CardType == uti.UnitType;
case OwnershipIsCondition oi:
{
var ownerPlayer = subject is CardInstance ownCard
? FindCardOwner(ctx.State, ownCard.InstanceId) : null;
if (ownerPlayer is null) return false;
return OwnershipMatchesForPlayer(oi.Ownership, ownerPlayer.AccountId, ctx.ActorId, ctx.State);
}
case IsThisCardCondition when subject is CardInstance thisCard:
return ctx.Source is CardInstance srcCard && srcCard.InstanceId == thisCard.InstanceId;
case UnitPropertyCompareCondition upc when subject is CardInstance upcCard:
{
int val = upc.PropertyName switch
{
"Damage" => upcCard.Damage ?? 0,
"Defense" => upcCard.CurrentDefense ?? 0,
"MaxDefense" => upcCard.MaxDefense ?? 0,
"Health" => upcCard.CurrentHealth ?? 0,
"MaxHealth" => upcCard.MaxHealth ?? 0,
"MovementPoints" => upcCard is FieldCard fcMp ? fcMp.CurrentMp : 0,
"MaxMovementPoints" => upcCard.MaxMp ?? 0,
"MinAttackRange" => upcCard.MinAttackRange ?? 0,
"MaxAttackRange" => upcCard.MaxAttackRange ?? 0,
"MinChannelRange" => upcCard.MinChannelRange ?? 0,
"MaxChannelRange" => upcCard.MaxChannelRange ?? 0,
"Tier" => upcCard.Tier ?? 0,
_ => 0,
};
return CompareInt(upc.Comparator, val, upc.Value);
}
case PlayerPropertyCompareCondition ppc:
{
var targetPlayer = ppc.Subject.ToLowerInvariant() switch
{
"opponent" => ctx.State.Players.Values.FirstOrDefault(p => p.AccountId != ctx.ActorId),
_ => player, // "self" | "owner" | "ally" → same player in a 2-player game
};
if (targetPlayer is null) return false;
int val = ppc.PropertyName switch
{
"SP" => targetPlayer.CurrentSp,
"ST" => targetPlayer.CurrentSt,
"SPAccumulation" => ctx.State.Rules.SpAccumulationPerTurn + targetPlayer.SpAccumulationBonus,
"HandSize" => targetPlayer.Hand.Count,
"DeckSize" => targetPlayer.Deck.Count,
"DiscardSize" => targetPlayer.Discard.Count,
_ => 0,
};
return CompareInt(ppc.Comparator, val, ppc.Value);
}
case HandContainsCountCondition hcc:
{
var cnt = player.Hand.Count(c =>
(hcc.CardType is null || c.CardType == hcc.CardType)
&& (hcc.Affinity is null || c.Affinity == hcc.Affinity.ToString()));
return CompareInt(hcc.Comparator, cnt, hcc.N);
}
case CardDefinitionCountInZoneCondition cdciz when subject is CardInstance defCard:
{
var defId = defCard.CardDefinitionId;
var cnt = ctx.State.Players.Values
.Where(p => cdciz.Ownership.ToLowerInvariant() == "any"
|| OwnershipMatchesForPlayer(cdciz.Ownership, p.AccountId, ctx.ActorId, ctx.State))
.SelectMany(p => cdciz.Zone.ToLowerInvariant() switch
{
"hand" => p.Hand.AsEnumerable(),
"deck" => p.Deck.AsEnumerable(),
"discard" => p.Discard.AsEnumerable(),
"battlefield" => p.Field.AsEnumerable(),
_ => Enumerable.Empty<CardInstance>(),
})
.Count(c => c.CardDefinitionId == defId);
return CompareInt(cdciz.Comparator, cnt, cdciz.N);
}
case IsInRangeOfUnitCondition irru when subject is FieldCard fcIrru && fcIrru.Position.HasValue:
{
if (ctx.State.Board is null) return false;
return ctx.State.Players.Values
.SelectMany(p => p.Field.OfType<FieldCard>())
.Where(u => u.InstanceId != fcIrru.InstanceId && u.Position.HasValue)
.Where(u => irru.UnitType == "Unit" || u.CardType == irru.UnitType)
.Where(u =>
{
var op = FindCardOwner(ctx.State, u.InstanceId);
return op is not null
&& OwnershipMatchesForPlayer(irru.Ownership, op.AccountId, ctx.ActorId, ctx.State);
})
.Where(u => irru.UnitFilters is null || FiltersMatch(irru.UnitFilters, u, ctx))
.Any(u =>
{
var d = fcIrru.Position!.Value.ManhattanDistance(u.Position!.Value);
return d >= irru.Min && d <= irru.Max;
});
}
case TileOccupantCondition toc when subject is FieldCard fcToc && fcToc.Position.HasValue:
{
var tile = ctx.State.Board?.GetTile(fcToc.Position.Value);
if (tile is null || tile.IsEmpty || tile.OccupantId is null || tile.OccupantOwner is null) return false;
if (!OwnershipMatchesForPlayer(toc.Ownership, tile.OccupantOwner, ctx.ActorId, ctx.State)) return false;
var occupant = ctx.State.Players.Values.SelectMany(p => p.Field)
.FirstOrDefault(u => u.InstanceId == tile.OccupantId);
if (occupant is null) return false;
if (toc.UnitType != "Unit" && occupant.CardType != toc.UnitType) return false;
return toc.UnitFilters is null || FiltersMatch(toc.UnitFilters, occupant, ctx);
}
case SurroundingTileCondition stc when subject is FieldCard fcStc && fcStc.Position.HasValue:
{
if (ctx.State.Board is null) return false;
var cnt = ctx.State.Board.Tiles.Values
.Where(t =>
{
var d = fcStc.Position!.Value.ManhattanDistance(t.Coord);
return d >= stc.Min && d <= stc.Max;
})
.Count(t => stc.TileFilters is null || TileMatchesFilters(stc.TileFilters, t, ctx));
return CompareInt(stc.TileCountComparator, cnt, stc.TileCount);
}
case SPAccumulationCompareCondition spac:
{
var total = ctx.State.Rules.SpAccumulationPerTurn + player.SpAccumulationBonus;
return CompareInt(spac.Comparator, total, spac.Value);
}
case CostOfCardsInHandCondition cochc:
{
var total = player.Hand
.Where(c => (cochc.CardType is null || c.CardType == cochc.CardType)
&& (cochc.Affinity is null || c.Affinity == cochc.Affinity.ToString()))
.Sum(c => cochc.CostType == "ST" ? c.StCost : c.SpCost);
return CompareInt(cochc.Comparator, total, cochc.Value);
}
default:
return true;
}
}
private static bool CompareInt(Comparator c, int actual, int threshold) => c switch
{
Comparator.Equal => actual == threshold,
Comparator.NotEqual => actual != threshold,
Comparator.LessThan => actual < threshold,
Comparator.LessThanOrEqual => actual <= threshold,
Comparator.GreaterThan => actual > threshold,
Comparator.GreaterThanOrEqual => actual >= threshold,
_ => false,
};
// ── Filter evaluation ─────────────────────────────────────────────────────
private static bool FiltersMatch(Filter[] filters, CardInstance card, AbilityContext ctx)
+3 -2
View File
@@ -413,9 +413,10 @@ public static class GameEngine
// Place on a random tile matching the Ruin's affinity (may already be occupied).
var hasAffinity = Enum.TryParse<Affinity>(card.Affinity, out var ruinAffinity);
var validTiles = board.Tiles.Values
.Where(t => !hasAffinity || AffinitySystem.IsAffinityValid(t, ruinAffinity))
.Where(t => (!hasAffinity || AffinitySystem.IsAffinityValid(t, ruinAffinity))
&& t.RuinId == null) // 6-C: never overwrite an existing Ruin
.ToList();
if (validTiles.Count == 0) throw new GameException("NO_VALID_TILE");
if (validTiles.Count == 0) throw new GameException("NO_VALID_RUIN_TILE");
var ruinCoord = validTiles[Random.Shared.Next(validTiles.Count)].Coord;