Ability system: zone-scope card picks, target-pick prompts, builder filter editor, tests

Server engine (SOR.Game):
- Zone-scope card targets (Hand/Deck/Discard/AnyZone) pause with a server-
  enumerated candidates list (PendingTargetPick.CandidatesJson) instead of
  failing when the client submits player accountIds for hidden zones
- Missing mandatory target picks now prompt (PendingTargetPick) rather than
  throwing INSUFFICIENT_TARGETS; all post-pick resume flows run with
  requireClientTargets so actions never silently auto-hit the first candidate
- ChannelCardFromZone: Filters + InOwn/InTargetChannelRange enforced via shared
  IsWithinChannelConstraints (incl. player-picked tile validation)
- TakeControl duration reversal via internal __ReturnControl effect; board
  occupant-owner kept in sync both ways
- TrackedDuration gains SourceOwnerAccountId (UntilStartOfSourceOwnerTurn now
  anchors correctly) and IsAura (aura reapply no longer strips unrelated buffs)
- RevealCards honours N for player targets; IsAllyTurn means teammate's turn;
  content-keyed ParseAbilities cache; AbilityValidator for save-time linting;
  duplicate PolyType attributes removed (converter reads base registry only)

Admin builder (AbilityBuilder/CardEditor):
- Full multi-filter editor (28 filter types with parameter fields) replacing
  the single param-less dropdown; raw-JSON ChooseOne editor per action
- Cost PickMode, TriggerLimitPerGame, SourceZoneGate inputs
- Save-time ability validation with error list (blocks invalid saves)

Client (Godot):
- Card-list picker for zone-scope target picks; OR/XOR-root abilities skip
  speculative upfront targeting; ally units included in team-aware highlight
  pools (Game.get_ally_units); state re-sync on rejected pick responses

Tests: new SOR.Game.Tests project (21 passing) covering the regression suite
from SOR.Abilities-Review-and-solutions.md §8 plus validator rules.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-07-04 06:23:17 -04:00
co-authored by Claude Fable 5
parent b96b8b89c0
commit 4961696fee
19 changed files with 2095 additions and 175 deletions
+31 -1
View File
@@ -260,6 +260,24 @@ func get_all_enemy_units() -> Array:
return units
## Returns all units (field + archSpirit) belonging to allied players
## (same team, not the local player). Empty in FFA games.
func get_ally_units() -> Array:
var my_team : int = int(get_my_player().get("teamIndex", -1))
var units : Array = []
if my_team < 0:
return units
for p: Dictionary in state.get("players", []):
var pid : String = str(p.get("accountId", ""))
if pid == Auth.user_id: continue
if int(p.get("teamIndex", -2)) != my_team: continue
units.append_array(_as_array(p.get("field", [])))
var arch = p.get("archSpirit")
if arch is Dictionary and not (arch as Dictionary).is_empty():
units.append(arch)
return units
## Returns a TileDto dict by coord, or {}.
func get_tile(x: int, y: int) -> Dictionary:
for t: Dictionary in get_tiles():
@@ -468,6 +486,16 @@ func send_reveal_choice_pick_response(request_id: String, ordered_indices: Array
# ── Private ───────────────────────────────────────────────────────────────────
## Pick/response messages where the client optimistically tears down its prompt UI
## before the server confirms. If the server rejects the pick, the pending prompt
## still exists server-side — re-fetching state makes GameGetStateHandler re-push
## it so the player is never stuck without a prompt.
const _PROMPT_RESPONSE_TYPES: Array[String] = [
"game.triggered_target", "game.cost_pick", "game.cost_group_pick",
"game.action_group_pick", "game.branch_pick", "game.target_pick",
"game.tile_pick", "game.player_pick", "game.reveal_choice_pick",
]
func _game_request(msg_type: String, extra: Dictionary) -> void:
var payload := { "sessionId": session_id }
payload.merge(extra)
@@ -480,7 +508,9 @@ func _game_request(msg_type: String, extra: Dictionary) -> void:
_apply_state_from_payload(p),
func(code: String, msg: String) -> void:
if debug_output:
print("[Game] ERR ", msg_type, " code=", code, " msg=", msg))
print("[Game] ERR ", msg_type, " code=", code, " msg=", msg)
if msg_type in _PROMPT_RESPONSE_TYPES:
_fetch_state())
func _apply_state_from_payload(p: Variant) -> void:
@@ -360,20 +360,21 @@ func highlight_ability_targets(action: Dictionary) -> void:
emit_signal("highlight_add_requested", tx, ty, "ability")
return
# Unit-type target.
var include_enemy: bool = ownership in ["Enemy", "Any"]
var include_friendly: bool = ownership in ["Owner", "Ally", "Any"]
if not include_enemy and not include_friendly:
include_enemy = true
# Unit-type target. Pools mirror the server's team-aware BuildCandidates:
# Owner = own units only, Ally = teammates only, Enemy = non-allies, Any = everyone.
var targets: Array = []
if include_enemy:
if ownership in ["Enemy", "Any"]:
targets.append_array(Game.get_all_enemy_units())
if include_friendly:
if ownership in ["Owner", "Any"]:
targets.append_array(Game.get_field())
var my_arch: Dictionary = Game.get_my_player().get("archSpirit", {})
if not my_arch.is_empty():
targets.append(my_arch)
if ownership in ["Ally", "Any"]:
targets.append_array(Game.get_ally_units())
if targets.is_empty() and not ownership in ["Owner", "Ally", "Enemy", "Any"]:
# Unknown ownership string — fall back to enemies (legacy behaviour).
targets.append_array(Game.get_all_enemy_units())
for u: Dictionary in targets:
if type_ in ["Spirit", "ArchSpirit", "SpiritToken", "Ruin"]:
@@ -511,6 +512,50 @@ func unit_passes_filters(unit: Dictionary, filters: Array) -> bool:
int(src_pos.get("x", 0)), int(src_pos.get("y", 0)))
if dist != 1:
return false
"genuscontains":
var genus_v: Variant = unit.get("genus")
var genus: Array = genus_v as Array if genus_v is Array else []
if not genus.has(str(f.get("tag", ""))):
return false
"cardtypeis":
if str(unit.get("cardType", "")) != str(f.get("cardtype", f.get("cardType", ""))):
return false
"affinitymatches":
if str(unit.get("affinity", "")) != str(f.get("affinity", "")):
return false
"tieris":
if int(unit.get("tier", 0)) != int(f.get("tier", 0)):
return false
"healthbelow":
if int(unit.get("currentHealth", 0)) >= int(f.get("n", 0)):
return false
"healthabove":
if int(unit.get("currentHealth", 0)) <= int(f.get("n", 0)):
return false
"damagerange":
var dmg: int = int(unit.get("damage", 0))
if dmg < int(f.get("min", 0)) or dmg > int(f.get("max", 999)):
return false
"defenserange":
var def_: int = int(unit.get("currentDefense", 0))
if def_ < int(f.get("min", 0)) or def_ > int(f.get("max", 999)):
return false
"ownership":
var uid: String = str(unit.get("instanceId", ""))
match str(f.get("ownership", "Any")).to_lower():
"self", "owner", "ally":
if unit_registry != null and not unit_registry.friendly_unit_ids.has(uid):
return false
"enemy", "opponent":
if unit_registry != null and not unit_registry.enemy_unit_ids.has(uid):
return false
"isself":
# Same card definition as the ability source.
if str(unit.get("cardDefinitionId", "")) != str(src.get("cardDefinitionId", "")):
return false
"isexactself":
if str(unit.get("instanceId", "")) != ability_unit_id:
return false
for cond: Dictionary in ability_target_conditions:
match str(cond.get("$type", "")).to_lower():
"isontilewithaffinity":
@@ -578,6 +623,33 @@ func tile_passes_filters(tx: int, ty: int, filters: Array) -> bool:
var tile: Dictionary = Game.get_tile(tx, ty)
if tile.get("occupantId", null) != null:
return false
"tileisoccupied":
var tile: Dictionary = Game.get_tile(tx, ty)
var occ_v: Variant = tile.get("occupantId")
if occ_v == null or str(occ_v).is_empty():
return false
var want_type: String = str(f.get("unittype", f.get("unitType", "")))
if not want_type.is_empty() and want_type != "Unit":
var occ_unit: Dictionary = Game.get_unit_by_id(str(occ_v))
if str(occ_unit.get("cardType", "")) != want_type:
return false
"tileoccupancy":
var tile: Dictionary = Game.get_tile(tx, ty)
var occ_v: Variant = tile.get("occupantId")
if occ_v == null or str(occ_v).is_empty():
return false
var occ_id: String = str(occ_v)
var occ_unit: Dictionary = Game.get_unit_by_id(occ_id)
var want_type: String = str(f.get("unittype", f.get("unitType", "Unit")))
if want_type != "Unit" and str(occ_unit.get("cardType", "")) != want_type:
return false
match str(f.get("ownership", "Any")).to_lower():
"self", "owner", "ally":
if unit_registry != null and not unit_registry.friendly_unit_ids.has(occ_id):
return false
"enemy", "opponent":
if unit_registry != null and not unit_registry.enemy_unit_ids.has(occ_id):
return false
return true
@@ -859,7 +931,14 @@ func get_ability_actions(ab: Dictionary) -> Array:
return legacy
var ag: Variant = ab.get("actiongroup")
if ag is Dictionary:
return flatten_and_group(ag as Dictionary)
var group: Dictionary = ag as Dictionary
# OR/XOR root group: the server either pauses for an action_group_pick BEFORE
# costs (Self/Opponent chooser) or picks one child at index 0 (Random) — either
# way upfront targets collected against the flattened list would misalign and be
# discarded. The server re-prompts for whatever targets the chosen branch needs.
if str(group.get("logicop", "and")).to_lower() != "and":
return []
return flatten_and_group(group)
return []
@@ -319,11 +319,25 @@ func on_branch_pick_request(req: Dictionary) -> void:
# ── PendingTargetPick ─────────────────────────────────────────────────────────
# Zone-scope card pick accumulation
var target_pick_selected: Array = [] # [{actionIndex, instanceId}]
var target_pick_required: int = 1
var target_pick_up_to: bool = false
func on_target_pick_request(req: Dictionary) -> void:
_cancel_current_mode()
if ability_targeting == null:
return
# Zone-scope pick: the server sends an explicit candidates list (hidden zones) —
# show a card list panel instead of board targeting.
var candidates_json: String = str(req.get("candidatesJson", ""))
if not candidates_json.is_empty() and candidates_json != "null" and candidates_json != "<null>":
var cand_raw: Variant = JSON.parse_string(candidates_json)
if cand_raw is Array and not (cand_raw as Array).is_empty():
_show_zone_target_panel(req, cand_raw as Array)
return
ability_targeting.is_target_pick = true
ability_targeting.pending_req_id = str(req.get("requestId", ""))
pending_req_id = ability_targeting.pending_req_id
@@ -356,6 +370,79 @@ func on_target_pick_request(req: Dictionary) -> void:
ability_targeting.ability_targets_this_action = 0
ability_targeting.start_ability_targeting()
## Card-list picker for zone-scope target picks (hand/deck/discard candidates
## enumerated by the server). Resumed action is replayed at index 0 server-side,
## so picks are submitted with actionIndex 0.
func _show_zone_target_panel(req: Dictionary, candidates: Array) -> void:
pending_req_id = str(req.get("requestId", ""))
pending_source_id = str(req.get("sourceInstanceId", ""))
target_pick_selected.clear()
target_pick_required = 1
target_pick_up_to = false
# Count requirements come from the action's target selector.
var action_raw: Variant = JSON.parse_string(str(req.get("actionJson", "{}")))
if action_raw is Dictionary:
var action_n: Dictionary = _normalize_keys(action_raw) as Dictionary
var count_d: Dictionary = (action_n.get("target", {}) as Dictionary).get("count", {}) as Dictionary
target_pick_required = maxi(1, int(count_d.get("n", 1)))
target_pick_up_to = bool(count_d.get("upto", false))
hide_pending_prompt_panel()
var panel: PanelContainer = PanelContainer.new()
panel.position = Vector2(8, 140)
var vbox: VBoxContainer = VBoxContainer.new()
vbox.add_theme_constant_override("separation", 6)
vbox.custom_minimum_size = Vector2(210, 0)
var title: Label = Label.new()
title.text = "Choose %s%d card(s):" % ["up to " if target_pick_up_to else "", target_pick_required]
title.add_theme_font_size_override("font_size", 13)
title.add_theme_color_override("font_color", Color(0.5, 0.9, 1.0))
vbox.add_child(title)
vbox.add_child(HSeparator.new())
for cand: Variant in candidates:
var card_d: Dictionary = cand as Dictionary
var iid: String = str(card_d.get("instanceId", ""))
var name_: String = str(card_d.get("name", iid))
var ctype: String = str(card_d.get("cardType", ""))
var btn: Button = Button.new()
btn.text = "%s%s" % [name_, "" if ctype.is_empty() else " (%s)" % ctype]
btn.add_theme_font_size_override("font_size", 11)
var cap_iid: String = iid
var cap_btn: Button = btn
btn.pressed.connect(func() -> void:
for sel_v: Variant in target_pick_selected:
if str((sel_v as Dictionary).get("instanceId", "")) == cap_iid:
return
target_pick_selected.append({ "actionIndex": 0, "instanceId": cap_iid })
cap_btn.modulate = Color(0.4, 1.0, 0.5)
if target_pick_selected.size() >= target_pick_required:
_finish_zone_target_pick())
vbox.add_child(btn)
if target_pick_up_to:
var done: Button = Button.new()
done.text = "Done Selecting"
done.add_theme_font_size_override("font_size", 12)
done.pressed.connect(_finish_zone_target_pick)
vbox.add_child(HSeparator.new())
vbox.add_child(done)
panel.add_child(vbox)
if hud != null:
hud.add_child(panel)
pending_prompt_panel = panel
func _finish_zone_target_pick() -> void:
hide_pending_prompt_panel()
var rid: String = pending_req_id
pending_req_id = ""
Game.send_target_pick_response(rid, target_pick_selected.duplicate())
target_pick_selected.clear()
# ── PendingTilePick ───────────────────────────────────────────────────────────
func on_tile_pick_request(req: Dictionary) -> void:
+89 -5
View File
@@ -33,11 +33,95 @@
> - **Builder** — UpTo checkbox added (parsed/compiled); dead triggers/effects delisted.
> - **Client** — cost-group / action-group prompt labels fixed (normalized keys + amounts).
>
> **Deferred** (see §7): validation-on-save endpoint (Phase 2.9), remaining H5 effects
> (SearchAndPlace→Battlefield, RevealCards N/ToOwnership, ChannelCardFromZone Filters/range flags,
> TakeControl duration reversal), H8 duration edge cases, H9 builder round-trip preservation,
> Phase 3 builder fields, Phase 4 client parity items (zone-scope card picking, prompt resilience,
> filter parity, OR-group UX), Phase 5 hygiene.
> **Also implemented (second pass):**
> - **Test suite** — new `Server/tests/SOR.Game.Tests` (added to SOR.slnx): 17 passing tests
> covering §8 tests 1–5 (passives-via-ActionGroup, ArchSpirit triggers, triggered pick at
> index 1, PreventDeath options, team-aware targeting, DOT tick gating, parse hardening,
> state-backed trigger limits/shields) plus 7 validator tests.
> - **Validation-on-save (Phase 2.9)** — new `SOR.Game.Abilities.AbilityValidator` (engine
> round-trip + structural lint: dead triggers, no-op effects, Repentance/Instinct shape,
> Range on effect cards, OR-group Passives, TokenDefJson incl. nested abilities); wired
> into `CardEditor.SaveAsync`, which blocks the save and lists the errors.
> - **SearchAndPlace Destination=Battlefield** — now places on a random affinity-valid empty
> tile (with enter-triggers/auras/passives), falling back to hand.
>
> **Also implemented (third pass):**
> - **H9 builder round-trip preservation** — every draft (ability/action/effect/condition/cost)
> stashes its original `JsonObject`; `Compile()` clones it and rewrites only UI-owned keys,
> guarded by `$type` so switching types drops stale fields. Preserved now: `SourceZoneGate`,
> `TriggerLimitPerGame`, `OnEnter/OnLeaveAuraActions`, `ChooseOne`, filter parameters +
> extra filters, cost `PickMode`/`Filters`, nested cost/action groups, trigger `Filter`
> params/`CardDefinitionId`/`AmountComparator`, unmodeled effect fields.
> - **ChannelCardFromZone.Filters** now enforced at all three resolution sites.
> - **Client prompt resilience (M11)** — a rejected pick response triggers `_fetch_state()`,
> which re-pushes the still-pending prompt (Game.gd `_PROMPT_RESPONSE_TYPES`).
>
> **Also implemented (fourth pass):**
> - **H8 duration edge cases** — `UntilStartOfSourceOwnerTurn` now anchors to the source
> unit's owner (`TrackedDuration.SourceOwnerAccountId`, old records fall back to the actor);
> `ReapplyAurasAtTurnStart` strips only aura-applied effects (`TrackedDuration.IsAura`,
> stamped via `AbilityContext.IsAuraApplication`) instead of every effect from that source.
> - **TakeControl duration reversal** — internal `__ReturnControl` effect tracked with the
> take-control duration; control (and the board occupant-owner) returns to the original
> owner on expiry. PermanentInMatch keeps control permanently.
> - **ChannelCardFromZone range flags** — `InOwnChannelRange` / `InTargetChannelRange`
> enforced via a shared `IsWithinChannelConstraints` helper at all three resolution sites,
> including validation of player-picked tiles (throws `OUT_OF_CHANNEL_RANGE`, client re-prompts).
> - **RevealCards N** — a player-targeted RevealCards now reveals the top N deck cards
> (ToOwnership still needs a per-player visibility model — deferred).
> - **Builder fields** — cost `PickMode` dropdown (pickable cost types only),
> `TriggerLimitPerGame` and `SourceZoneGate` inputs on Triggered abilities; all three
> added to the UI-owned key handling.
> - **Client filter parity (subset)** — `GenusContains`, `CardTypeIs`, `AffinityMatches`,
> `TierIs`, `HealthBelow/Above`, `DamageRange`, `DefenseRange`, `Ownership`,
> `IsSelf`/`IsExactSelf` unit filters and `TileIsOccupied`/`TileOccupancy` tile filters
> now enforced in targeting highlights/click validation.
> - Tests: 19 passing (added TakeControl reversal + source-owner expiry).
>
> **Also implemented (fifth pass):**
> - **H2 zone-scope card picking** — for Hand/Deck/Discard/AnyZone card targets on
> player-driven paths, the engine now pauses with a server-enumerated candidates list
> (`PendingTargetPick.CandidatesJson`, pushed in `TargetPickRequestPush`); the client's
> player/zone panel flow feeds into a new card-list picker (`_show_zone_target_panel`
> in server_prompt_handler.gd). AccountId placeholders are auto-substituted when
> there is no real choice.
> - **Prompt-instead-of-throw** — a mandatory explicit pick with no submitted targets on a
> player-driven path now emits `PendingTargetPick` (guarded by a non-empty-pool check)
> instead of `INSUFFICIENT_TARGETS`; all post-pick resume flows
> (cost/cost-group/action-group/branch/tile/player/reveal) now run with
> `requireClientTargets: true`, so "choose an enemy" actions after an OR-pick **prompt**
> rather than silently auto-hitting the first candidate.
> - **M13 OR-group UX** — the client no longer collects speculative targets for OR/XOR-root
> abilities (indices would misalign and be discarded); the server drives the flow.
> - **Hygiene** — `IsAllyTurn` now means "a teammate's turn" (was identical to IsOwnTurn);
> content-keyed `ParseAbilities` cache (bounded, safe: parsed defs are engine-immutable)
> removes the per-event JSON parse of every card in every zone.
> - Tests: 21 passing (added zone-pick pause/resume + prompt-instead-of-throw).
>
> **Also implemented (sixth pass, 2026-07-03):**
> - **Multi-filter editor** — the single param-less "Target Filter" dropdown is replaced by
> a full filter list per action (form view + canvas inspector): 28 filter types grouped
> Unit/Card vs Tile, each with its parameter fields (`FilterDraft`, `ParseFilter`,
> `CompileFilter`, `RenderFilterFields`). Nested-parameter filters
> (IsAdjacentToUnitMatching etc.) are selectable with their inner params preserved via
> the round-trip overlay.
> - **ChooseOne editor (advanced)** — per-action raw-JSON textarea (same pattern as
> AddAbility/ApplyOnEvent); parsed/compiled with fallback to the loaded value on
> invalid JSON. Branch abilities are now authorable.
> - **M14 allied pools** — new `Game.get_ally_units()`; highlight pools now mirror the
> server's team-aware semantics (Owner = own only, Ally = teammates only,
> Enemy = non-allies, Any = everyone).
>
> **Also implemented (seventh pass, 2026-07-04):**
> - PolyType duplicate attributes removed from sealed condition/filter classes (the
> converter only reads the base-type registry — verified inert before removal).
> - `IgnoreTurnConstraint` decided: documented as **reserved/no-effect** — ability-driven
> channels are never subject to the own-turn constraint (model doc comment updated).
>
> **Remaining backlog (feature work, not defects):** RevealCards `ToOwnership` — blocked on
> a per-player card-visibility model; structured (non-JSON) ChooseOne branch editor — the
> raw-JSON editor covers authoring today. Everything else from this review is resolved and
> covered by the 21-test regression suite in `Server/tests/SOR.Game.Tests`.
**Date:** 2026-07-02
**Scope reviewed:**
+3
View File
@@ -24,4 +24,7 @@
<Project Path="src/SOR.Support/SOR.Support.csproj" />
<Project Path="src/SOR.Versioning/SOR.Versioning.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/SOR.Game.Tests/SOR.Game.Tests.csproj" />
</Folder>
</Solution>
@@ -136,6 +136,15 @@
</select>
<input type="number" min="1" class="form-control form-control-sm" style="width:80px"
@bind="cost.Amount" @bind:after="Compile" placeholder="Amount" title="Amount" />
@if (PickableCostTypes.Contains(cost.TypeStr))
{
<select class="form-select form-select-sm" style="width:150px"
@bind="cost.PickModeStr" @bind:after="Compile"
title="Who picks which cards/units pay this cost">
@foreach (var pm in CostPickModeValues)
{ <option value="@pm">@(pm == "" ? "(auto)" : pm)</option> }
</select>
}
<button class="btn btn-sm btn-outline-danger py-0 px-1"
@onclick="() => { ab.Costs.RemoveAt(cidx); Compile(); }">
<i class="bi bi-x"></i>
@@ -234,6 +243,21 @@
@bind="ab.TriggerLimitPerTurn" @bind:after="Compile"
placeholder="blank = unlimited" />
</div>
<div class="col-md-3">
<label class="form-label small mb-0">Trigger Limit / Game</label>
<input type="number" min="1" class="form-control form-control-sm"
@bind="ab.TriggerLimitPerGame" @bind:after="Compile"
placeholder="blank = unlimited" />
</div>
<div class="col-md-4">
<label class="form-label small mb-0">
Source Zones
<small class="text-muted">(comma-separated; blank = battlefield only)</small>
</label>
<input class="form-control form-control-sm"
@bind="ab.SourceZoneGate" @bind:after="Compile"
placeholder="e.g. Hand, Battlefield" />
</div>
</div>
</div>
}
@@ -397,19 +421,50 @@
}
</div>
</div>
<!-- Target filter (optional, single filter, no-param types) -->
<div class="row g-2 mb-2 align-items-end">
<div class="col-md-4">
<label class="form-label small mb-0">Target Filter <span class="text-muted">(optional)</span></label>
<select class="form-select form-select-sm" @bind="action.FilterType" @bind:after="Compile">
<option value="">(none)</option>
<option value="IsSelf">IsSelf — same card definition</option>
<option value="IsExactSelf">IsExactSelf — same instance only</option>
<option value="IsAdjacentToSource">IsAdjacentToSource</option>
<option value="IsAdjacentToUnitMatching">IsAdjacentToUnitMatching</option>
<option value="IsAdjacentToTileMatching">IsAdjacentToTileMatching</option>
</select>
<!-- Target filters (all must match) -->
<div class="mb-2">
<div class="d-flex justify-content-between align-items-center mb-1">
<label class="form-label small mb-0">
Target Filters <span class="text-muted">(all must match)</span>
</label>
<button class="btn btn-sm btn-outline-secondary py-0 px-2"
@onclick="() => { action.Filters.Add(new FilterDraft()); Compile(); }">
<i class="bi bi-plus-lg me-1"></i>Add Filter
</button>
</div>
@for (int flI = 0; flI < action.Filters.Count; flI++)
{
var flIdx = flI;
var flt = action.Filters[flIdx];
<div class="d-flex gap-1 align-items-center mb-1 flex-wrap">
<select class="form-select form-select-sm" style="width:230px"
@bind="flt.TypeStr" @bind:after="Compile">
@foreach (var fgrp in FilterGroups)
{
<optgroup label="@fgrp.Label">
@foreach (var ft in fgrp.Types)
{ <option value="@ft">@ft</option> }
</optgroup>
}
</select>
@RenderFilterFields(flt)
<button class="btn btn-sm btn-outline-danger py-0 px-1"
@onclick="() => { action.Filters.RemoveAt(flIdx); Compile(); }">
<i class="bi bi-x"></i>
</button>
</div>
}
</div>
<!-- ChooseOne (advanced) -->
<div class="mb-2">
<label class="form-label small mb-0">
ChooseOne JSON
<small class="text-muted">(advanced — when set, Effects below are ignored and the chooser picks a branch)</small>
</label>
<textarea class="form-control form-control-sm font-monospace" rows="2"
@bind="action.ChooseOneJson" @bind:after="Compile"
placeholder='{"ChooserRole":"Self","Branches":[{"Label":"…","Actions":[…]}]}'></textarea>
</div>
<!-- Action-level duration override -->
@@ -1543,15 +1598,39 @@
<label class="form-label small mb-0">Count</label>
<input type="number" class="form-control form-control-sm mb-1" @bind="inAct.Count" @bind:after="Compile" min="1" />
}
<label class="form-label small mb-0">Target Filter</label>
<select class="form-select form-select-sm mb-2" @bind="inAct.FilterType" @bind:after="Compile">
<option value="">(none)</option>
<option value="IsSelf">IsSelf</option>
<option value="IsExactSelf">IsExactSelf</option>
<option value="IsAdjacentToSource">IsAdjacentToSource</option>
<option value="IsAdjacentToUnitMatching">IsAdjacentToUnitMatching</option>
<option value="IsAdjacentToTileMatching">IsAdjacentToTileMatching</option>
</select>
<div class="d-flex justify-content-between align-items-center mb-1">
<span class="small fw-medium">Target Filters</span>
<button class="btn btn-sm btn-outline-secondary py-0 px-1"
@onclick="() => { inAct.Filters.Add(new FilterDraft()); Compile(); }">
<i class="bi bi-plus-lg"></i>
</button>
</div>
@for (int inFlI = 0; inFlI < inAct.Filters.Count; inFlI++)
{
int inFlIdx = inFlI;
var inFlt = inAct.Filters[inFlIdx];
<div class="border rounded p-1 mb-1" style="overflow-x:auto">
<div class="d-flex gap-1 align-items-center mb-1">
<select class="form-select form-select-sm flex-grow-1"
@bind="inFlt.TypeStr" @bind:after="Compile">
@foreach (var fgrp in FilterGroups)
{
<optgroup label="@fgrp.Label">
@foreach (var ft in fgrp.Types)
{ <option value="@ft">@ft</option> }
</optgroup>
}
</select>
<button class="btn btn-sm btn-outline-danger py-0 px-1 flex-shrink-0"
@onclick="() => { inAct.Filters.RemoveAt(inFlIdx); Compile(); }">
<i class="bi bi-x"></i>
</button>
</div>
<div class="d-flex gap-1 flex-wrap align-items-center">
@RenderFilterFields(inFlt)
</div>
</div>
}
@* Action conditions *@
<div class="d-flex justify-content-between align-items-center mb-1">
@@ -2209,6 +2288,15 @@
"DealDamageToOwnArchSpirit", "DealDamageToOwnSpirit",
];
/// <summary>Cost types the engine supports interactive PickMode for.</summary>
private static readonly string[] PickableCostTypes = [
"DiscardFromHand", "SendSpiritFromBattlefieldToDiscard", "DealDamageToOwnSpirit",
];
private static readonly string[] CostPickModeValues = [
"", "Random", "SelfPick", "EnemySeePick", "EnemyRandomPick", "EnemyPick",
];
// Only triggers the engine actually fires AND matches are listed here.
// NOT yet implemented server-side (do not re-add without engine support —
// see SOR.Abilities-Review-and-solutions.md §C3):
@@ -2284,6 +2372,27 @@
new("Composite", ["AND", "OR", "XOR", "NOT"]),
];
// ── Filter groups (target-pool filters) ──────────────────────────────────────
private static readonly EffectGroup[] FilterGroups =
[
new("Unit / Card", ["GenusContains", "AffinityMatches", "HealthBelow", "HealthAbove",
"DamageRange", "DefenseRange", "MPRange", "HasFlag", "TierIs",
"IsAdjacentToSource", "CardTypeIs", "CardSPCostRange", "CardSTCostRange",
"WithinRange", "IsSelf", "IsExactSelf",
"IsAdjacentToUnitMatching", "IsAdjacentToTileMatching",
"Ownership", "UnitProperty"]),
new("Tile", ["TileAffinityMatches", "TileIsOccupied", "TileIsUnoccupied",
"TileWithinRange", "TileIsAdjacentToUnit", "TileIsOnPlayerSide",
"TileIsInArchSpiritChannelRange", "TileOccupancy"]),
];
/// <summary>Flags the engine's HasFlagFilter actually evaluates.</summary>
private static readonly string[] FilterFlagValues = ["CanMove", "CanAttack", "IsLeader", "IsExhausted"];
private static readonly string[] CardTypeIsValues =
["Spirit", "ArchSpirit", "SpiritToken", "Repentance", "Instinct", "Terramorpha", "Ruin"];
// ── Effect type categories for rendering ─────────────────────────────────────
private static readonly HashSet<string> _amountBypassTypes = ["DealDamage", "DealDamageToSelf"];
@@ -2373,11 +2482,16 @@
{
var ab = new AbilityDraft
{
Original = node,
TypeStr = node["Type"]?.GetValue<string>() ?? "Active",
Name = node["Name"]?.GetValue<string>() ?? "",
Description = node["Description"]?.GetValue<string>() ?? "",
UsesPerTurn = node["UsesPerTurn"]?.GetValue<int>() ?? 1,
TriggerLimitPerTurn = node["TriggerLimitPerTurn"]?.GetValue<int?>(),
TriggerLimitPerGame = node["TriggerLimitPerGame"]?.GetValue<int?>(),
SourceZoneGate = node["SourceZoneGate"] is JsonArray szg
? string.Join(", ", szg.Select(z => z?.GetValue<string>() ?? "").Where(z => !string.IsNullOrEmpty(z)))
: "",
RangeMin = node["Range"]?["Min"]?.GetValue<int>(),
RangeMax = node["Range"]?["Max"]?.GetValue<int>(),
RangeRequiresLos = node["Range"]?["RequiresLos"]?.GetValue<bool>() ?? false,
@@ -2419,16 +2533,20 @@
foreach (var c in cgEntries.OfType<JsonObject>())
ab.Costs.Add(new CostDraft
{
Original = c,
TypeStr = c["Type"]?.GetValue<string>() ?? "SpiritPoints",
Amount = c["Amount"]?.GetValue<int>() ?? 1,
PickModeStr = c["PickMode"]?.GetValue<string>() ?? "",
});
}
else if (node["Cost"] is JsonArray costs)
foreach (var c in costs.OfType<JsonObject>())
ab.Costs.Add(new CostDraft
{
Original = c,
TypeStr = c["Type"]?.GetValue<string>() ?? "SpiritPoints",
Amount = c["Amount"]?.GetValue<int>() ?? 1,
PickModeStr = c["PickMode"]?.GetValue<string>() ?? "",
});
if (node["ActivationConditions"] is JsonArray aconds)
@@ -2461,6 +2579,7 @@
{
LogicOp = sgNode["LogicOp"]?.GetValue<string>() ?? "And",
ChooserRole = sgNode["ChooserRole"]?.GetValue<string>() ?? "Self",
OriginalNestedGroups = sgNode["Groups"] as JsonArray,
};
if (sgNode["Actions"] is JsonArray sgActions)
foreach (var sgActionNode in sgActions.OfType<JsonObject>())
@@ -2498,6 +2617,7 @@
private static ConditionDraft ParseCondition(JsonObject c) => new()
{
Original = c,
TypeStr = c["$type"]?.GetValue<string>() ?? "IsOwnTurn",
Subject = c["Subject"]?.GetValue<string>() ?? "Self",
N = c["N"]?.GetValue<int>() ?? 1,
@@ -2524,7 +2644,7 @@
private static EffectDraft ParseEffect(JsonObject eff)
{
var typeKey = eff["$type"]?.GetValue<string>() ?? "DealDamage";
var d = new EffectDraft { TypeKey = typeKey };
var d = new EffectDraft { TypeKey = typeKey, Original = eff };
// ValueExpr helpers — eff[key] may be a raw JsonValue (legacy) or a JsonObject
// with a "Fixed" int field or a "Ref" string field. Calling GetValue<int>() on a
@@ -2734,10 +2854,10 @@
private static ActionDraft ParseActionNode(JsonObject actionNode)
{
var target = actionNode["Target"] as JsonObject;
var firstFilter = (target?["Filters"] as JsonArray)?.OfType<JsonObject>().FirstOrDefault();
var target = actionNode["Target"] as JsonObject;
var act = new ActionDraft
{
Original = actionNode,
Scope = target?["Scope"]?.GetValue<string>() ?? "Battlefield",
TargetType = target?["Type"]?.GetValue<string>() ?? "Unit",
Ownership = target?["Ownership"]?.GetValue<string>() ?? "Enemy",
@@ -2745,8 +2865,12 @@
Count = target?["Count"]?["N"]?.GetValue<int>() ?? 1,
All = target?["Count"]?["All"]?.GetValue<bool>() ?? false,
UpTo = target?["Count"]?["UpTo"]?.GetValue<bool>() ?? false,
FilterType = firstFilter?["$type"]?.GetValue<string>() ?? "",
};
if (target?["Filters"] is JsonArray filtersArr)
foreach (var f in filtersArr.OfType<JsonObject>())
act.Filters.Add(ParseFilter(f));
if (actionNode["ChooseOne"] is JsonObject chooseOne)
act.ChooseOneJson = chooseOne.ToJsonString();
if (actionNode["Duration"] is JsonObject actionDur)
{
act.DurationStr = actionDur["Type"]?.GetValue<string>() ?? "";
@@ -2763,6 +2887,20 @@
// ── Compile ──────────────────────────────────────────────────────────────────
/// <summary>
/// Top-level AbilityDefinition keys the UI owns and rewrites on every compile.
/// Anything NOT in this list (SourceZoneGate, TriggerLimitPerGame,
/// OnEnterAuraActions, OnLeaveAuraActions, future fields…) is preserved from the
/// loaded JSON so an open → save round-trip never strips it.
/// </summary>
private static readonly string[] _abilityOwnedKeys =
[
"Type", "Name", "Description", "Range", "UsesPerTurn",
"CostGroup", "Cost", "AuraRange", "ClearOnLeave", "LingerDuration",
"TriggerEvent", "TriggerLimitPerTurn", "TriggerLimitPerGame", "SourceZoneGate",
"ActivationConditions", "ActionGroup", "Actions", "Duration", "Animation",
];
private void Compile()
{
try
@@ -2771,12 +2909,16 @@
foreach (var ab in _abilities)
{
var node = new JsonObject
{
["Type"] = ab.TypeStr,
["Name"] = ab.Name,
["Description"] = ab.Description,
};
// Start from the loaded node (preserve-unknown), then rewrite UI-owned keys.
var node = ab.Original is not null
? (JsonObject)ab.Original.DeepClone()
: new JsonObject();
foreach (var owned in _abilityOwnedKeys)
node.Remove(owned);
node["Type"] = ab.TypeStr;
node["Name"] = ab.Name;
node["Description"] = ab.Description;
if (ab.TypeStr == "Active")
{
@@ -2800,8 +2942,24 @@
costGroup["ChooserRole"] = ab.CostGroupChooserRole;
var entriesArr = new JsonArray();
foreach (var cost in ab.Costs)
entriesArr.Add(new JsonObject { ["Type"] = cost.TypeStr, ["Amount"] = cost.Amount });
{
// Preserve unmodeled entry fields (Filters) when Type unchanged.
var entryNode = cost.Original is not null
&& string.Equals(cost.Original["Type"]?.GetValue<string>(), cost.TypeStr, StringComparison.Ordinal)
? (JsonObject)cost.Original.DeepClone()
: new JsonObject();
entryNode["Type"] = cost.TypeStr;
entryNode["Amount"] = cost.Amount;
if (!string.IsNullOrEmpty(cost.PickModeStr))
entryNode["PickMode"] = cost.PickModeStr;
else
entryNode.Remove("PickMode");
entriesArr.Add(entryNode);
}
costGroup["Entries"] = entriesArr;
// Nested cost groups are not modeled by the UI — carry them through.
if (ab.Original?["CostGroup"]?["Groups"] is JsonArray origCostGroups && origCostGroups.Count > 0)
costGroup["Groups"] = origCostGroups.DeepClone();
node["CostGroup"] = costGroup;
}
}
@@ -2824,9 +2982,20 @@
}
else if (ab.TypeStr == "Triggered" && !string.IsNullOrEmpty(ab.TriggerType))
{
node["TriggerEvent"] = CompileTrigger(ab);
node["TriggerEvent"] = CompileTrigger(ab,
ab.Original?["TriggerEvent"] as JsonObject);
if (ab.TriggerLimitPerTurn is > 0)
node["TriggerLimitPerTurn"] = ab.TriggerLimitPerTurn.Value;
if (ab.TriggerLimitPerGame is > 0)
node["TriggerLimitPerGame"] = ab.TriggerLimitPerGame.Value;
var zones = ab.SourceZoneGate
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (zones.Length > 0)
{
var zoneArr = new JsonArray();
foreach (var z in zones) zoneArr.Add(z);
node["SourceZoneGate"] = zoneArr;
}
}
if (ab.Conditions.Count > 0)
@@ -2857,7 +3026,10 @@
if (sg.LogicOp != "And" || sg.ChooserRole != "Self")
subGroup["ChooserRole"] = sg.ChooserRole;
subGroup["Actions"] = sgActionsArr;
subGroup["Groups"] = new JsonArray();
// Preserve deeper nesting the UI does not model.
subGroup["Groups"] = sg.OriginalNestedGroups is not null
? (JsonArray)sg.OriginalNestedGroups.DeepClone()
: new JsonArray();
groupsArr.Add(subGroup);
}
actionGroup["Groups"] = groupsArr;
@@ -2901,6 +3073,32 @@
private static JsonObject CompileActionNode(ActionDraft action)
{
// Preserve-unknown: unmodeled action keys (ChooseOne, …) carry through from
// the loaded node; UI-owned keys are removed and rewritten below.
var actionNode = action.Original is not null
? (JsonObject)action.Original.DeepClone()
: new JsonObject();
actionNode.Remove("Target");
actionNode.Remove("Conditions");
actionNode.Remove("Effects");
actionNode.Remove("Duration");
actionNode.Remove("ChooseOne");
// ChooseOne (advanced, raw JSON). Invalid JSON falls back to the loaded value.
if (!string.IsNullOrWhiteSpace(action.ChooseOneJson))
{
try
{
if (JsonNode.Parse(action.ChooseOneJson) is JsonObject co)
actionNode["ChooseOne"] = co;
}
catch
{
if (action.Original?["ChooseOne"] is JsonObject origCo)
actionNode["ChooseOne"] = (JsonObject)origCo.DeepClone();
}
}
var targetNode = new JsonObject
{
["Scope"] = action.Scope,
@@ -2914,10 +3112,14 @@
["All"] = action.All,
},
};
if (!string.IsNullOrEmpty(action.FilterType))
targetNode["Filters"] = new JsonArray(
new JsonObject { ["$type"] = action.FilterType });
var actionNode = new JsonObject { ["Target"] = targetNode };
if (action.Filters.Count > 0)
{
var filtersArr = new JsonArray();
foreach (var flt in action.Filters)
filtersArr.Add(CompileFilter(flt));
targetNode["Filters"] = filtersArr;
}
actionNode["Target"] = targetNode;
if (action.Conditions.Count > 0)
{
var ca = new JsonArray();
@@ -2937,10 +3139,84 @@
return actionNode;
}
private static FilterDraft ParseFilter(JsonObject f) => new()
{
Original = f,
TypeStr = f["$type"]?.GetValue<string>() ?? "GenusContains",
Tag = f["Tag"]?.GetValue<string>() ?? "",
Affinity = f["Affinity"]?.GetValue<string>() ?? "Aether",
N = f["N"]?.GetValue<int>() ?? 1,
Min = f["Min"]?.GetValue<int>() ?? 1,
Max = f["Max"]?.GetValue<int>() ?? 2,
Flag = f["Flag"]?.GetValue<string>() ?? "CanAttack",
Tier = f["Tier"]?.GetValue<int>() ?? 1,
CardType = f["CardType"]?.GetValue<string>() ?? "Spirit",
UnitType = f["UnitType"]?.GetValue<string>() ?? "Unit",
Ownership = f["Ownership"]?.GetValue<string>() ?? "Any",
PropertyName = f["PropertyName"]?.GetValue<string>() ?? "Damage",
Comparator = f["Comparator"]?.GetValue<string>() ?? "GreaterThanOrEqual",
Value = f["Value"]?.GetValue<int>() ?? 1,
};
private static JsonObject CompileFilter(FilterDraft f)
{
// Preserve nested/unmodeled parameters when the filter type is unchanged.
var node = f.Original is not null
&& string.Equals(f.Original["$type"]?.GetValue<string>(), f.TypeStr, StringComparison.Ordinal)
? (JsonObject)f.Original.DeepClone()
: new JsonObject();
node["$type"] = f.TypeStr;
switch (f.TypeStr)
{
case "GenusContains":
node["Tag"] = f.Tag; break;
case "AffinityMatches": case "TileAffinityMatches":
node["Affinity"] = f.Affinity; break;
case "HealthBelow": case "HealthAbove":
node["N"] = f.N; break;
case "DamageRange": case "DefenseRange": case "MPRange":
case "CardSPCostRange": case "CardSTCostRange":
case "WithinRange": case "TileWithinRange":
node["Min"] = f.Min; node["Max"] = f.Max; break;
case "HasFlag":
node["Flag"] = f.Flag; break;
case "TierIs":
node["Tier"] = f.Tier; break;
case "CardTypeIs":
node["CardType"] = f.CardType; break;
case "TileIsOccupied":
if (!string.IsNullOrEmpty(f.UnitType) && f.UnitType != "Unit") node["UnitType"] = f.UnitType;
else node.Remove("UnitType");
break;
case "Ownership": case "TileIsOnPlayerSide": case "TileIsInArchSpiritChannelRange":
node["Ownership"] = f.Ownership; break;
case "UnitProperty":
node["PropertyName"] = f.PropertyName;
node["Comparator"] = f.Comparator;
node["Value"] = f.Value;
break;
case "TileOccupancy":
node["UnitType"] = f.UnitType;
node["Ownership"] = f.Ownership;
break;
// IsSelf / IsExactSelf / IsAdjacentToSource / TileIsUnoccupied — no parameters.
// IsAdjacentToUnitMatching / IsAdjacentToTileMatching / TileIsAdjacentToUnit —
// nested UnitFilters/TileFilters preserved via the overlay; no UI-owned fields.
}
return node;
}
private static JsonObject CompileCondition(ConditionDraft c)
{
var node = new JsonObject { ["$type"] = c.TypeStr };
// Preserve unmodeled parameters when the condition type is unchanged.
var node = c.Original is not null
&& string.Equals(c.Original["$type"]?.GetValue<string>(), c.TypeStr, StringComparison.Ordinal)
? (JsonObject)c.Original.DeepClone()
: new JsonObject();
node["$type"] = c.TypeStr;
if (c.Subject != "Self") node["Subject"] = c.Subject;
else node.Remove("Subject");
switch (c.TypeStr)
{
@@ -2968,7 +3244,9 @@
case "MovementTypeIs":
node["MovementType"] = c.MovementType; break;
case "TileIsOccupied":
if (!string.IsNullOrEmpty(c.UnitType)) node["UnitType"] = c.UnitType; break;
if (!string.IsNullOrEmpty(c.UnitType)) node["UnitType"] = c.UnitType;
else node.Remove("UnitType");
break;
case "IsActivePlayerTurn":
node["Ownership"] = c.Ownership; break;
case "UnitCountOnBattlefield":
@@ -3013,7 +3291,9 @@
break;
case "HandContainsCount":
if (!string.IsNullOrEmpty(c.Tag)) node["CardType"] = c.Tag;
else node.Remove("CardType");
if (c.Affinity != "Aether") node["Affinity"] = c.Affinity;
else node.Remove("Affinity");
node["Comparator"] = c.Comparator;
node["N"] = c.N;
break;
@@ -3036,17 +3316,25 @@
case "CostOfCardsInHand":
node["CostType"] = c.CostType;
if (!string.IsNullOrEmpty(c.Tag)) node["CardType"] = c.Tag;
else node.Remove("CardType");
if (c.Affinity != "Aether") node["Affinity"] = c.Affinity;
else node.Remove("Affinity");
node["Comparator"] = c.Comparator; node["Value"] = c.Value;
break;
}
return node;
}
private static JsonObject CompileTrigger(AbilityDraft ab)
private static JsonObject CompileTrigger(AbilityDraft ab, JsonObject? original = null)
{
var t = ab.TriggerType;
var n = new JsonObject { ["$type"] = t };
// Preserve unmodeled trigger fields (Filter parameters, CardDefinitionId,
// AmountComparator, OccupantFilters, …) when the trigger type is unchanged.
var n = original is not null
&& string.Equals(original["$type"]?.GetValue<string>(), t, StringComparison.Ordinal)
? (JsonObject)original.DeepClone()
: new JsonObject();
n["$type"] = t;
// Player-only
if (t is "OnTurnStart" or "OnTurnEnd" or "OnCardDrawn"
@@ -3060,12 +3348,14 @@
{
n["Player"] = ab.TriggerPlayer;
if (ab.TriggerAmount.HasValue) n["Amount"] = ab.TriggerAmount.Value;
else n.Remove("Amount");
}
// Player + optional Cause
else if (t == "OnCardDiscarded")
{
n["Player"] = ab.TriggerPlayer;
if (!string.IsNullOrEmpty(ab.TriggerCause)) n["Cause"] = ab.TriggerCause;
else n.Remove("Cause");
}
// Ownership-only
else if (t is "OnAscend" or "OnTransition" or "OnUnitMove" or "OnUnitAttack"
@@ -3079,12 +3369,14 @@
{
n["Ownership"] = ab.TriggerOwnership;
if (ab.TriggerAmount.HasValue) n["Amount"] = ab.TriggerAmount.Value;
else n.Remove("Amount");
}
// Ownership + optional Stat
else if (t == "OnStatModified")
{
n["Ownership"] = ab.TriggerOwnership;
if (!string.IsNullOrEmpty(ab.TriggerStat)) n["Stat"] = ab.TriggerStat;
else n.Remove("Stat");
}
// Ownership + CardType
else if (t == "OnChanneled")
@@ -3104,6 +3396,7 @@
n["Ownership"] = ab.TriggerOwnership;
n["UnitType"] = ab.TriggerUnitType;
if (!string.IsNullOrEmpty(ab.TriggerCausedBy)) n["CausedBy"] = ab.TriggerCausedBy;
else n.Remove("CausedBy");
}
// SourceOwnership + TargetOwnership + optional DamageType + optional Amount
else if (t == "OnDamageDealt")
@@ -3111,9 +3404,20 @@
n["SourceOwnership"] = ab.TriggerSourceOwnership;
n["TargetOwnership"] = ab.TriggerTargetOwnership;
if (ab.TriggerDamageType != "Any") n["DamageType"] = ab.TriggerDamageType;
else n.Remove("DamageType");
if (ab.TriggerAmount.HasValue) n["Amount"] = ab.TriggerAmount.Value;
else n.Remove("Amount");
if (!string.IsNullOrWhiteSpace(ab.TriggerSourceFilterType))
n["SourceFilter"] = new JsonObject { ["$type"] = ab.TriggerSourceFilterType };
{
// Keep the original SourceFilter (with its parameters) when its type is unchanged.
var origSf = n["SourceFilter"] as JsonObject;
if (origSf?["$type"]?.GetValue<string>() != ab.TriggerSourceFilterType)
n["SourceFilter"] = new JsonObject { ["$type"] = ab.TriggerSourceFilterType };
}
else
{
n.Remove("SourceFilter");
}
}
else if (t == "BeforeDamageApplied")
{
@@ -3130,6 +3434,7 @@
{
n["TargetOwnership"] = ab.TriggerTargetOwnership;
if (ab.TriggerAmount.HasValue) n["Amount"] = ab.TriggerAmount.Value;
else n.Remove("Amount");
}
// TargetOwnership + SourceOwnership
else if (t is "OnTargetedByAbility" or "OnEffectApplied")
@@ -3143,6 +3448,8 @@
n["RuinOwnership"] = ab.TriggerRuinOwnership;
if (!string.IsNullOrEmpty(ab.TriggerOccupantOwnership))
n["OccupantOwnership"] = ab.TriggerOccupantOwnership;
else
n.Remove("OccupantOwnership");
}
// UnitOwnership only
else if (t == "OnUnitOccupyRuin")
@@ -3162,7 +3469,13 @@
private static JsonObject CompileEffect(EffectDraft d)
{
var node = new JsonObject { ["$type"] = d.TypeKey };
// Preserve unmodeled effect fields (ToOwnership, TileFilter params, ThenGroup, …)
// when the effect type is unchanged; switching types starts from a clean node.
var node = d.Original is not null
&& string.Equals(d.Original["$type"]?.GetValue<string>(), d.TypeKey, StringComparison.Ordinal)
? (JsonObject)d.Original.DeepClone()
: new JsonObject();
node["$type"] = d.TypeKey;
JsonObject ValueExpr() => string.IsNullOrEmpty(d.AmountRef)
? new JsonObject { ["Fixed"] = d.Amount }
@@ -3212,6 +3525,7 @@
{
node["Tiles"] = d.Tiles;
if (d.BlockedDamage > 0) node["BlockedDamage"] = d.BlockedDamage;
else node.Remove("BlockedDamage");
}
else if (d.TypeKey == "DisplaceUnit")
{
@@ -3221,9 +3535,13 @@
{
node["Tiles"] = d.Tiles;
if (d.AdjacentToSource) node["AdjacentToSource"] = true;
else node.Remove("AdjacentToSource");
if (!string.IsNullOrWhiteSpace(d.RelativeToTargetRef)) node["RelativeToTargetRef"] = d.RelativeToTargetRef;
else node.Remove("RelativeToTargetRef");
if (d.AdjacentToRelativeTarget) node["AdjacentToRelativeTarget"] = true;
else node.Remove("AdjacentToRelativeTarget");
if (d.AllowRelativeTargetTile) node["AllowRelativeTargetTile"] = true;
else node.Remove("AllowRelativeTargetTile");
}
else if (d.TypeKey == "SetAttackRange")
{
@@ -3268,7 +3586,9 @@
else if (d.TypeKey == "ModifyCost")
{
if (d.Sp.HasValue) node["Sp"] = d.Sp.Value;
else node.Remove("Sp");
if (d.St.HasValue) node["St"] = d.St.Value;
else node.Remove("St");
}
else if (d.TypeKey == "SetStatModMultiplier")
{
@@ -3325,11 +3645,16 @@
node["TileFilter"] = new JsonArray(
new JsonObject { ["$type"] = "TileAffinityMatches", ["Affinity"] = d.TokenAffinity });
}
else
{
node.Remove("TileFilter");
}
}
else if (d.TypeKey is "AscendFromZone" or "TransitionFromZone")
{
node["Zone"] = d.Zone;
if (d.IgnoreCost) node["IgnoreCost"] = true;
else node.Remove("IgnoreCost");
}
else if (d.TypeKey == "ModifyChannelRange")
{
@@ -3359,6 +3684,10 @@
}
else if (_rawJsonTypes.Contains(d.TypeKey))
{
// Raw-JSON effects: the textarea IS the whole definition — replace every
// field so deletions made in the raw editor actually take effect.
foreach (var staleKey in node.Select(kv => kv.Key).Where(k => k != "$type").ToList())
node.Remove(staleKey);
if (!string.IsNullOrWhiteSpace(d.RawJson))
{
try
@@ -3378,6 +3707,44 @@
// ── Per-type field renderers (RenderFragment) ─────────────────────────────────
private RenderFragment RenderFilterFields(FilterDraft f) => __builder =>
{
switch (f.TypeStr)
{
case "GenusContains":
BuildTextInput(__builder, f.Tag, v => { f.Tag = v; Compile(); }, 120, "Tag"); break;
case "AffinityMatches": case "TileAffinityMatches":
BuildSelect(__builder, AffinityValues, f.Affinity, v => { f.Affinity = v; Compile(); }, 120); break;
case "HealthBelow": case "HealthAbove":
BuildIntInput(__builder, f.N, v => { f.N = v; Compile(); }, 70, "N"); break;
case "DamageRange": case "DefenseRange": case "MPRange":
case "CardSPCostRange": case "CardSTCostRange":
case "WithinRange": case "TileWithinRange":
BuildIntInput(__builder, f.Min, v => { f.Min = v; Compile(); }, 60, "Min");
BuildIntInput(__builder, f.Max, v => { f.Max = v; Compile(); }, 60, "Max");
break;
case "HasFlag":
BuildSelect(__builder, FilterFlagValues, f.Flag, v => { f.Flag = v; Compile(); }, 120); break;
case "TierIs":
BuildIntInput(__builder, f.Tier, v => { f.Tier = v; Compile(); }, 60, "Tier"); break;
case "CardTypeIs":
BuildSelect(__builder, CardTypeIsValues, f.CardType, v => { f.CardType = v; Compile(); }, 130); break;
case "TileIsOccupied":
BuildSelect(__builder, UnitTypeValues, f.UnitType, v => { f.UnitType = v; Compile(); }, 110); break;
case "Ownership": case "TileIsOnPlayerSide": case "TileIsInArchSpiritChannelRange":
BuildSelect(__builder, OwnershipValues, f.Ownership, v => { f.Ownership = v; Compile(); }, 100); break;
case "UnitProperty":
BuildSelect(__builder, UnitPropertyNames, f.PropertyName, v => { f.PropertyName = v; Compile(); }, 150);
BuildSelect(__builder, ComparatorValues, f.Comparator, v => { f.Comparator = v; Compile(); }, 150);
BuildIntInput(__builder, f.Value, v => { f.Value = v; Compile(); }, 60, "Value");
break;
case "TileOccupancy":
BuildSelect(__builder, UnitTypeValues, f.UnitType, v => { f.UnitType = v; Compile(); }, 110);
BuildSelect(__builder, OwnershipValues, f.Ownership, v => { f.Ownership = v; Compile(); }, 100);
break;
}
};
private RenderFragment RenderConditionFields(ConditionDraft c) => __builder =>
{
var t = c.TypeStr;
@@ -3970,6 +4337,19 @@
b.CloseElement();
}
private void BuildTextInput(RenderTreeBuilder b, string value, Action<string> onChange, int widthPx, string placeholder)
{
b.OpenElement(0, "input");
b.AddAttribute(1, "class", "form-control form-control-sm");
b.AddAttribute(2, "style", $"width:{widthPx}px");
b.AddAttribute(3, "placeholder", placeholder);
b.AddAttribute(4, "title", placeholder);
b.AddAttribute(5, "value", value);
b.AddAttribute(6, "onchange", EventCallback.Factory.Create<ChangeEventArgs>(
this, e => onChange(e.Value?.ToString() ?? "")));
b.CloseElement();
}
private void BuildIntInput(RenderTreeBuilder b, int value, Action<int> onChange, int widthPx, string placeholder)
{
b.OpenElement(0, "input");
@@ -4510,6 +4890,14 @@
private sealed class AbilityDraft
{
/// <summary>
/// The ability's original JSON node as loaded (null for newly added abilities).
/// Compile() starts from a clone of this so properties the UI does not model
/// (SourceZoneGate, TriggerLimitPerGame, OnEnter/OnLeaveAuraActions, …) survive
/// an open → save round-trip instead of being silently stripped.
/// </summary>
public JsonObject? Original { get; set; }
public string TypeStr { get; set; } = "Active";
public string Name { get; set; } = "";
public string Description { get; set; } = "";
@@ -4547,6 +4935,9 @@
public string TriggerUnitOwnership { get; set; } = "Any";
public string TriggerAuraOwnership { get; set; } = "Owner";
public int? TriggerLimitPerTurn { get; set; }
public int? TriggerLimitPerGame { get; set; }
/// <summary>Comma-separated zone list ("Hand, Battlefield"); "" = battlefield-only default.</summary>
public string SourceZoneGate { get; set; } = "";
// Ability-level duration (overrides per-action Duration when set; "" = per-action)
public string DurationStr { get; set; } = "";
public int DurationN { get; set; } = 1;
@@ -4573,10 +4964,15 @@
public string LogicOp { get; set; } = "And";
public string ChooserRole { get; set; } = "Self";
public List<ActionDraft> Actions { get; set; } = new();
/// <summary>Nested Groups[] of this sub-group as loaded — preserved verbatim (UI edits one level only).</summary>
public JsonArray? OriginalNestedGroups { get; set; }
}
private sealed class ActionDraft
{
/// <summary>Original action JSON node (null for new actions). Preserves ChooseOne, filter parameters, etc.</summary>
public JsonObject? Original { get; set; }
public string Scope { get; set; } = "Battlefield";
public string TargetType { get; set; } = "Unit";
public string Ownership { get; set; } = "Enemy";
@@ -4586,11 +4982,15 @@
public bool All { get; set; }
/// <summary>Player may select fewer than Count valid targets.</summary>
public bool UpTo { get; set; }
/// <summary>Target-pool filters (all must match). Maps to Target.Filters in the compiled JSON.</summary>
public List<FilterDraft> Filters { get; set; } = new();
/// <summary>
/// Optional filter type applied to the target pool (single filter, no-param variant).
/// "" = no filter. Maps to Target.Filters[0] in the compiled JSON.
/// Raw ChooseOne JSON ({"Branches":[…],"ChooserRole":"Self"}); "" = none.
/// When set, the engine ignores this action's Effects and the chooser picks a branch.
/// Advanced editor — edited as raw JSON like AddAbility/ApplyOnEvent effects.
/// </summary>
public string FilterType { get; set; } = "";
public string ChooseOneJson { get; set; } = "";
/// <summary>
/// Action-level duration override. "" = no override (each effect uses its own duration or the ability-level duration).
/// Written to "Duration": {"Type": ...} in the compiled action JSON.
@@ -4603,6 +5003,9 @@
private sealed class EffectDraft
{
/// <summary>Original effect JSON node (null for new effects). Used when $type still matches TypeKey.</summary>
public JsonObject? Original { get; set; }
public string TypeKey { get; set; } = "DealDamage";
public int Amount { get; set; } = 1;
public string AmountRef { get; set; } = ""; // "" = use Fixed; non-empty = ValueExpr Ref path
@@ -4676,6 +5079,9 @@
private sealed class ConditionDraft
{
/// <summary>Original condition JSON node (null for new conditions). Used when $type still matches TypeStr.</summary>
public JsonObject? Original { get; set; }
public string TypeStr { get; set; } = "IsOwnTurn";
public string Subject { get; set; } = "Self";
public int N { get; set; } = 1;
@@ -4701,9 +5107,37 @@
public string CostType { get; set; } = "SP";
}
private sealed class FilterDraft
{
/// <summary>Original filter JSON node (null for new filters). Used when $type still matches TypeStr —
/// preserves nested parameters (UnitFilters, TileFilters) the UI does not model.</summary>
public JsonObject? Original { get; set; }
public string TypeStr { get; set; } = "GenusContains";
public string Tag { get; set; } = "";
public string Affinity { get; set; } = "Aether";
public int N { get; set; } = 1;
public int Min { get; set; } = 1;
public int Max { get; set; } = 2;
public string Flag { get; set; } = "CanAttack";
public int Tier { get; set; } = 1;
public string CardType { get; set; } = "Spirit";
public string UnitType { get; set; } = "Unit";
public string Ownership { get; set; } = "Any";
public string PropertyName { get; set; } = "Damage";
public string Comparator { get; set; } = "GreaterThanOrEqual";
public int Value { get; set; } = 1;
}
private sealed class CostDraft
{
/// <summary>Original cost-entry JSON node (null for new costs). Preserves Filters when Type unchanged.</summary>
public JsonObject? Original { get; set; }
public string TypeStr { get; set; } = "SpiritPoints";
public int Amount { get; set; } = 1;
/// <summary>Interactive pick mode; "" = server auto-resolves. Only honoured by the engine for
/// DiscardFromHand / SendSpiritFromBattlefieldToDiscard / DealDamageToOwnSpirit.</summary>
public string PickModeStr { get; set; } = "";
}
}
@@ -43,6 +43,18 @@ else
{
<div class="alert alert-danger">@_saveError</div>
}
@if (_abilityErrors.Count > 0)
{
<div class="alert alert-danger">
<strong>Abilities failed validation — not saved:</strong>
<ul class="mb-0 mt-1">
@foreach (var err in _abilityErrors)
{
<li class="small">@err</li>
}
</ul>
</div>
}
@if (_saveSuccess)
{
<div class="alert alert-success">Saved successfully.</div>
@@ -782,6 +794,7 @@ else
private bool _saving;
private string? _saveError;
private bool _saveSuccess;
private IReadOnlyList<string> _abilityErrors = [];
private List<string> _selectedGenus = new();
private List<string> _availableGenus = new();
private string _newGenusTag = string.Empty;
@@ -1036,6 +1049,16 @@ else
_saveError = null;
_saveSuccess = false;
// Validate abilities with the game engine's own deserializer + structural lint
// so unplayable content never reaches the catalog.
_abilityErrors = SOR.Game.Abilities.AbilityValidator.Validate(
_abilitiesJson, _card.CardType.ToString());
if (_abilityErrors.Count > 0)
{
_saving = false;
return;
}
try
{
_card.Genus = _selectedGenus.Count > 0 ? _selectedGenus.ToArray() : null;
@@ -40,6 +40,13 @@ public sealed class AbilityContext
/// </summary>
public AbilityRange? ActivationRange { get; set; }
/// <summary>
/// True while an Aura ability is applying its effects. Stamped into the tracked
/// duration so ReapplyAurasAtTurnStart only strips aura-applied effects and never
/// unrelated buffs the same unit applied via an Active ability.
/// </summary>
public bool IsAuraApplication { get; set; }
// ── Intra-action position tracking (set per-loop-iteration by ExecuteSingleAction) ──
/// <summary>Index of the currently-executing effect within <see cref="CurrentActionAllEffects"/>.</summary>
+336 -96
View File
@@ -66,19 +66,33 @@ public static class AbilitySystem
// ── Parsing ────────────────────────────────────────────────────────────────
// Content-keyed parse cache. FireTrigger parses every card's AbilitiesJson on every
// occurrence — the same JSON strings repeat constantly, so caching by content is a
// large win and safe across sessions. Parsed definitions are treated as immutable by
// the engine (ability-list mutations always serialize a NEW string). Bounded to guard
// against unbounded growth from AddAbilityEffect-generated variants.
private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, AbilityDefinition[]>
_parseCache = new();
private const int MaxParseCacheEntries = 4096;
public static AbilityDefinition[] ParseAbilities(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
if (_parseCache.TryGetValue(json, out var cached)) return cached;
AbilityDefinition[] parsed;
try
{
return JsonSerializer.Deserialize<AbilityDefinition[]>(json, _jsonOpts) ?? [];
parsed = JsonSerializer.Deserialize<AbilityDefinition[]>(json, _jsonOpts) ?? [];
}
catch (JsonException ex)
{
// One malformed card must not poison every trigger scan / activation.
_log?.LogWarning(ex, "[ABILITY] Unparseable AbilitiesJson ignored: {Json}", json);
return [];
parsed = [];
}
if (_parseCache.Count >= MaxParseCacheEntries) _parseCache.Clear();
_parseCache[json] = parsed;
return parsed;
}
public static Models.Action[] ParseEffects(string? json)
@@ -783,7 +797,9 @@ public static class AbilitySystem
if (paused) return state;
}
ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: false,
// Player-driven flow: mandatory explicit picks must prompt (PendingTargetPick),
// never silently auto-take the first N candidates.
ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: true,
activationRange: range, forceDuration: forceDuration);
return state;
}
@@ -986,7 +1002,8 @@ public static class AbilitySystem
? JsonSerializer.Deserialize<AbilityRange>(pending.RangeJson, _jsonOpts)
: null;
ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: false,
// Player-driven flow: mandatory explicit picks must prompt, not auto-resolve.
ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: true,
activationRange: range, forceDuration: forceDuration);
return state;
@@ -1027,7 +1044,8 @@ public static class AbilitySystem
var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source };
var allActions = branches[branchIndex].Actions.Concat(continuation).ToArray();
ExecuteActions(allActions, ctx, clientTargets: null, requireClientTargets: false,
// Player-driven flow: mandatory explicit picks must prompt, not auto-resolve.
ExecuteActions(allActions, ctx, clientTargets: null, requireClientTargets: true,
activationRange: range, forceDuration: forceDuration);
return state;
}
@@ -1246,7 +1264,8 @@ public static class AbilitySystem
// Correct AND-group order: [preceding] + [chosen/remaining] + [outer continuation].
var allActions = preceding.Concat(chosen).Concat(continuation).ToArray();
ExecuteActions(allActions, ctx, clientTargets: null, requireClientTargets: false,
// Player-driven flow: mandatory explicit picks must prompt, not auto-resolve.
ExecuteActions(allActions, ctx, clientTargets: null, requireClientTargets: true,
activationRange: range, forceDuration: forceDuration);
return state;
}
@@ -1323,8 +1342,8 @@ public static class AbilitySystem
{
AbilityRange? rrcRange = pending.RangeJson is not null
? JsonSerializer.Deserialize<AbilityRange>(pending.RangeJson, _jsonOpts) : null;
ExecuteActions(rrcContinuation, rrcCtx, clientTargets: null, activationRange: rrcRange,
forceDuration: rrcActionDuration);
ExecuteActions(rrcContinuation, rrcCtx, clientTargets: null, requireClientTargets: true,
activationRange: rrcRange, forceDuration: rrcActionDuration);
}
}
@@ -1431,6 +1450,15 @@ public static class AbilitySystem
? JsonSerializer.Deserialize<Effect>(pending.EffectJson, _jsonOpts) as ChannelCardFromZoneEffect
: null;
// Card constraint filters.
if (ccze?.Filters is { Length: > 0 } && !FiltersMatch(ccze.Filters, ccCard, ctx))
break;
// Channel-range constraints on the picked tile — throw so the client's
// rejected pick re-prompts instead of silently consuming the effect.
if (!IsWithinChannelConstraints(state, pending.ActorId, ccDestPlayer, ccCard, ccze, pickedTile))
throw new GameException("OUT_OF_CHANNEL_RANGE");
// Affinity check.
if (ccze?.IgnoreAffinity != true && Enum.TryParse<Affinity>(ccCard.Affinity, out var tpAffinity))
{
@@ -1485,8 +1513,8 @@ public static class AbilitySystem
{
AbilityRange? range = pending.RangeJson is not null
? JsonSerializer.Deserialize<AbilityRange>(pending.RangeJson, _jsonOpts) : null;
ExecuteActions(continuation, ctx, clientTargets: null, activationRange: range,
forceDuration: tpActionDuration);
ExecuteActions(continuation, ctx, clientTargets: null, requireClientTargets: true,
activationRange: range, forceDuration: tpActionDuration);
}
}
return state;
@@ -1544,6 +1572,10 @@ public static class AbilitySystem
? JsonSerializer.Deserialize<Effect>(pending.EffectJson, _jsonOpts) as ChannelCardFromZoneEffect
: null;
// Card constraint filters.
if (ppCcze?.Filters is { Length: > 0 } && !FiltersMatch(ppCcze.Filters, ppCard, ppCtx))
break;
if (ppCcze?.TargetTile == true)
{
// Chain into a tile pick for the chosen dest player.
@@ -1567,36 +1599,14 @@ public static class AbilitySystem
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();
}
// Random empty tile satisfying the channel-range constraints.
Coord? ppCoord = ppBoard.Tiles.Values
.Where(t => t.IsEmpty)
.Where(t => IsWithinChannelConstraints(state, pending.ActorId, ppDest, ppCard, ppCcze, t.Coord))
.Select(t => t.Coord)
.OrderBy(_ => Random.Shared.Next())
.Cast<Coord?>()
.FirstOrDefault();
if (ppCoord is null) break;
// Affinity check.
@@ -1661,8 +1671,8 @@ public static class AbilitySystem
{
AbilityRange? ppRange = pending.RangeJson is not null
? JsonSerializer.Deserialize<AbilityRange>(pending.RangeJson, _jsonOpts) : null;
ExecuteActions(ppContinuation, ppCtx, clientTargets: null, activationRange: ppRange,
forceDuration: ppActionDuration);
ExecuteActions(ppContinuation, ppCtx, clientTargets: null, requireClientTargets: true,
activationRange: ppRange, forceDuration: ppActionDuration);
}
}
return state;
@@ -1819,20 +1829,126 @@ 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)
// ── Zone-scope card picks ─────────────────────────────────────────────
// For Hand/Deck/Discard/AnyZone card targets the client cannot enumerate the
// pool itself (hidden zones); it submits player accountIds (or nothing).
// Pause with an explicit candidates list so the chooser picks real cards;
// resumed via game.target_pick with card InstanceIds. Only on player-driven
// paths (requireClientTargets) — automated paths keep auto-resolving.
if (requireClientTargets
&& sel.Scope is TargetScope.Hand or TargetScope.Deck or TargetScope.Discard or TargetScope.AnyZone
&& sel.Type is not (TargetType.Player or TargetType.Tile)
&& !sel.Count.All
&& sel.Chooser != TargetChooser.Random
&& sel.Ownership is not (TargetOwnership.Self or TargetOwnership.ExactSelf
or TargetOwnership.Target or TargetOwnership.Random))
{
var tpChooser = sel.Chooser == TargetChooser.Opponent
? ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId
: ctx.State.Players.Values
var providedIds = clientTargets?
.Where(t => t.ActionIndex == actionIndex && t.InstanceId is not null)
.Select(t => t.InstanceId!)
.ToList() ?? [];
bool onlyPlayerIds = providedIds.Count == 0
|| providedIds.All(id => ctx.State.Players.ContainsKey(id));
if (onlyPlayerIds)
{
var pool = BuildCandidates(sel, ctx.State, ctx.ActorId);
if (providedIds.Count > 0)
{
var allowedOwners = providedIds.ToHashSet();
pool = pool.Where(c =>
FindCardOwner(ctx.State, c.InstanceId)?.AccountId is { } cardOwnerId
&& allowedOwners.Contains(cardOwnerId)).ToList();
}
if (sel.Filters is { Length: > 0 })
pool = pool.Where(c => FiltersMatch(sel.Filters, c, ctx)).ToList();
// Pause only when the chooser has an actual choice to make; otherwise
// fall through and let ResolveTargets auto-take the pool.
if (pool.Count > sel.Count.N || (sel.Count.UpTo && pool.Count > 0))
{
var zoneChooserId = sel.Chooser switch
{
TargetChooser.Opponent =>
ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId,
TargetChooser.Ally => ctx.State.Players.Values
.FirstOrDefault(p => p.AccountId != ctx.ActorId
&& ctx.State.AreAllies(p.AccountId, ctx.ActorId))
?.AccountId ?? ctx.ActorId,
_ => ctx.ActorId,
};
var zoneCandidates = pool
.Select(c => new { instanceId = c.InstanceId, name = c.Name, cardType = c.CardType })
.ToArray();
ctx.State.PendingTargetPick = new PendingTargetPick
{
ActorId = ctx.ActorId,
ChooserActorId = zoneChooserId,
SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty,
ActionJson = JsonSerializer.Serialize(action, _jsonOpts),
CandidatesJson = JsonSerializer.Serialize(zoneCandidates),
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;
}
// No real choice: substitute the pool's card ids as the client picks so
// ResolveTargets (which expects card InstanceIds and enforces mandatory
// explicit targets) resolves them directly.
var autoPicks = pool.Take(sel.Count.N)
.Select(c => new AbilityTarget(actionIndex, c.InstanceId));
clientTargets = (clientTargets ?? [])
.Where(t => t.ActionIndex != actionIndex)
.Concat(autoPicks)
.ToList();
}
}
// Pause for a target pick when a human choice is required and missing:
// • Chooser=Opponent/Ally — the non-activating player must pick.
// • Chooser=Self on a player-driven path (requireClientTargets) with no targets
// submitted for this action — happens after OR/XOR Random group resolution
// (indices shifted) or any flow where the client couldn't pre-target.
// Prompting beats throwing INSUFFICIENT_TARGETS at the player.
bool actionServerResolved =
sel.Type == TargetType.Player
|| sel.Count.All
|| sel.Chooser == TargetChooser.Random
|| sel.Ownership is TargetOwnership.Self or TargetOwnership.ExactSelf
or TargetOwnership.Target or TargetOwnership.Random;
bool hasTargetsForAction = clientTargets?.Any(t => t.ActionIndex == actionIndex
&& (t.InstanceId is not null || t.Coord is not null)) == true;
bool chooserIsOtherPlayer = sel.Chooser is TargetChooser.Opponent or TargetChooser.Ally;
// Never pause into an unwinnable pick: for card targets verify at least one valid
// candidate exists (tile pools are filter-dependent and assumed non-empty).
// With an empty pool we fall through and let ResolveTargets fail fast.
bool PickPoolNonEmpty() =>
sel.Type == TargetType.Tile
|| BuildCandidates(sel, ctx.State, ctx.ActorId)
.Any(c => sel.Filters is not { Length: > 0 } || FiltersMatch(sel.Filters, c, ctx));
if (!actionServerResolved
&& !hasTargetsForAction
&& (chooserIsOtherPlayer || (requireClientTargets && !sel.Count.UpTo))
&& PickPoolNonEmpty())
{
var tpChooser = sel.Chooser switch
{
TargetChooser.Opponent =>
ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId,
TargetChooser.Ally => ctx.State.Players.Values
.FirstOrDefault(p => p.AccountId != ctx.ActorId
&& ctx.State.AreAllies(p.AccountId, ctx.ActorId))
?.AccountId ?? ctx.ActorId;
?.AccountId ?? ctx.ActorId,
_ => ctx.ActorId,
};
ctx.State.PendingTargetPick = new PendingTargetPick
{
@@ -2858,6 +2974,11 @@ public static class AbilitySystem
}
break;
}
// Player target: reveal the top N cards of that player's deck.
case RevealCardsEffect rvc when target is PlayerState revPs:
foreach (var revealed in revPs.Deck.TakeLast(Math.Max(1, rvc.N)))
revealed.IsRevealed = true;
break;
case RevealCardsEffect when target is CardInstance ci:
ci.IsRevealed = true;
break;
@@ -3011,10 +3132,11 @@ public static class AbilitySystem
}
// ── §5.10 Control ─────────────────────────────────────────────────
case TakeControlEffect when target is FieldCard fc4:
case TakeControlEffect tce when target is FieldCard fc4:
{
var originalOwner = FindCardOwner(ctx.State, fc4.InstanceId);
if (originalOwner is not null) originalOwner.Field.Remove(fc4);
if (originalOwner is null || originalOwner.AccountId == ctx.ActorId) break;
originalOwner.Field.Remove(fc4);
ctx.State.Players[ctx.ActorId].Field.Add(fc4);
// Keep the board's occupant-owner in sync so ownership filters,
// sacrifice checks and tile conditions agree with the new controller.
@@ -3023,6 +3145,29 @@ public static class AbilitySystem
tcBoard.RemoveUnit(fc4.InstanceId);
tcBoard.PlaceUnit(tcPos, fc4.InstanceId, ctx.ActorId);
}
// Honour the effect's own Duration when the action carries none
// (mirrors the ObstructMovementType pattern); PermanentInMatch = keep.
var tcDuration = duration is null || duration.Type is DurationType.Instant
? tce.Duration
: duration;
TrackEffect(new ReturnControlEffect { ToAccountId = originalOwner.AccountId },
fc4.InstanceId, tcDuration, ctx);
break;
}
case ReturnControlEffect rce when target is FieldCard fcRet:
{
if (string.IsNullOrEmpty(rce.ToAccountId)
|| !ctx.State.Players.TryGetValue(rce.ToAccountId, out var backTo))
break;
var holder = FindCardOwner(ctx.State, fcRet.InstanceId);
if (holder is null || holder.AccountId == rce.ToAccountId) break;
holder.Field.Remove(fcRet);
backTo.Field.Add(fcRet);
if (fcRet.Position is { } rcPos && ctx.State.Board is { } rcBoard)
{
rcBoard.RemoveUnit(fcRet.InstanceId);
rcBoard.PlaceUnit(rcPos, fcRet.InstanceId, rce.ToAccountId);
}
break;
}
case GrantMovementControlEffect gmc when target is FieldCard fc6:
@@ -3287,6 +3432,10 @@ public static class AbilitySystem
var board = ctx.State.Board;
if (board is null) break;
// Card constraint filters (e.g. "channel a Spirit costing 3 or less").
if (ccze.Filters is { Length: > 0 } && !FiltersMatch(ccze.Filters, ciCcze, ctx))
break;
// Determine destination player.
PlayerState? ccDestPlayer = ccze.UnderControlOf switch
{
@@ -3348,36 +3497,15 @@ public static class AbilitySystem
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();
}
// Random empty tile satisfying the channel-range constraints
// (destination arch range by default; InOwn/InTargetChannelRange extras).
Coord? ccDestCoord = board.Tiles.Values
.Where(t => t.IsEmpty)
.Where(t => IsWithinChannelConstraints(ctx.State, ctx.ActorId, ccDestPlayer, ciCcze, ccze, t.Coord))
.Select(t => t.Coord)
.OrderBy(_ => Random.Shared.Next())
.Cast<Coord?>()
.FirstOrDefault();
if (ccDestCoord is null) break;
// Affinity check.
@@ -3580,9 +3708,38 @@ public static class AbilitySystem
case "Hand": sapPs.Hand.Add(card); break;
case "Discard": sapPs.Discard.Add(card); break;
case "Battlefield":
// Basic: put in discard if no tile available.
sapPs.Discard.Add(card);
{
// Place on a random empty tile with a compatible affinity;
// fall back to hand when no valid tile exists.
var sapBoard = ctx.State.Board;
bool hasAff = Enum.TryParse<Affinity>(card.Affinity, out var sapAff)
&& card.Affinity != "Void";
var sapTile = sapBoard?.Tiles.Values
.Where(t => t.IsEmpty)
.Where(t => !hasAff || AffinitySystem.IsAffinityValid(t, sapAff))
.OrderBy(_ => Random.Shared.Next())
.FirstOrDefault();
if (sapBoard is null || sapTile is null
|| card.CardType is not ("Spirit" or "SpiritToken"))
{
sapPs.Hand.Add(card);
break;
}
var sapField = GameEngine.ToFieldCardInternal(card, sapTile.Coord);
sapPs.Field.Add(sapField);
sapBoard.PlaceUnit(sapTile.Coord, sapField.InstanceId, sapPs.AccountId);
FireTrigger(ctx.State, new TriggerOccurrence
{
Kind = TriggerEventKind.UnitEnterBattlefield,
ActorId = sapPs.AccountId,
UnitType = sapField.CardType,
Data = new TriggerEventData { SourceId = sapField.InstanceId },
});
EvaluateAurasOnEnter(ctx.State, sapField.InstanceId);
ApplyPassivesForSource(ctx.State, sapField.InstanceId, sapPs.AccountId);
ApplyPassivesToNewTarget(ctx.State, sapField.InstanceId);
break;
}
default: sapPs.Hand.Add(card); break;
}
}
@@ -4135,6 +4292,45 @@ public static class AbilitySystem
return result;
}
/// <summary>
/// True when <paramref name="coord"/> satisfies the channel-range constraints of a
/// ChannelCardFromZone resolution: the destination player's ArchSpirit range by default
/// (unless IgnoreChannelRange), plus the optional InOwnChannelRange (actor's arch) and
/// InTargetChannelRange (destination player's arch) extra constraints.
/// </summary>
private static bool IsWithinChannelConstraints(
GameState state, string actorId, PlayerState destPlayer,
CardInstance card, ChannelCardFromZoneEffect? ccze, Coord coord)
{
var board = state.Board;
if (board is null) return false;
bool InRangeOf(FieldCard? arch)
{
if (arch?.Position is not { } archPos) return false;
var d = board.HexSides > 0
? HexGrid.Distance(archPos, coord, board.HexSides)
: archPos.ManhattanDistance(coord);
return d >= (card.MinChannelRange ?? 1) && d <= (card.MaxChannelRange ?? 2);
}
// Default constraint (legacy behaviour): destination player's arch range,
// or unconstrained when that arch is not placed.
if (ccze?.IgnoreChannelRange != true
&& ccze?.InOwnChannelRange != true
&& ccze?.InTargetChannelRange != true)
{
return destPlayer.ArchSpirit?.Position is null || InRangeOf(destPlayer.ArchSpirit);
}
if (ccze?.InOwnChannelRange == true
&& !InRangeOf(state.Players.GetValueOrDefault(actorId)?.ArchSpirit))
return false;
if (ccze?.InTargetChannelRange == true && !InRangeOf(destPlayer.ArchSpirit))
return false;
return true;
}
/// <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
@@ -4312,7 +4508,9 @@ public static class AbilitySystem
case IsOpponentTurnCondition:
return ctx.State.ActivePlayerAccountId != ctx.ActorId;
case IsAllyTurnCondition:
return ctx.State.ActivePlayerAccountId == ctx.ActorId;
// A teammate's turn — not the owner's own, not an enemy's.
return ctx.State.ActivePlayerAccountId != ctx.ActorId
&& ctx.State.AreAllies(ctx.State.ActivePlayerAccountId, ctx.ActorId);
case IsActivePlayerTurnCondition iaptc:
return iaptc.Ownership.ToLowerInvariant() == "owner"
? ctx.State.ActivePlayerAccountId == ctx.ActorId
@@ -5088,9 +5286,18 @@ public static class AbilitySystem
private sealed class TrackedDuration
{
public DurationModel Duration { get; set; } = new();
/// <summary>AccountId of the ability actor who applied the effect.</summary>
public string OwnerAccountId { get; set; } = string.Empty;
/// <summary>
/// AccountId of the SOURCE UNIT's owner at apply time. Differs from
/// <see cref="OwnerAccountId"/> after TakeControl or opponent-cast buffs.
/// Null on records written before this field existed (falls back to OwnerAccountId).
/// </summary>
public string? SourceOwnerAccountId { get; set; }
/// <summary>True for DOT/HOT tick effects (apply each turn); false for reversal effects.</summary>
public bool IsTick { get; set; }
/// <summary>True when the effect was applied by an Aura (used by ReapplyAurasAtTurnStart).</summary>
public bool IsAura { get; set; }
}
/// <summary>
@@ -5114,8 +5321,13 @@ public static class AbilitySystem
EffectJson = JsonSerializer.Serialize(reversal, _jsonOpts),
DurationJson = JsonSerializer.Serialize(new TrackedDuration
{
Duration = duration,
OwnerAccountId = ctx.ActorId,
Duration = duration,
OwnerAccountId = ctx.ActorId,
SourceOwnerAccountId = ctx.Source is null
? null
: FindUnitOwner(ctx.State, ctx.Source.InstanceId)
?? FindCardOwner(ctx.State, ctx.Source.InstanceId)?.AccountId,
IsAura = ctx.IsAuraApplication,
}, _jsonOpts),
TurnsRemaining = duration.N ?? 0,
Label = LabelFromReversal(reversal),
@@ -5198,6 +5410,7 @@ public static class AbilitySystem
SetBaseAffinity2Effect _ => "Affinity Overridden",
ClearPreventDeathEffect _ => "Death Shield",
ClearPreventNextDamageEffect _ => "Damage Block",
ReturnControlEffect _ => "Mind Control",
SetFixedSacrificeReturnEffect _ => "Sacrifice Override",
SetHealthMinimumEffect e => $"HP Min {e.Minimum}",
_ => reversal.GetType().Name.Replace("Effect", ""),
@@ -5295,7 +5508,6 @@ public static class AbilitySystem
break;
case DurationType.UntilStartOfOwnerTurn:
case DurationType.UntilStartOfSourceOwnerTurn:
if (!isEndOfTurn && currentPlayerId == td.OwnerAccountId)
{
if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId);
@@ -5303,6 +5515,17 @@ public static class AbilitySystem
}
break;
case DurationType.UntilStartOfSourceOwnerTurn:
// Anchored to the SOURCE UNIT's owner (may differ from the actor after
// TakeControl / opponent-cast buffs). Old records without the field
// fall back to the actor.
if (!isEndOfTurn && currentPlayerId == (td.SourceOwnerAccountId ?? td.OwnerAccountId))
{
if (!td.IsTick) ApplyReversal(state, ae, td.OwnerAccountId);
toRemove.Add(ae);
}
break;
case DurationType.ForNTurns:
if (isEndOfTurn)
{
@@ -5682,12 +5905,23 @@ public static class AbilitySystem
int dist = auraPos.ManhattanDistance(target.Position!.Value);
if (dist < min || dist > max) continue;
// Strip stale tracked effects for this source→target pair without reversal.
// Current stats (CurrentMp, CurrentDefense) were already reset by the
// turn transition, so applying the reversal would incorrectly subtract.
// Strip stale AURA-applied tracked effects for this source→target pair
// without reversal. Current stats (CurrentMp, CurrentDefense) were already
// reset by the turn transition, so applying the reversal would incorrectly
// subtract. Non-aura effects from the same source (e.g. an Active-ability
// buff it cast on this target) must NOT be stripped.
state.ActiveEffects.RemoveAll(ae =>
ae.SourceInstanceId == auraUnit.InstanceId &&
ae.TargetRef == target.InstanceId);
{
if (ae.SourceInstanceId != auraUnit.InstanceId ||
ae.TargetRef != target.InstanceId)
return false;
try
{
var aeTd = JsonSerializer.Deserialize<TrackedDuration>(ae.DurationJson, _jsonOpts);
return aeTd?.IsAura == true;
}
catch { return false; }
});
// Re-apply fresh — same path as when the unit entered the aura.
ApplyAuraEffects(state, auraOwnerId, auraUnit, def, target.InstanceId);
@@ -5758,7 +5992,13 @@ public static class AbilitySystem
string targetUnitId)
{
// Honour aura-level activation conditions (e.g. IsOnTileWithAffinity of the aura source).
var ctx = new AbilityContext { State = state, ActorId = auraOwnerId, Source = auraUnit };
var ctx = new AbilityContext
{
State = state,
ActorId = auraOwnerId,
Source = auraUnit,
IsAuraApplication = true,
};
if (def.ActivationConditions is { Length: > 0 } &&
!def.ActivationConditions.All(c => EvaluateCondition(c, ctx, auraUnit)))
return;
@@ -0,0 +1,189 @@
namespace SOR.Game.Abilities;
using System.Text.Json;
using SOR.Game.Abilities.Models;
/// <summary>
/// Structural validation for authored AbilitiesJson. Used by the admin CardEditor at
/// save time so unplayable content (unparseable JSON, dead triggers, no-op effects,
/// card-type mismatches) is rejected before it reaches the catalog.
///
/// Keep the supported-trigger set in sync with <see cref="AbilitySystem.TriggerMatches"/>
/// and the engine's FireTrigger call sites — see SOR.Abilities-Review-and-solutions.md §C3.
/// </summary>
public static class AbilityValidator
{
/// <summary>Trigger types the engine both fires and matches.</summary>
private static readonly HashSet<Type> _supportedTriggers =
[
typeof(OnTurnStartTrigger), typeof(OnTurnEndTrigger),
typeof(OnChanneledTrigger), typeof(OnAscendTrigger),
typeof(OnTransitionTrigger), typeof(OnUnitMoveTrigger),
typeof(OnUnitAttackTrigger), typeof(OnUnitAbilityActivatedTrigger),
typeof(OnDamageDealtTrigger), typeof(OnDamagePreventedTrigger),
typeof(OnHealedTrigger), typeof(BeforeDamageAppliedTrigger),
typeof(BeforeUnitDeathTrigger), typeof(OnUnitEnterBattlefieldTrigger),
typeof(OnUnitLeaveBattlefieldTrigger),typeof(OnUnitDeathTrigger),
typeof(OnUnitSentToDiscardTrigger), typeof(OnSpiritSacrificedTrigger),
typeof(OnTokenSummonedTrigger), typeof(OnRuinActivationTrigger),
typeof(OnUnitOccupyRuinTrigger), typeof(OnSPGainedTrigger),
typeof(OnSPSpentTrigger), typeof(OnSTGainedTrigger),
typeof(OnSTSpentTrigger), typeof(OnCardDrawnTrigger),
typeof(OnEnterAuraRangeTrigger), typeof(OnLeaveAuraRangeTrigger),
];
/// <summary>Effect types with no ExecuteEffect implementation (silent no-ops).</summary>
private static readonly HashSet<Type> _unimplementedEffects =
[
typeof(ChannelCardEffect),
typeof(SetStatModMultiplierEffect),
typeof(ModifySacrificeTokenReturnEffect),
];
/// <summary>
/// Validates the given AbilitiesJson for a card of the given type
/// ("Spirit" | "ArchSpirit" | "SpiritToken" | "Repentance" | "Instinct" | "Ruin" | "Terramorpha").
/// Returns a list of human-readable errors; empty = valid.
/// </summary>
public static IReadOnlyList<string> Validate(string? abilitiesJson, string cardType)
{
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(abilitiesJson)) return errors;
AbilityDefinition[] defs;
try
{
defs = JsonSerializer.Deserialize<AbilityDefinition[]>(
abilitiesJson, AbilitySystem.CreateJsonOptions()) ?? [];
}
catch (JsonException ex)
{
errors.Add($"AbilitiesJson does not deserialize with the game engine's options: {ex.Message}");
return errors;
}
bool isEffectCard = cardType is "Repentance" or "Instinct";
for (int i = 0; i < defs.Length; i++)
{
var def = defs[i];
var name = string.IsNullOrWhiteSpace(def.Name) ? $"ability #{i + 1}" : $"\"{def.Name}\"";
switch (def.Type)
{
case AbilityType.Triggered:
if (def.TriggerEvent is null)
errors.Add($"{name}: Triggered ability has no TriggerEvent.");
else if (!_supportedTriggers.Contains(def.TriggerEvent.GetType()))
errors.Add($"{name}: trigger \"{def.TriggerEvent.GetType().Name}\" is not implemented by the game engine — it will never fire.");
break;
case AbilityType.Passive:
if (def.ActionGroup is { } pag && pag.LogicOp != ActionGroupLogicOp.And)
errors.Add($"{name}: Passive abilities cannot use OR/XOR action groups (no interactive picks); only leaf actions would execute.");
break;
case AbilityType.Aura:
if (def.AuraRange is null)
errors.Add($"{name}: Aura ability has no AuraRange — it will never apply.");
break;
}
if (isEffectCard)
{
if (def.Type != AbilityType.Active)
errors.Add($"{name}: {cardType} cards resolve on channel — only Active abilities execute ({def.Type} will never run).");
if (def.Range is not null)
errors.Add($"{name}: {cardType} cards are not battlefield units — an ability Range makes every target resolve as out-of-range. Remove the Range.");
}
foreach (var action in EnumerateActions(def))
foreach (var effect in EnumerateEffects(action))
{
if (_unimplementedEffects.Contains(effect.GetType()))
errors.Add($"{name}: effect \"{effect.GetType().Name}\" has no engine implementation (silent no-op).");
if (effect is SummonTokenEffect ste)
ValidateTokenDef(ste.TokenDefJson, name, errors);
}
}
if (isEffectCard && defs.Count(d => d.Type == AbilityType.Active) != 1)
errors.Add($"{cardType} cards must define exactly one Active ability (found {defs.Count(d => d.Type == AbilityType.Active)}).");
return errors;
}
private static void ValidateTokenDef(string tokenDefJson, string abilityName, List<string> errors)
{
CardInstance? proto;
try
{
proto = JsonSerializer.Deserialize<CardInstance>(
tokenDefJson, AbilitySystem.CreateJsonOptions());
}
catch (JsonException ex)
{
errors.Add($"{abilityName}: SummonToken TokenDefJson does not deserialize: {ex.Message}");
return;
}
if (proto is null)
{
errors.Add($"{abilityName}: SummonToken TokenDefJson is empty.");
return;
}
// Nested token abilities must themselves be valid.
if (!string.IsNullOrWhiteSpace(proto.AbilitiesJson))
foreach (var nested in Validate(proto.AbilitiesJson, "SpiritToken"))
errors.Add($"{abilityName} (token abilities): {nested}");
}
/// <summary>All actions in a definition: root group tree, branches, aura enter/leave.</summary>
private static IEnumerable<Models.Action> EnumerateActions(AbilityDefinition def)
{
#pragma warning disable CS0618 // legacy flat Actions still validated
foreach (var a in def.Actions) yield return a;
#pragma warning restore CS0618
if (def.ActionGroup is { } ag)
foreach (var a in EnumerateGroup(ag)) yield return a;
if (def.OnEnterAuraActions is { } ea)
foreach (var a in EnumerateGroup(ea)) yield return a;
if (def.OnLeaveAuraActions is { } la)
foreach (var a in EnumerateGroup(la)) yield return a;
}
private static IEnumerable<Models.Action> EnumerateGroup(ActionGroup group)
{
foreach (var a in group.Actions)
{
yield return a;
if (a.ChooseOne is { } co)
foreach (var branch in co.Branches)
foreach (var ba in branch.Actions)
yield return ba;
}
foreach (var child in group.Groups)
foreach (var a in EnumerateGroup(child))
yield return a;
}
/// <summary>All effects in an action, descending into SearchDeck.ThenGroup and ApplyOnEvent trees.</summary>
private static IEnumerable<Effect> EnumerateEffects(Models.Action action)
{
foreach (var e in action.Effects)
{
yield return e;
switch (e)
{
case SearchDeckEffect { ThenGroup: { } tg }:
foreach (var a in EnumerateGroup(tg))
foreach (var ne in EnumerateEffects(a)) yield return ne;
break;
case ApplyOnEventEffect { ActionGroup: { } aog }:
foreach (var a in EnumerateGroup(aog))
foreach (var ne in EnumerateEffects(a)) yield return ne;
break;
}
}
}
}
@@ -168,14 +168,12 @@ public sealed class ControlledTileCountWithAffinityCondition : Condition
// ── §6.6 Extended unit conditions ─────────────────────────────────────────────
/// <summary>Subject unit's CardType must match. Values: "Spirit", "ArchSpirit", "SpiritToken".</summary>
[PolyType(typeof(UnitTypeIsCondition), "UnitTypeIs")]
public sealed class UnitTypeIsCondition : Condition
{
public string UnitType { get; set; } = "Spirit";
}
/// <summary>Subject unit is owned by the specified player group.</summary>
[PolyType(typeof(OwnershipIsCondition), "OwnershipIs")]
public sealed class OwnershipIsCondition : Condition
{
/// <summary>"Self" | "Ally" | "Opponent" | "Owner"</summary>
@@ -183,7 +181,6 @@ public sealed class OwnershipIsCondition : Condition
}
/// <summary>Subject is the exact card instance that owns this ability (by InstanceId).</summary>
[PolyType(typeof(IsThisCardCondition), "IsThisCard")]
public sealed class IsThisCardCondition : Condition { }
/// <summary>
@@ -192,7 +189,6 @@ public sealed class IsThisCardCondition : Condition { }
/// "MovementPoints", "MaxMovementPoints", "MinAttackRange", "MaxAttackRange",
/// "MinChannelRange", "MaxChannelRange", "Tier".
/// </summary>
[PolyType(typeof(UnitPropertyCompareCondition), "UnitPropertyCompare")]
public sealed class UnitPropertyCompareCondition : Condition
{
public string PropertyName { get; set; } = string.Empty;
@@ -205,7 +201,6 @@ public sealed class UnitPropertyCompareCondition : Condition
/// PropertyName values: "SP", "ST", "SPAccumulation", "HandSize", "DeckSize", "DiscardSize".
/// Subject field ("Self", "Owner", "Ally", "Opponent") identifies which player.
/// </summary>
[PolyType(typeof(PlayerPropertyCompareCondition), "PlayerPropertyCompare")]
public sealed class PlayerPropertyCompareCondition : Condition
{
public string PropertyName { get; set; } = "SP";
@@ -214,7 +209,6 @@ public sealed class PlayerPropertyCompareCondition : Condition
}
/// <summary>The specified player's hand contains at least N cards of the given type and/or affinity.</summary>
[PolyType(typeof(HandContainsCountCondition), "HandContainsCount")]
public sealed class HandContainsCountCondition : Condition
{
public string? CardType { get; set; } // null = any
@@ -226,7 +220,6 @@ public sealed class HandContainsCountCondition : Condition
/// <summary>
/// X copies of the source card's definition exist in the given zone(s) for the given ownership.
/// </summary>
[PolyType(typeof(CardDefinitionCountInZoneCondition), "CardDefinitionCountInZone")]
public sealed class CardDefinitionCountInZoneCondition : Condition
{
/// <summary>"Hand" | "Deck" | "Discard" | "Battlefield"</summary>
@@ -238,7 +231,6 @@ public sealed class CardDefinitionCountInZoneCondition : Condition
}
/// <summary>Subject unit is within [Min, Max] Manhattan distance of a unit matching type + ownership.</summary>
[PolyType(typeof(IsInRangeOfUnitCondition), "IsInRangeOfUnit")]
public sealed class IsInRangeOfUnitCondition : Condition
{
public int Min { get; set; } = 1;
@@ -249,7 +241,6 @@ public sealed class IsInRangeOfUnitCondition : Condition
}
/// <summary>The tile the subject unit occupies is occupied by a unit matching the given type/ownership/filters.</summary>
[PolyType(typeof(TileOccupantCondition), "TileOccupant")]
public sealed class TileOccupantCondition : Condition
{
public string UnitType { get; set; } = "Unit";
@@ -258,7 +249,6 @@ public sealed class TileOccupantCondition : Condition
}
/// <summary>At least N surrounding tiles within [Min, Max] distance match the given affinity/occupancy filters.</summary>
[PolyType(typeof(SurroundingTileCondition), "SurroundingTile")]
public sealed class SurroundingTileCondition : Condition
{
public int Min { get; set; } = 1;
@@ -269,7 +259,6 @@ public sealed class SurroundingTileCondition : Condition
}
/// <summary>Compares the source player's SP accumulation per turn against a value.</summary>
[PolyType(typeof(SPAccumulationCompareCondition), "SPAccumulationCompare")]
public sealed class SPAccumulationCompareCondition : Condition
{
public Comparator Comparator { get; set; } = Comparator.GreaterThanOrEqual;
@@ -280,7 +269,6 @@ public sealed class SPAccumulationCompareCondition : Condition
/// The aggregate channeling cost (SP or ST) of cards matching the given filters in the player's hand
/// meets the comparator threshold.
/// </summary>
[PolyType(typeof(CostOfCardsInHandCondition), "CostOfCardsInHand")]
public sealed class CostOfCardsInHandCondition : Condition
{
/// <summary>"SP" | "ST"</summary>
@@ -94,6 +94,7 @@ using SOR.Database.Enums;
[PolyType(typeof(TakeControlEffect), "TakeControl")]
[PolyType(typeof(GrantMovementControlEffect), "GrantMovementControl")]
[PolyType(typeof(SetFixedSacrificeReturnEffect),"SetFixedSacrificeReturn")]
[PolyType(typeof(ReturnControlEffect), "__ReturnControl")]
// §5.11 Token
[PolyType(typeof(SummonTokenEffect), "SummonToken")]
// §5.12 Deferred
@@ -290,6 +291,12 @@ public sealed class RepositionUnitEffect : Effect
// ── §5.10 Control effects ─────────────────────────────────────────────────────
public sealed class TakeControlEffect : Effect { public DurationModel Duration { get; set; } = DurationModel.EndOfTurn; }
/// <summary>
/// Internal reversal for <see cref="TakeControlEffect"/>: returns the target unit to
/// the given player when the take-control duration expires. Not authorable.
/// </summary>
public sealed class ReturnControlEffect : Effect { public string ToAccountId { get; set; } = string.Empty; }
public sealed class GrantMovementControlEffect : Effect { public int N { get; set; } = 1; }
/// <summary>Overrides the sacrifice formula: controller receives exactly StAmount ST instead.</summary>
public sealed class SetFixedSacrificeReturnEffect : Effect { public int StAmount { get; set; } }
@@ -369,6 +376,11 @@ public sealed class ChannelCardFromZoneEffect : Effect
/// <summary>Who controls the channeled unit. "Self" | "Ally" | "Opponent" | "Random" | "Target"</summary>
public string UnderControlOf { get; set; } = "Self";
public bool IgnoreChannelCost { get; set; }
/// <summary>
/// Reserved. Ability-driven channels are resolved inside an already-validated action
/// and are never subject to the own-turn constraint, so this flag is accepted but has
/// no effect. Kept for forward compatibility with player-initiated channel variants.
/// </summary>
public bool IgnoreTurnConstraint { get; set; }
public bool IgnoreChannelRange { get; set; }
public bool IgnoreAffinity { get; set; }
@@ -152,7 +152,6 @@ public sealed class TileIsInArchSpiritChannelRangeFilter : Filter
// ── Additional filters ────────────────────────────────────────────────────────
/// <summary>Unit must be owned by the specified player group.</summary>
[PolyType(typeof(OwnershipFilter), "Ownership")]
public sealed class OwnershipFilter : Filter
{
/// <summary>"Self" | "Ally" | "Opponent" | "Owner" | "Any"</summary>
@@ -160,7 +159,6 @@ public sealed class OwnershipFilter : Filter
}
/// <summary>Generic numeric comparison against a named unit property.</summary>
[PolyType(typeof(UnitPropertyFilter), "UnitProperty")]
public sealed class UnitPropertyFilter : Filter
{
/// <summary>
@@ -177,7 +175,6 @@ public sealed class UnitPropertyFilter : Filter
/// Tile must be occupied by a unit of the given type and ownership.
/// Use instead of <see cref="TileIsOccupiedFilter"/> when ownership matters.
/// </summary>
[PolyType(typeof(TileOccupancyFilter), "TileOccupancy")]
public sealed class TileOccupancyFilter : Filter
{
/// <summary>"Spirit" | "ArchSpirit" | "SpiritToken" | "Ruin" | "Unit" (any)</summary>
@@ -31,6 +31,13 @@ public sealed class PendingTargetPick
/// </summary>
public string ActionJson { get; set; } = "{}";
/// <summary>
/// JSON array of candidate cards ({instanceId, name, cardType}) for zone-scope picks
/// (Hand/Deck/Discard/AnyZone), where the client cannot enumerate the pool itself.
/// Null for battlefield picks — the client resolves those from visible board state.
/// </summary>
public string? CandidatesJson { get; set; }
/// <summary>JSON-serialized Action[] — remaining actions to execute after this one resolves.</summary>
public string ContinuationActionsJson { get; set; } = "[]";
+6 -1
View File
@@ -1044,7 +1044,12 @@ public sealed record TargetPickRequestPush(
/// <summary>JSON-serialized Action — full selector for client highlight logic.</summary>
string ActionJson,
/// <summary>JSON-serialized AbilityRange? — null when no range constraint.</summary>
string? RangeJson);
string? RangeJson,
/// <summary>
/// JSON array of candidate cards ({instanceId, name, cardType}) for zone-scope picks.
/// Null for battlefield picks (client resolves those from visible board state).
/// </summary>
string? CandidatesJson = null);
/// <summary>
/// Pushed to the chooser when an effect requires a tile selection.
@@ -479,7 +479,8 @@ internal abstract class GameHandlerBase
ttp.RequestId,
ttp.SourceInstanceId,
ttp.ActionJson,
ttp.RangeJson)), ct);
ttp.RangeJson,
ttp.CandidatesJson)), ct);
}
if (state.PendingTilePick is { } tp)
@@ -0,0 +1,579 @@
namespace SOR.Game.Tests;
using SOR.Database.Enums;
using SOR.Game;
using SOR.Game.Abilities;
using SOR.Game.Grid;
using Xunit;
/// <summary>
/// Regression tests for the ability-system fixes documented in
/// SOR.Abilities-Review-and-solutions.md. Each test targets a scenario that was
/// broken before the 2026-07-02 remediation (tests 1–5 of the doc's §8 test plan).
/// </summary>
public sealed class AbilitySystemRegressionTests
{
private const string P1 = "11111111-1111-1111-1111-111111111111";
private const string P2 = "22222222-2222-2222-2222-222222222222";
private const string P3 = "33333333-3333-3333-3333-333333333333";
// ── Fixture helpers ───────────────────────────────────────────────────────
private static GameState NewState(params (string accountId, int teamIndex)[] players)
{
var state = new GameState
{
SessionId = Guid.NewGuid(),
Phase = GamePhase.Main,
TurnNumber = 3,
Board = Board.Create(6, 6),
ActivePlayerAccountId = players[0].accountId,
PlayerOneAccountId = players[0].accountId,
};
foreach (var (id, team) in players)
state.Players[id] = new PlayerState
{
AccountId = id,
TeamIndex = team,
CurrentSp = 10,
CurrentSt = 10,
};
return state;
}
private static FieldCard PlaceSpirit(
GameState state, string ownerId, int x, int y,
string? abilitiesJson = null, string cardType = "Spirit",
int hp = 10, int damage = 2)
{
var fc = new FieldCard
{
Name = $"{cardType}@{x},{y}",
CardType = cardType,
MaxHealth = hp,
CurrentHealth = hp,
MaxDefense = 0,
CurrentDefense = 0,
Damage = damage,
AbilitiesJson = abilitiesJson,
Position = new Coord(x, y),
IsLeader = cardType == "ArchSpirit",
};
var player = state.Players[ownerId];
if (cardType == "ArchSpirit") player.ArchSpirit = fc;
else player.Field.Add(fc);
state.Board!.PlaceUnit(new Coord(x, y), fc.InstanceId, ownerId);
return fc;
}
private static CardInstance NewCard(string name = "Card", string cardType = "Spirit")
=> new() { Name = name, CardType = cardType };
// ── §8 Test 1 — Passive authored as ActionGroup (builder shape) applies ──
[Fact]
public void Passive_AuthoredWithActionGroup_AppliesAndRevokes()
{
// Builder-shaped JSON: ActionGroup only, empty legacy Actions.
const string abilities = """
[{
"Type": "Passive",
"Name": "War Cry",
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": {
"Scope": "Battlefield", "Type": "Unit", "Ownership": "ExactSelf",
"Chooser": "Self", "Count": { "N": 1, "UpTo": false, "All": false }
},
"Effects": [ { "$type": "ModifyDamage", "Amount": { "Fixed": 2 } } ]
}],
"Groups": []
}
}]
""";
var state = NewState((P1, 0), (P2, 1));
var unit = PlaceSpirit(state, P1, 1, 1, abilities, damage: 2);
AbilitySystem.ApplyPassivesForSource(state, unit.InstanceId, P1);
Assert.Equal(4, unit.Damage); // +2 applied
Assert.Single(state.ActiveEffects); // reversal tracked
AbilitySystem.RevokePassivesForSource(state, unit.InstanceId);
Assert.Equal(2, unit.Damage); // reverted
Assert.Empty(state.ActiveEffects);
}
// ── §8 Test 2 — ArchSpirit triggered ability fires ────────────────────────
[Fact]
public void ArchSpirit_TriggeredAbility_FiresOnTurnStart()
{
const string abilities = """
[{
"Type": "Triggered",
"Name": "Dawn Draw",
"TriggerEvent": { "$type": "OnTurnStart", "Player": "Owner" },
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": { "Scope": "Player", "Type": "Player", "Ownership": "Owner", "Count": { "N": 1 } },
"Effects": [ { "$type": "DrawCards", "N": 1, "Player": "Owner" } ]
}],
"Groups": []
}
}]
""";
var state = NewState((P1, 0), (P2, 1));
PlaceSpirit(state, P1, 0, 0, abilities, cardType: "ArchSpirit", hp: 20);
state.Players[P1].Deck.Add(NewCard("Top"));
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.TurnStart,
ActorId = P1,
});
Assert.Single(state.Players[P1].Hand);
Assert.Empty(state.Players[P1].Deck);
}
// ── §8 Test 4 — Triggered ability with pick action at index 1 ────────────
[Fact]
public void TriggeredAbility_PickActionAtIndexOne_ResolvesWithOriginalIndex()
{
const string abilities = """
[{
"Type": "Triggered",
"Name": "Snipe",
"TriggerEvent": { "$type": "OnTurnStart", "Player": "Owner" },
"ActionGroup": {
"LogicOp": "And",
"Actions": [
{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "ExactSelf", "Count": { "N": 1 } },
"Effects": [ { "$type": "ModifyDamage", "Amount": { "Fixed": 1 } } ]
},
{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } },
"Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 3 }, "BypassDefense": true } ]
}
],
"Groups": []
}
}]
""";
var state = NewState((P1, 0), (P2, 1));
var source = PlaceSpirit(state, P1, 1, 1, abilities, damage: 2);
var enemy = PlaceSpirit(state, P2, 4, 4, hp: 10);
AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.TurnStart,
ActorId = P1,
});
// The Enemy-target action (index 1) needs a human pick — engine must pause.
var pending = state.PendingTriggeredTarget;
Assert.NotNull(pending);
// Client submits the pick with the ORIGINAL action index (1). Before the fix
// the prompt only carried the pick action and the resume threw INSUFFICIENT_TARGETS.
AbilitySystem.ResumeTriggeredAbility(state, P1, pending!.RequestId,
[new AbilityTarget(1, enemy.InstanceId)]);
Assert.Equal(3, source.Damage); // action 0 auto-resolved (+1)
Assert.Equal(7, enemy.CurrentHealth); // action 1 hit the picked enemy (-3)
Assert.Null(state.PendingTriggeredTarget);
}
// ── PreventDeath options (DamageIgnored) ─────────────────────────────────
[Fact]
public void PreventDeath_DamageIgnored_CancelsLethalHitAndConsumesMarker()
{
const string abilities = """
[{
"Type": "Active",
"Name": "Smite",
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } },
"Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 99 }, "BypassDefense": true } ]
}],
"Groups": []
}
}]
""";
var state = NewState((P1, 0), (P2, 1));
var target = PlaceSpirit(state, P2, 4, 4, hp: 10);
var card = NewCard("Repentance of Smiting", "Repentance");
card.AbilitiesJson = abilities;
state.Players[P1].Discard.Add(card); // channel flow discards before firing
state.PreventDeathMarkers[target.InstanceId] = new PreventDeathMarker { DamageIgnored = true };
AbilitySystem.FireCardEffects(state, P1, card,
[new AbilityTarget(0, target.InstanceId)]);
Assert.Equal(10, target.CurrentHealth); // hit fully ignored
Assert.False(state.PreventDeathMarkers.ContainsKey(target.InstanceId)); // marker consumed
Assert.Contains(state.Players[P2].Field, f => f.InstanceId == target.InstanceId);
}
[Fact]
public void PreventDeath_SetHpOption_SurvivesAtConfiguredHp()
{
const string abilities = """
[{
"Type": "Active",
"Name": "Smite",
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } },
"Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 99 }, "BypassDefense": true } ]
}],
"Groups": []
}
}]
""";
var state = NewState((P1, 0), (P2, 1));
var target = PlaceSpirit(state, P2, 4, 4, hp: 10);
var card = NewCard("Repentance of Smiting", "Repentance");
card.AbilitiesJson = abilities;
state.Players[P1].Discard.Add(card);
state.PreventDeathMarkers[target.InstanceId] =
new PreventDeathMarker { DamageTakenSetToHp = 3 };
AbilitySystem.FireCardEffects(state, P1, card,
[new AbilityTarget(0, target.InstanceId)]);
Assert.Equal(3, target.CurrentHealth); // saved at the configured HP
Assert.Contains(state.Players[P2].Field, f => f.InstanceId == target.InstanceId);
}
// ── Team-aware Enemy targeting ────────────────────────────────────────────
[Fact]
public void EnemyTargeting_ExcludesTeammates()
{
const string abilities = """
[{
"Type": "Active",
"Name": "Nova",
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy",
"Count": { "N": 1, "All": true } },
"Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 1 }, "BypassDefense": true } ]
}],
"Groups": []
}
}]
""";
// P1 + P2 are teammates (team 0); P3 is the enemy (team 1).
var state = NewState((P1, 0), (P2, 0), (P3, 1));
var teammate = PlaceSpirit(state, P2, 2, 2, hp: 10);
var enemy = PlaceSpirit(state, P3, 4, 4, hp: 10);
var card = NewCard("Nova Repentance", "Repentance");
card.AbilitiesJson = abilities;
state.Players[P1].Discard.Add(card);
AbilitySystem.FireCardEffects(state, P1, card, clientTargets: null);
Assert.Equal(10, teammate.CurrentHealth); // ally untouched
Assert.Equal(9, enemy.CurrentHealth); // enemy hit
}
// ── DOT ticks once per round, not per player-turn ─────────────────────────
[Fact]
public void DotTick_OnlyFiresOnApplyingPlayersTurnEnd()
{
var state = NewState((P1, 0), (P2, 1));
var target = PlaceSpirit(state, P2, 4, 4, hp: 10);
state.ActiveEffects.Add(new ActiveEffect
{
SourceInstanceId = "src",
TargetRef = target.InstanceId,
EffectJson = """{ "$type": "DealDamage", "Amount": { "Fixed": 2 }, "BypassDefense": true }""",
DurationJson = $$"""{ "Duration": { "Type": "ForNTurns", "N": 3 }, "OwnerAccountId": "{{P1}}", "IsTick": true }""",
TurnsRemaining = 3,
});
AbilitySystem.TickActiveEffects(state, P2); // not the applier's turn — no tick
Assert.Equal(10, target.CurrentHealth);
AbilitySystem.TickActiveEffects(state, P1); // applier's turn — tick once
Assert.Equal(8, target.CurrentHealth);
}
// ── Parse hardening ───────────────────────────────────────────────────────
[Fact]
public void ParseAbilities_MalformedJson_ReturnsEmptyInsteadOfThrowing()
{
// "Base" is not a valid StatTarget enum value — previously poisoned the card.
const string malformed = """
[{
"Type": "Passive",
"ActionGroup": { "LogicOp": "And", "Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "ExactSelf", "Count": { "N": 1 } },
"Effects": [ { "$type": "ModifyHealth", "Amount": { "Fixed": 1 }, "StatTarget": "Base" } ]
}], "Groups": [] }
}]
""";
var defs = AbilitySystem.ParseAbilities(malformed);
Assert.Empty(defs);
// And a card carrying malformed JSON must not break trigger scans.
var state = NewState((P1, 0), (P2, 1));
PlaceSpirit(state, P1, 1, 1, malformed);
var ex = Record.Exception(() => AbilitySystem.FireTrigger(state, new TriggerOccurrence
{
Kind = TriggerEventKind.TurnStart,
ActorId = P1,
}));
Assert.Null(ex);
}
// ── Trigger limits live on GameState and survive round-trips ─────────────
[Fact]
public void TriggerLimitPerTurn_EnforcedViaGameState()
{
const string abilities = """
[{
"Type": "Triggered",
"Name": "Once Only",
"TriggerLimitPerTurn": 1,
"TriggerEvent": { "$type": "OnCardDrawn", "Player": "Owner" },
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": { "Scope": "Player", "Type": "Player", "Ownership": "Owner", "Count": { "N": 1 } },
"Effects": [ { "$type": "ModifySP", "Amount": { "Fixed": 1 } } ]
}],
"Groups": []
}
}]
""";
var state = NewState((P1, 0), (P2, 1));
PlaceSpirit(state, P1, 1, 1, abilities);
var occ = new TriggerOccurrence { Kind = TriggerEventKind.CardDrawn, ActorId = P1 };
AbilitySystem.FireTrigger(state, occ);
AbilitySystem.FireTrigger(state, occ);
Assert.Equal(11, state.Players[P1].CurrentSp); // fired exactly once
Assert.Single(state.TriggerUsesThisTurn); // counter lives on the state
}
// ── TakeControl: duration-tracked, board-synced, reversed on expiry ───────
[Fact]
public void TakeControl_ReturnsUnitToOriginalOwnerWhenDurationExpires()
{
const string abilities = """
[{
"Type": "Active",
"Name": "Dominate",
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } },
"Effects": [ { "$type": "TakeControl", "Duration": { "Type": "UntilEndOfTurn" } } ]
}],
"Groups": []
}
}]
""";
var state = NewState((P1, 0), (P2, 1));
var victim = PlaceSpirit(state, P2, 4, 4, hp: 10);
var card = NewCard("Dominate", "Instinct");
card.AbilitiesJson = abilities;
state.Players[P1].Discard.Add(card);
AbilitySystem.FireCardEffects(state, P1, card,
[new AbilityTarget(0, victim.InstanceId)]);
Assert.Contains(state.Players[P1].Field, f => f.InstanceId == victim.InstanceId);
Assert.DoesNotContain(state.Players[P2].Field, f => f.InstanceId == victim.InstanceId);
Assert.Equal(P1, state.Board!.GetTile(new Coord(4, 4))!.OccupantOwner);
Assert.Single(state.ActiveEffects); // return-control reversal tracked
// End of turn: control returns to the original owner, board included.
AbilitySystem.ExpireActiveEffects(state, P1, isEndOfTurn: true);
Assert.Contains(state.Players[P2].Field, f => f.InstanceId == victim.InstanceId);
Assert.DoesNotContain(state.Players[P1].Field, f => f.InstanceId == victim.InstanceId);
Assert.Equal(P2, state.Board!.GetTile(new Coord(4, 4))!.OccupantOwner);
Assert.Empty(state.ActiveEffects);
}
// ── UntilStartOfSourceOwnerTurn anchors to the source unit's owner ────────
[Fact]
public void UntilStartOfSourceOwnerTurn_ExpiresOnSourceOwnersTurnNotActors()
{
var state = NewState((P1, 0), (P2, 1));
var unit = PlaceSpirit(state, P1, 1, 1, damage: 4); // buffed to 4; reversal -2
state.ActiveEffects.Add(new ActiveEffect
{
SourceInstanceId = "src",
TargetRef = unit.InstanceId,
EffectJson = """{ "$type": "ModifyDamage", "Amount": { "Fixed": -2 } }""",
DurationJson = $$"""
{ "Duration": { "Type": "UntilStartOfSourceOwnerTurn" },
"OwnerAccountId": "{{P1}}", "SourceOwnerAccountId": "{{P2}}" }
""",
});
// Actor's (P1) turn start: must NOT expire — the anchor is the source owner (P2).
AbilitySystem.ExpireActiveEffects(state, P1, isEndOfTurn: false);
Assert.Equal(4, unit.Damage);
Assert.Single(state.ActiveEffects);
// Source owner's (P2) turn start: expires and reverts.
AbilitySystem.ExpireActiveEffects(state, P2, isEndOfTurn: false);
Assert.Equal(2, unit.Damage);
Assert.Empty(state.ActiveEffects);
}
// ── Zone-scope card picks pause with a server-enumerated candidates list ──
[Fact]
public void ZoneScopeCardPick_PausesWithCandidates_ThenResumesWithCardIds()
{
const string abilities = """
[{
"Type": "Active",
"Name": "Pilfer",
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": { "Scope": "Hand", "Type": "Card", "Ownership": "Enemy", "Count": { "N": 1 } },
"Effects": [ { "$type": "SendToDiscard" } ]
}],
"Groups": []
}
}]
""";
var state = NewState((P1, 0), (P2, 1));
var source = PlaceSpirit(state, P1, 1, 1, abilities);
var cardA = NewCard("A");
var cardB = NewCard("B");
state.Players[P2].Hand.AddRange([cardA, cardB]);
// The client can only submit the target PLAYER's accountId for hidden zones.
AbilitySystem.ActivateAbility(state, P1, source.InstanceId, 0,
[new AbilityTarget(0, P2)]);
var pending = state.PendingTargetPick;
Assert.NotNull(pending);
Assert.NotNull(pending!.CandidatesJson);
Assert.Contains(cardA.InstanceId, pending.CandidatesJson);
Assert.Contains(cardB.InstanceId, pending.CandidatesJson);
// The chooser picks a real card; the paused action is replayed at index 0.
AbilitySystem.ResumeTargetPick(state, P1, pending.RequestId,
[new AbilityTarget(0, cardA.InstanceId)]);
Assert.Contains(cardA, state.Players[P2].Discard);
Assert.DoesNotContain(cardA, state.Players[P2].Hand);
Assert.Contains(cardB, state.Players[P2].Hand);
Assert.Null(state.PendingTargetPick);
}
// ── Missing mandatory targets prompt instead of throwing ─────────────────
[Fact]
public void MissingMandatoryTargets_PromptInsteadOfInsufficientTargets()
{
const string abilities = """
[{
"Type": "Active",
"Name": "Zap",
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } },
"Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 2 }, "BypassDefense": true } ]
}],
"Groups": []
}
}]
""";
var state = NewState((P1, 0), (P2, 1));
var source = PlaceSpirit(state, P1, 1, 1, abilities);
var enemy = PlaceSpirit(state, P2, 4, 4, hp: 10);
// No targets submitted (e.g. after an OR-group Random pick shifted indices).
AbilitySystem.ActivateAbility(state, P1, source.InstanceId, 0, clientTargets: null);
var pending = state.PendingTargetPick;
Assert.NotNull(pending); // prompt, not INSUFFICIENT_TARGETS
Assert.Null(pending!.CandidatesJson); // battlefield pick — client resolves visually
AbilitySystem.ResumeTargetPick(state, P1, pending.RequestId,
[new AbilityTarget(0, enemy.InstanceId)]);
Assert.Equal(8, enemy.CurrentHealth);
Assert.Null(state.PendingTargetPick);
}
// ── PreventNextDamage shield lives on GameState ───────────────────────────
[Fact]
public void PreventNextDamage_ShieldAbsorbsViaGameState()
{
const string abilities = """
[{
"Type": "Active",
"Name": "Bolt",
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } },
"Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 5 }, "BypassDefense": true } ]
}],
"Groups": []
}
}]
""";
var state = NewState((P1, 0), (P2, 1));
var target = PlaceSpirit(state, P2, 4, 4, hp: 10);
var card = NewCard("Bolt", "Instinct");
card.AbilitiesJson = abilities;
state.Players[P1].Discard.Add(card);
state.PreventNextDamageByUnit[target.InstanceId] = 3; // absorb up to 3
AbilitySystem.FireCardEffects(state, P1, card,
[new AbilityTarget(0, target.InstanceId)]);
Assert.Equal(8, target.CurrentHealth); // 5 - 3 absorbed = 2 through
Assert.False(state.PreventNextDamageByUnit.ContainsKey(target.InstanceId));
}
}
@@ -0,0 +1,134 @@
namespace SOR.Game.Tests;
using SOR.Game.Abilities;
using Xunit;
/// <summary>
/// Tests for the save-time ability validation used by the admin CardEditor.
/// </summary>
public sealed class AbilityValidatorTests
{
private const string ValidActive = """
[{
"Type": "Active",
"Name": "Bolt",
"ActionGroup": {
"LogicOp": "And",
"Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } },
"Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 3 } } ]
}],
"Groups": []
}
}]
""";
[Fact]
public void ValidAbility_PassesForUnitAndEffectCards()
{
Assert.Empty(AbilityValidator.Validate(ValidActive, "Spirit"));
Assert.Empty(AbilityValidator.Validate(ValidActive, "Repentance"));
Assert.Empty(AbilityValidator.Validate(null, "Spirit"));
Assert.Empty(AbilityValidator.Validate("", "Spirit"));
}
[Fact]
public void UnparseableJson_IsRejected()
{
const string badEnum = """
[{ "Type": "Passive", "ActionGroup": { "LogicOp": "And", "Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "ExactSelf", "Count": { "N": 1 } },
"Effects": [ { "$type": "ModifyHealth", "Amount": { "Fixed": 1 }, "StatTarget": "Base" } ]
}], "Groups": [] } }]
""";
var errors = AbilityValidator.Validate(badEnum, "Spirit");
Assert.Single(errors);
Assert.Contains("deserialize", errors[0]);
}
[Fact]
public void UnimplementedTrigger_IsRejected()
{
const string json = """
[{
"Type": "Triggered",
"Name": "Dead Trigger",
"TriggerEvent": { "$type": "OnStatModified", "Ownership": "Any" },
"ActionGroup": { "LogicOp": "And", "Actions": [], "Groups": [] }
}]
""";
var errors = AbilityValidator.Validate(json, "Spirit");
Assert.Contains(errors, e => e.Contains("never fire"));
}
[Fact]
public void TriggeredWithoutEvent_IsRejected()
{
const string json = """
[{ "Type": "Triggered", "Name": "Empty", "ActionGroup": { "LogicOp": "And", "Actions": [], "Groups": [] } }]
""";
var errors = AbilityValidator.Validate(json, "Spirit");
Assert.Contains(errors, e => e.Contains("no TriggerEvent"));
}
[Fact]
public void UnimplementedEffect_IsRejected()
{
const string json = """
[{
"Type": "Active",
"Name": "NoOp",
"ActionGroup": { "LogicOp": "And", "Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } },
"Effects": [ { "$type": "ChannelCard", "PayCost": true } ]
}], "Groups": [] }
}]
""";
var errors = AbilityValidator.Validate(json, "Spirit");
Assert.Contains(errors, e => e.Contains("no engine implementation"));
}
[Fact]
public void EffectCard_RangeAndNonActive_AreRejected()
{
const string json = """
[{
"Type": "Active",
"Name": "Ranged Smite",
"Range": { "Min": 1, "Max": 2 },
"ActionGroup": { "LogicOp": "And", "Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } },
"Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 1 } } ]
}], "Groups": [] }
},
{
"Type": "Passive",
"Name": "Never Runs",
"ActionGroup": { "LogicOp": "And", "Actions": [], "Groups": [] }
}]
""";
var errors = AbilityValidator.Validate(json, "Repentance");
Assert.Contains(errors, e => e.Contains("Remove the Range"));
Assert.Contains(errors, e => e.Contains("only Active abilities execute"));
// The same definitions are fine on a battlefield unit.
Assert.Empty(AbilityValidator.Validate(json, "Spirit"));
}
[Fact]
public void PassiveWithOrGroup_IsRejected()
{
const string json = """
[{
"Type": "Passive",
"Name": "Choose Buff",
"ActionGroup": { "LogicOp": "Or", "ChooserRole": "Self", "Actions": [{
"Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "ExactSelf", "Count": { "N": 1 } },
"Effects": [ { "$type": "ModifyDamage", "Amount": { "Fixed": 1 } } ]
}], "Groups": [] }
}]
""";
var errors = AbilityValidator.Validate(json, "Spirit");
Assert.Contains(errors, e => e.Contains("OR/XOR"));
}
}
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\SOR.Game\SOR.Game.csproj" />
</ItemGroup>
</Project>