From 8f3911e8816b6b49ade299d4ebc0acf0bea6d98a Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 18 Apr 2026 20:15:13 -0400 Subject: [PATCH] feat(ability): implement AbilityBuilderR3 + engine additions Engine: - AbilityDefinition: add SourceZoneGate (zone-restricted triggers) and TriggerLimitPerGame - Effects: add StatModOperator (Add/Subtract/Multiply/Divide/Percent) on all stat mod effects; reversal stored as delta - Action/CostEntry: add CostPickMode enum (Random/SelfPick/EnemySeePick/EnemyRandomPick/EnemyPick) - PendingCostPick: new model for interactive cost pause/resume (mirrors PendingTriggeredTarget) - GameState: PendingCostPick field - GameMessages: CostPickRequestPush, GameCostPickRequest, GameCostPickResponse records - AbilitySystem: FireTrigger scans Hand/Discard/Deck when SourceZoneGate set; per-game trigger limit tracking; ApplyStatOperator helper; PayCosts/ResumeCostPick for interactive cost flow - GameCostPickHandler + ServiceRegistration wiring Admin: - AbilityBuilderR3.razor: full ability builder at /cards/ability-builder-r3 (39 triggers, 69 effects, 32 conditions, form/canvas/mermaid modes, compiles to engine-native $type JSON) - AbilityBuilderR2-Draft.razor: fix switch expression no-best-type error Docs: - BuilderR3.md: master plan document Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- BuilderR3.md | 1064 +++++++++ Client/origin-client/autoloads/Chat.gd | 38 + .../components/deck_editor_panel.gd | 3 + .../components/rules_editor_dialog.gd | 2 +- .../scenes/free_play/free_play_screen.gd | 4 +- .../scenes/free_play/lobby_room_screen.gd | 2 + .../origin-client/scenes/game/game_screen.gd | 57 +- .../origin-client/scenes/main/main_screen.gd | 4 +- .../Components/Pages/Ai/AiMatchPage.razor | 2 +- .../Pages/Cards/AbilityBuilderR2-Draft.razor | 1517 ++++++++++++ .../Pages/Cards/AbilityBuilderR3.razor | 2042 +++++++++++++++++ .../src/SOR.Game/Abilities/AbilitySystem.cs | 468 +++- .../Abilities/Models/AbilityDefinition.cs | 16 +- .../src/SOR.Game/Abilities/Models/Action.cs | 30 +- .../src/SOR.Game/Abilities/Models/Effects.cs | 21 +- .../Abilities/Models/PendingCostPick.cs | 53 + Server/src/SOR.Game/GameMessages.cs | 31 + Server/src/SOR.Game/GameState.cs | 7 + .../SOR.Game/Handlers/GameCostPickHandler.cs | 59 + Server/src/SOR.Game/ServiceRegistration.cs | 3 + 20 files changed, 5290 insertions(+), 133 deletions(-) create mode 100644 BuilderR3.md create mode 100644 Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilderR2-Draft.razor create mode 100644 Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilderR3.razor create mode 100644 Server/src/SOR.Game/Abilities/Models/PendingCostPick.cs create mode 100644 Server/src/SOR.Game/Handlers/GameCostPickHandler.cs diff --git a/BuilderR3.md b/BuilderR3.md new file mode 100644 index 0000000..ba61981 --- /dev/null +++ b/BuilderR3.md @@ -0,0 +1,1064 @@ +# BuilderR3 — Master Plan: New Card Flow + Ability Builder + +**Synthesized from:** BuilderR2.md · AbilityBuilderR2-Draft.razor assessment · long-form design spec +**Scope:** SOR.Admin UI authoring pipeline only. Engine runtime internals out of scope. +**Date:** 2026-04-16 + +--- + +## 0) Vision Statement + +> Design abilities the way you think about them — grab pieces, connect them, see the flow. +> The canvas **is** the JSON. The English description **is** the JSON. The form **is** the JSON. +> Three surfaces, one output, zero ambiguity. + +The ideal experience: +1. Fill in a card's core details (name, type, affinity, stats). +2. Open the Ability Builder — a canvas of **typed bubble nodes** you drag, drop, and connect. +3. Wire: `Trigger` → `Condition Group` → `Cost Group` → `Action Group` → `Effects`. +4. The canvas re-renders in real time as a flowchart **that is the ability**. +5. Hit Validate. Hit Save. The canonical JSON block is emitted — exactly what the AbilitySystem parses. + +Mobile fallback: a progressive-disclosure form that maps one-to-one to the same canonical model. +Power user add-on: plain-English description → AI maps it to draft nodes → designer confirms. + +--- + +## 1) Architecture + +### 1.1 Three authoring surfaces, one model + +``` +Form Editor ──┐ +Visual Editor ──┼──► AbilityDefinitionDraftR3 ──► Canonical JSON ──► AbilitySystem +English/AI ────┘ (single source of truth) +``` + +All three surfaces read from and write to `AbilityDefinitionDraftR3`. +No surface has its own persistence format. +Saving always goes through: Draft → Validate → Canonical JSON → DB. + +### 1.2 Visual Editor ("Bubble Canvas") + +The primary design goal for the ability builder is a **node-and-wire canvas** where: + +- Each structural piece (Trigger, Condition Group, Cost Group, Action Group, Effect) is a **bubble node**. +- Nodes have typed **output ports** (e.g., a Trigger node has a `→ when active` port). +- Connecting a port to another node creates the structural relationship in the draft model. +- Invalid connections are **blocked at the UI level** (port types don't match). +- The rendered connection graph IS the ability flowchart — no separate diagram step needed. +- Sidebar: selected node shows its property form. +- Read-only JSON panel: always reflects current canonical output. + +Visual mode is desktop-first. Mobile falls back to Form mode automatically. + +### 1.3 Form Editor + +Progressive-disclosure form, mobile-first: +- Step 1: Common fields (Name, Description, Type, Limits, Presentation). +- Step 2: Type section (Active / Triggered / Passive / Aura). +- Step 3: Activation Conditions. +- Step 4: Costs (Active only). +- Step 5: Actions and Effects. +- Step 6: Validate + Preview + Save. + +Each step is collapsible. Errors are sticky at the bottom. + +### 1.4 English / AI Surface + +1. Designer types plain-English intent. +2. AI assistant produces a structured draft + confidence score + unresolved slots. +3. Draft is loaded into Visual or Form editor for designer review. +4. Unresolved slots are explicit `TODO` placeholders — never silently defaulted. +5. Save is only available after all TODOs are resolved and validation passes. +6. A diff panel shows AI-generated vs confirmed fields. + +--- + +## 2) Canonical Data Model — `AbilityDefinitionDraftR3` + +This is the single in-memory representation all surfaces write to. + +```csharp +sealed class AbilityDefinitionDraftR3 +{ + // --- Common --- + string Name; + string Description; + string Type; // Active | Triggered | Passive | Aura + LimitsDraft Limits; + PresentationDraft Presentation; + LogicGroupDraft ActivationConditions; + + // --- Type sections (only one populated per ability) --- + ActiveDraft? Active; + TriggeredDraft? Triggered; + PassiveDraft? Passive; + AuraDraft? Aura; + + // --- Costs (Active only; may appear on Triggered via spec extension) --- + CostGroupDraft Costs; + + // --- Actions --- + ActionGroupDraft Actions; +} + +sealed class LimitsDraft +{ + int? PerTurn; + int? PerGame; +} + +sealed class PresentationDraft +{ + string? Animation; + string? AnimationAsset; + string? CastSfx; + string? ImpactSfx; +} +``` + +### 2.1 Active section + +```csharp +sealed class ActiveDraft +{ + int RangeMin; + int RangeMax; + bool RequiresLos; + bool LinearOnly; + int? UsesPerTurn; +} +``` + +### 2.2 Triggered section + +```csharp +sealed class TriggeredDraft +{ + string EventFamily; // see §5 trigger catalog + string EventType; // canonical event key + string LimitMode; // Unlimited | PerTurn | PerGame + int? LimitAmount; + List SourceZoneGate; // Battlefield | Hand | Discard | Deck (multi-select) + string OwnershipScope; // Any | Self | Ally | Opponent + string? AmountComparator; // > | == | < | != | <= | >= + int? Amount; + List Filters; +} +``` + +### 2.3 Passive section + +```csharp +sealed class PassiveDraft +{ + string ContinuousScope; // Global | Battlefield | Zone | Self + string RecheckCadence; // OnAnyEvent | OnTurnStart | OnTurnEnd | Manual + string SourceLeavePolicy; // Remove | Linger | Keep +} +``` + +### 2.4 Aura section + +```csharp +sealed class AuraDraft +{ + int RangeMin; + int RangeMax; + string? EnterHook; // ability key to trigger on enter + string? LeaveHook; // ability key to trigger on leave + string LeavePolicy; // Remove | Linger + int? LingerDuration; +} +``` + +### 2.5 Logic group (conditions, nested) + +```csharp +sealed class LogicGroupDraft +{ + string Logic = "AND"; // AND | OR | XOR + List Rules; + List Groups; // max depth: 3 +} + +sealed class ConditionRuleDraft +{ + string Domain; // see §6 condition domains + string Field; + string Comparator; // > | == | < | != | <= | >= + string Value; +} +``` + +### 2.6 Cost group + +```csharp +sealed class CostGroupDraft +{ + string Logic = "AND"; // AND | OR (alternatives) + List Costs; + List Groups; +} + +sealed class CostDraft +{ + string Type; // see §7 cost catalog + int? Amount; + string? PickMode; // Random | SelfPick | EnemySeePick | EnemyRandomPick | EnemyPick + string? Chooser; // Self | Opponent | Random +} +``` + +### 2.7 Action group + +```csharp +sealed class ActionGroupDraft +{ + string Logic = "AND"; // AND | OR | XOR + string? ChooserAuthority; // Self | Opponent | Random | System (OR/XOR only) + List Actions; + List Groups; +} + +sealed class ActionDraft +{ + string Scope; // see §8 scope catalog + string TargetType; + string Chooser; // Self | Opponent | Random | System + int? Count; + bool All; + List Filters; + LogicGroupDraft Conditions; + List Effects; +} +``` + +### 2.8 Typed filter + +```csharp +sealed class TypedFilterDraft +{ + string Type; // filter category key + string Field; // specific field within type + string Comparator; // > | == | < | != | <= | >= + string Value; + string? ParameterKey; // for parameterized filters + string? ParameterValue; +} +``` + +### 2.9 Effect + +```csharp +sealed class EffectDraft +{ + string Type; // canonical effect key — see §9 effect catalog + int? Amount; + string? AmountSource; // value expression: "Target.Damage", "Self.Health", etc. + string? DurationMode; // Permanent | Turns | UntilEndOfTurn | UntilNextTurn + int? DurationN; + string? ParameterKey; + string? ParameterValue; + + // Stat modification (for stat mod effects) + string? StatModOperator; // Add | Subtract | Multiply | Divide | Percent + + // Zone movement metadata + string? ZonePosition; // Top | Bottom | Random + bool ResetToDefinition; +} +``` + +--- + +## 3) Card Creation Wizard — New Card Flow R3 + +### 3.1 Step overview + +| Step | Name | Content | +|------|------|---------| +| 1 | Core | Name, CardType, Affinity, Description, art preview, SP cost, ST cost | +| 2 | Type-Specific | Stats, movement, genus tags, ArchSpirit channel/tier settings | +| 3 | Flags & Constraints | Can-booleans, LOS requirements | +| 4 | Abilities | Add/edit/reorder abilities (opens Ability Builder per ability) | +| 5 | Review + Save | Human-readable summary, canonical JSON preview, validation panel | + +### 3.2 Step 1 — Core + +- **Name** (required) +- **CardType**: Spirit | ArchSpirit | SpiritToken | Ruin | Instinct | Repentance | Terramorpha +- **Affinity**: Fire | Water | Earth | Air | Void | Neutral (+ multi-affinity support) +- **Description** (flavor/rules text) +- **Art preview** (asset path or upload) +- **SP Cost** (int ≥ 0) +- **ST Cost** (int ≥ 0) + +### 3.3 Step 2 — Type-Specific + +**Spirit and ArchSpirit additional fields:** + +| Field | Type | Notes | +|-------|------|-------| +| Attack Type | Melee \| Ranged \| Extensible | | +| Attack Range Min | int | Ranged only | +| Attack Range Max | int | Ranged only | +| Damage | int | | +| Health | int | | +| Defense | int | | +| Movement Type | string | e.g. Walk, Fly, Burrow | +| Movement Points | int | | +| Genus Tags | List\ | autocomplete + create-new | + +**ArchSpirit additional fields:** + +| Field | Type | Notes | +|-------|------|-------| +| Channel Range Min | int | | +| Channel Range Max | int | | +| Tier | int | 1–N | +| Previous Tier Card | CardRef? | required if Tier > 1 — search by name | + +### 3.4 Step 3 — Flags & Constraints + +**Universal booleans:** +- Can Attack +- Can Defend +- Can Be Attacked +- Can Be Blocked +- Can Move +- Can Be Obstructed +- Can Use Ability +- Has LOS Requirement + +**Type-gated booleans:** +- Spirit: Can Be Sacrificed +- Repentance / Instinct: LOS handling mode (selector, not just bool) + +### 3.5 Step 4 — Abilities + +- Ability list with drag-to-reorder. +- `+ Add Ability` opens the Ability Builder (see §4). +- Type gating enforced in the ability type selector: + - Spirit / ArchSpirit / SpiritToken / Ruin → Active | Triggered | Aura | Passive + - Instinct / Repentance → Active | Triggered only +- Instinct / Repentance: default ability name to card name; designer may override. + +### 3.6 Step 5 — Review + Validate + Save + +- Human-readable summary panel: "Spirit 'Emberveil' — 3 abilities — Tier 2 ArchSpirit…" +- Canonical JSON accordion (collapsible per field group). +- Validation panel (see §10). +- Save disabled while blocking errors exist. +- Non-blocking warnings shown with save-anyway option. + +--- + +## 4) Ability Builder — Three-Mode UI + +### 4.1 Common header (all modes) + +- Ability Name, Description, Type selector. +- Limits: Per Turn / Per Game (optional ints). +- Presentation: Animation key, Animation Asset, Cast SFX, Impact SFX. +- Mode switcher: Form | Visual | English (tabs). + +### 4.2 Form Mode — type section routing + +After common fields, route to type-specific section: + +**Active:** +- Range Min / Max +- Requires LOS (bool) +- Linear Only (bool) +- Uses Per Turn (optional int) +- → then Activation Conditions → Costs → Actions + +**Triggered:** +- Trigger Event (family → event picker, see §5) +- Source Zone Gate (multi-select: Battlefield / Hand / Discard / Deck) +- Ownership Scope (Any / Self / Ally / Opponent) +- Trigger Filters (typed, see §5 per-event filter schema) +- Trigger Limits (Unlimited / N per turn / N per game) +- → then Activation Conditions → Actions (no costs on triggered by default) + +**Passive:** +- Continuous Scope (Global / Battlefield / Zone / Self) +- Recheck Cadence (OnAnyEvent / OnTurnStart / OnTurnEnd / Manual) +- Source Leave Policy (Remove / Linger / Keep) +- → then Activation Conditions → Actions + +**Aura:** +- Range Min / Max +- Enter Hook (optional ability key) +- Leave Hook (optional ability key) +- Leave Policy (Remove / Linger) +- Linger Duration (optional int, Linger only) +- → then Activation Conditions → Actions + +### 4.3 Visual Mode — Bubble Canvas + +#### Node palette (left sidebar) + +| Node Type | Color | Ports | +|-----------|-------|-------| +| Trigger | Purple | → when active | +| Condition Group | Blue | ← from trigger/action; → to action/cost | +| Cost Group | Orange | ← from condition; → to action | +| Target Selector | Teal | ← from action; → effects | +| Action Group | Green | ← from cost/trigger; → effects | +| Effect | Red | ← from action | +| Duration/Policy | Grey | ← from effect | + +#### Canvas behaviors +- Drag node from palette → drops onto canvas. +- Drag from output port → hover over compatible input port → release to connect. +- Incompatible port types: connection blocked with a red indicator. +- Click node → property sidebar opens (right panel, replaces JSON view temporarily). +- Connection line labels show logic type (AND / OR / XOR). +- Delete node: `Backspace` or right-click menu. +- Undo/redo: `Ctrl+Z / Ctrl+Y`. + +#### Execution path preview +- When a node is selected, the path from Trigger → Effect is highlighted on the canvas. +- A readable sequence list appears beneath the canvas: "1. When [event] from [zone] → 2. If [condition] → 3. Pay [cost] → 4. Target [N] [type] → 5. Apply [effect]". + +#### JSON sync +- Every canvas edit immediately updates `AbilityDefinitionDraftR3`. +- JSON panel (bottom-right) reflects current canonical output in real time. +- "Decompile from JSON" button: paste existing JSON → re-renders as nodes. + +### 4.4 English / AI Mode + +- Large textarea: "Describe what this ability does in plain English." +- Submit → AI generates draft nodes (confidence 0–1 per slot). +- Low-confidence slots marked yellow; unresolved (null) slots marked red as TODO. +- Designer can accept, edit, or reject each slot inline. +- Diff panel: shows AI-proposed values vs current model. +- "Apply to Canvas" button loads confirmed slots into Visual mode for final wiring. +- Save unavailable until all TODO slots resolved. + +--- + +## 5) Trigger Event Catalog + +### 5.1 Event families and events + +| Family | Events | +|--------|--------| +| **Lifecycle** | TurnStart, TurnEnd, GameStart, GameEnd, ChannelStart, ChannelEnd | +| **Unit — Combat** | AttackDeclared, AttackResolved, BlockDeclared, DefendDeclared, DamageDelt, DamageReceived, HealReceived, DeathOccurred | +| **Unit — Move/Ability** | MoveDeclared, MoveResolved, AbilityActivated, AbilityResolved, AbilityTargeted | +| **Battlefield State** | SpiritEntersBattlefield, SpiritLeavesBattlefield, RuinActivated, RuinDeactivated, TileAffinityChanged, AuraEntered, AuraLeft | +| **Resource Economy** | SpGained, SpSpent, StGained, StSpent | +| **Card Movement** | CardDrawn, CardDiscarded, CardReturned, CardRevealed, CardShuffled, CardSentToZone | +| **Stat / Ability Mutation** | StatModified, AbilityAdded, AbilityRemoved, GenusChanged, AffinityChanged | +| **Ruin / Occupancy** | RuinOccupied, RuinVacated, RuinDestroyed | +| **Token** | TokenCreated, TokenDestroyed, SpiritSacrificed | + +### 5.2 Per-event filter schema + +Every trigger event exposes only the filters valid for that event. Example schemas: + +**DamageDelt / DamageReceived:** +- Ownership: Any | Self | Ally | Opponent +- Source type: Any | Spirit | ArchSpirit | Ability | Ruin +- Amount comparator + value + +**SpiritEntersBattlefield / SpiritLeavesBattlefield:** +- Ownership scope +- Genus match (exact | contains) +- Affinity match + +**CardDrawn / CardDiscarded / CardReturned:** +- Card type filter +- Ownership scope +- Zone source/destination + +**SpGained / SpSpent / StGained / StSpent:** +- Amount comparator + value +- Who: Self | Opponent | Any + +**AbilityActivated / AbilityTargeted:** +- Ownership scope +- Ability type filter +- Target type filter + +**TileAffinityChanged:** +- Affinity before / after +- Ownership of tile occupant + +**AuraEntered / AuraLeft:** +- Aura source ownership +- Entity type entering/leaving + +### 5.3 Trigger limits + +- Unlimited +- N per turn (int input) +- N per game (int input) + +### 5.4 Source zone gate + +Multi-select; at least one required for Triggered abilities. + +| Option | Meaning | +|--------|---------| +| Battlefield | Card must be deployed on the battlefield | +| Hand | Card must be in owner's hand | +| Discard | Card must be in discard pile | +| Deck | Card must be in deck | + +Default for new Triggered abilities: `[Battlefield]`. + +--- + +## 6) Condition System + +### 6.1 Logic structure + +Conditions use nested `LogicGroupDraft` (AND / OR / XOR, max depth 3). +Conditions appear in three places: +1. **Activation conditions** — on the ability itself (when is it legal to use/fire). +2. **Action conditions** — per action (is this action branch taken). +3. **Target conditions** — per filter (does this target qualify). + +### 6.2 Condition domains + +| Domain | Fields Available | +|--------|-----------------| +| **Turn / Timing** | IsMyTurn, IsOpponentTurn, TurnNumber, PhaseType | +| **Unit — Ownership** | Owner (Self/Ally/Opponent/Any), IsAlly, IsEnemy | +| **Unit — Type** | CardType, Genus (contains/exact), Affinity | +| **Unit — Properties** | Damage, Health, Defense, MovementPoints, CurrentHealth, AttackType | +| **This Card** | Name (exact), SP cost, ST cost, HealthRemaining, IsChanneling | +| **This Card Definition — Zone Count** | CountInZone (zone, comparator, amount) | +| **Location — Zone Counts** | HandSize, DeckSize, DiscardSize, BattlefieldCount (by type) | +| **Tile — Occupied** | IsOccupied, OccupantType, OccupantOwner, OccupantGenus | +| **Tile — Surrounding** | AdjacentTileCount (by affinity/occupant), OccupiedNeighborCount | +| **Tile — Affinity** | TileAffinity (matches/contains list) | +| **Player — Resources** | SP, ST, AccumulatedSP, AccumulatedST | +| **Player — Hand/Deck/Discard** | HandSize, DeckSize, DiscardSize, HasCardOfType | +| **Player — Channel State** | HasChanneledThisTurn, ChannelCount | + +### 6.3 Comparators + +`>` | `==` | `<` | `!=` | `<=` | `>=` + +--- + +## 7) Cost System + +### 7.1 Cost group structure + +`CostGroupDraft` is a recursive group with `AND` (all costs required) or `OR` (alternative cost paths). + +### 7.2 Cost type catalog + +| Cost Key | Description | Required Metadata | +|----------|-------------|-------------------| +| `PaySP` | Spend N spirit points | Amount | +| `PayST` | Spend N soul tokens | Amount | +| `DiscardFromHand` | Discard card(s) from hand | Amount, PickMode | +| `SendSpiritFromBattlefieldToDiscard` | Remove own spirit from battlefield | Amount, PickMode | +| `DealDamageToOwnSpirit` | Deal damage to own spirit | Amount, PickMode | +| `SacrificeSpirit` | Sacrifice a spirit permanently | Amount, PickMode | +| `SkipAction` | Forfeit an action this turn | — | +| `ExhaustSpirit` | Exhaust (tap) a spirit | Amount, Chooser | + +### 7.3 Pick mode values + +Required for all costs with `PickMode`: + +| Mode | Description | +|------|-------------| +| `Random` | System picks randomly | +| `SelfPick` | Controlling player picks | +| `EnemySeePick` | Opponent picks (sees options) | +| `EnemyRandomPick` | Opponent picks (random from options) | +| `EnemyPick` | Opponent picks (any method) | + +--- + +## 8) Action and Targeting System + +### 8.1 Action group structure + +`ActionGroupDraft` supports AND / OR / XOR. +OR / XOR require `ChooserAuthority` (Self / Opponent / Random / System). + +### 8.2 Scope catalog + +| Scope | Valid Target Types | +|-------|-------------------| +| `Hand` | AnyCard, ByType, ByName | +| `Deck` | AnyCard, ByType, ByName | +| `Discard` | AnyCard, ByType, ByName | +| `Battlefield` | Spirit, ArchSpirit, SpiritToken, Ruin, Tile | +| `Player` | Self, Ally, Opponent, All, Random | +| `Hand+Deck` | Combined search | +| `Hand+Discard` | Combined search | +| `Battlefield+Hand` | Combined send/recall | + +### 8.3 Chooser values + +`Self` | `Opponent` | `Random` | `System` + +### 8.4 Count options + +- Fixed N (int input) +- All matching targets (`All` flag) + +### 8.5 Target type details by scope + +**Battlefield targets:** + +| Target Type | Notes | +|-------------|-------| +| Spirit | Any spirit unit | +| ArchSpirit | Any arch-spirit | +| SpiritToken | Any spirit token | +| Ruin | Any ruin structure | +| Tile | Grid tile (position-based) | + +**Player targets:** + +| Target | Notes | +|--------|-------| +| Self | Controlling player | +| Ally | Allied player (multiplayer) | +| Opponent | Opposing player | +| All | All players | +| Random | Random player | + +Player targets support additional property filters (SP / ST / hand size / etc.). + +--- + +## 9) Effect Catalog + +Organized by scope. Each effect lists its required and optional parameters. + +### 9.1 Hand / Deck / Discard operations + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `SendToHand` | Move target card(s) to hand | — | +| `SendToDeck` | Move target card(s) to deck | ZonePosition (Top/Bottom/Random) | +| `SendToDiscard` | Move target card(s) to discard | — | +| `ShuffleDeck` | Shuffle target player's deck | — | +| `SearchDeck` | Search deck for card matching filter | FilterType, ZonePosition (where to put result) | +| `StackDeck` | Place specific card on top of deck | — | +| `DrawCards` | Draw N cards | Amount, AmountSource | +| `DiscardCards` | Discard N cards from hand | Amount, PickMode | +| `RevealCard` | Reveal top N cards of deck | Amount | + +### 9.2 Channeling operations + +| Effect Key | Card Type | Description | Params | +|------------|-----------|-------------|--------| +| `ChannelSpirit` | Spirit | Channel target spirit card | IgnoreCost, IgnoreRange, IgnoreAffinity, IgnoreTurnLimit | +| `ChannelArchSpirit` | ArchSpirit | Channel target arch-spirit | same flags | +| `ChannelInstinct` | Instinct | Channel instinct card | IgnoreCost | +| `ChannelRepentance` | Repentance | Channel repentance card | IgnoreCost | +| `ChannelRuin` | Ruin | Place/activate ruin | IgnoreCost, IgnoreRange | +| `ChannelFromHand` | Any | Channel any card from hand | Type filter, IgnoreFlags | +| `ChannelFromDeck` | Any | Channel any card from top of deck | Type filter, IgnoreFlags | + +### 9.3 Unit — health / damage operations + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `DealDamage` | Deal N damage to target | Amount, AmountSource | +| `HealDamage` | Heal N damage on target | Amount, AmountSource | +| `ApplyDot` | Apply damage-over-time | Amount, DurationMode, DurationN | +| `ApplyHot` | Apply heal-over-time | Amount, DurationMode, DurationN | +| `PreventDamage` | Prevent next N damage | Amount, DurationMode | +| `PreventDeath` | Prevent next death | DurationMode | + +### 9.4 Unit — movement and positioning + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `PushUnit` | Push target N tiles in direction | Amount, Direction (Away/Toward/Cardinal) | +| `PullUnit` | Pull target N tiles toward caster | Amount | +| `DisplaceUnit` | Move unit to specific tile | TargetTile (selector) | +| `SwapPositions` | Swap two units | — | + +### 9.5 Unit — stat modifications + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `ModifyStat` | Modify a numeric stat | Stat (Damage/Health/Defense/MovementPoints/AttackRangeMin/AttackRangeMax), StatModOperator, Amount, AmountSource, DurationMode, DurationN | +| `ToggleBool` | Toggle a boolean capability | BoolKey (CanAttack/CanDefend/CanMove/CanUseAbility/etc.), Value (true/false), DurationMode | + +**StatModOperator values:** `Add` | `Subtract` | `Multiply` | `Divide` | `Percent` + +### 9.6 Unit — genus / affinity / ability mutations + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `AddGenus` | Add genus tag to unit | GenusTag | +| `RemoveGenus` | Remove genus tag from unit | GenusTag | +| `ChangeAffinity` | Change unit affinity | Affinity, DurationMode | +| `AddAbility` | Grant an ability to target | AbilityKey, DurationMode | +| `RemoveAbility` | Remove an ability from target | AbilityKey | + +### 9.7 ArchSpirit-specific operations + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `AscendArchSpirit` | Ascend arch-spirit to next tier | IgnoreCost | +| `TransitionVariant` | Transition to alternate form | VariantKey | +| `ModifyChannelRange` | Adjust channel range | Min, Max, StatModOperator | + +### 9.8 Spirit-specific operations + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `CloneAsToken` | Create spirit token copy of target | — | +| `TakeControl` | Take control of target spirit | DurationMode, DurationN | +| `TakeControlTemporary` | Take control until end of turn | — | +| `ReturnToOwner` | Return controlled spirit to its owner | — | +| `ModifyTokenReturnPolicy` | Change what happens when token expires | Policy | + +### 9.9 SpiritToken-specific operations + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `DestroyToken` | Destroy target spirit token | — | + +### 9.10 Ruin-specific operations + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `RelocateRuin` | Move ruin to target tile | TargetTile | +| `DisableRuin` | Disable ruin ability | DurationMode, DurationN | +| `ActivateRuinAbility` | Force-activate a ruin's ability | AbilityKey | +| `SendRuinToZone` | Send ruin card to zone | Zone | + +### 9.11 Tile operations + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `SetTileAffinity` | Set tile affinity | Affinity | +| `PushTileAffinity` | Push affinity to neighbors | Affinity, Radius | +| `ResolveTileEffect` | Force tile effect resolution | — | + +### 9.12 Player resource operations + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `ModifySP` | Add/subtract SP | Amount, AmountSource, StatModOperator | +| `ModifyST` | Add/subtract ST | Amount, AmountSource, StatModOperator | +| `SkipTurn` | Force target to skip their next turn | — | +| `ToggleChannelCapability` | Enable/disable a channel type for player | ChannelType, Value, DurationMode | + +### 9.13 Token creation + +| Effect Key | Description | Params | +|------------|-------------|--------| +| `CreateTokenFromCard` | Create token copy of an existing card | CardKey, OwnershipMode | +| `CreateCustomToken` | Create token from inline template | TokenTemplate (name/stats/abilities) | +| `ChannelCreatedToken` | Immediately channel the created token | IgnoreFlags | + +### 9.14 Value expressions (AmountSource) + +Effect amounts can be sourced from runtime game state: + +| Expression | Meaning | +|------------|---------| +| `Target.Damage` | Target unit's current damage stat | +| `Target.Health` | Target unit's current health | +| `Target.Defense` | Target unit's current defense | +| `Target.CurrentHealth` | Target unit's remaining health | +| `Self.Damage` | Caster's damage stat | +| `Self.Health` | Caster's health stat | +| `Self.CurrentHealth` | Caster's remaining health | +| `Self.SP` | Caster's current SP | +| `Action0.Target.SpCost` | SP cost of first action's target | +| `Trigger.Amount` | Amount from the trigger event (e.g., damage dealt) | + +--- + +## 10) Validation System + +### 10.1 Three validation stages + +**Stage 1 — Schema** +- Required fields present and correctly typed. +- Enums within valid value sets. +- Range min ≤ range max. +- Logic group depth ≤ 3. + +**Stage 2 — Semantic** +- Ability type gating: Passive/Aura not valid on Instinct/Repentance cards. +- Trigger event compatible with selected family. +- Source zone gate populated (Triggered abilities). +- Filter parameters correct for event type. +- Cost pick mode required when cost type demands it. +- Effect parameters present and typed correctly. +- Value expressions reference valid game state properties. + +**Stage 3 — Flow** +- Action group with OR/XOR has a ChooserAuthority. +- All TODO slots resolved (English mode). +- Target scope + target type combination is valid. +- Effect type valid for selected scope. +- Loop risk detection: Triggered ability that fires on events it can itself produce → Warning: recommend limits. + +### 10.2 Validation issue model + +```csharp +record ValidationIssue( + string Severity, // Error | Warning | Info + string Code, // stable dot-notation key, e.g. "trigger.sourceZoneGate.empty" + string Path, // JSON path to field, e.g. "triggered.sourceZoneGate" + string Message, // human-readable + string SuggestedFix // actionable suggestion +); +``` + +### 10.3 Error panel UX + +- Sticky at bottom of builder (all modes). +- Errors: red badge count in tab header. +- Warnings: yellow badge. +- Click issue → navigates to the relevant node (visual mode) or form field (form mode). +- Mobile: collapsible error drawer. + +### 10.4 Pre-save interactive metadata check + +Before save, validate all interactive mechanics have required authoring metadata: +- `DiscardFromHand` cost → PickMode required. +- `SendSpiritFromBattlefieldToDiscard` cost → PickMode required. +- `DealDamageToOwnSpirit` cost → PickMode required. +- Any action with `Chooser = Opponent` → confirm intent with warning. +- Action with `All` flag and `Scope = Battlefield` → performance warning. + +--- + +## 11) Canonical JSON Contract + +The compiled output is what the AbilitySystem parses. All three UI surfaces must produce identical JSON for the same logical ability. + +```json +{ + "name": "Ashwake Response", + "description": "When an ally spirit enters the battlefield, heal it for 2.", + "type": "Triggered", + "limits": { "perTurn": 1 }, + "triggered": { + "eventFamily": "BattlefieldState", + "eventType": "SpiritEntersBattlefield", + "sourceZoneGate": ["Battlefield"], + "ownershipScope": "Ally", + "limitMode": "PerTurn", + "limitAmount": 1, + "filters": [] + }, + "activationConditions": { + "logic": "AND", + "rules": [], + "groups": [] + }, + "actions": { + "logic": "AND", + "actions": [ + { + "scope": "Battlefield", + "targetType": "Spirit", + "chooser": "System", + "count": 1, + "filters": [ + { + "type": "Ownership", + "field": "Owner", + "comparator": "==", + "value": "TriggerSource" + } + ], + "conditions": { "logic": "AND", "rules": [], "groups": [] }, + "effects": [ + { + "type": "HealDamage", + "amount": 2 + } + ] + } + ], + "groups": [] + } +} +``` + +### 11.1 Serialization rules + +- `System.Text.Json` with `JsonIgnoreCondition.WhenWritingNull`. +- `JsonNamingPolicy.CamelCase`. +- Enums as strings (not integers). +- No mode-specific fields in output — all surfaces produce identical schema. +- Round-trip guarantee: `Parse(Compile(draft)) == draft` (semantic equivalence, not string equality). + +--- + +## 12) Gap Analysis — AbilityBuilderR2-Draft.razor vs R3 + +| Area | R2-Draft Status | R3 Target | +|------|----------------|-----------| +| Data model | ✅ Good structure | Extend with value expressions, StatModOperator | +| Trigger events | ⚠️ Placeholder simplified list | Full 40+ event catalog per §5 | +| Trigger filters | ⚠️ Single OwnershipScope + Amount | Per-event filter schema per §5.2 | +| Source zone gate | ✅ Present | ✅ Carry forward | +| Condition system | ✅ LogicGroup structure | Add all domains per §6.2 | +| Cost system | ⚠️ Basic Cost types only | Full catalog + PickMode per §7 | +| Effect catalog | ⚠️ 8 placeholder types | Full 50+ catalog per §9 | +| Action scope | ⚠️ Basic scopes | Full scope + combined scopes per §8 | +| Value expressions | ❌ Not present | Add AmountSource expressions per §9.14 | +| StatModOperator | ❌ Not present | Add per §9.5 | +| Visual / Bubble canvas | ❌ Not present | Core R3 feature per §4.3 | +| English / AI mode | ❌ Not present | Phase E (post-form parity) | +| Flowchart output | ❌ JSON only | Canvas IS the flowchart in visual mode | +| Mermaid read-only diagram | ❌ Not present | Phase B: read-only in form mode | +| Validation | ✅ Basic coverage | Add Stage 3 + loop detection | +| Card wizard | ❌ Not wired | Full wizard per §3 | + +--- + +## 13) Delivery Phases + +### Phase A — Foundation (prerequisite) + +- [ ] Define `AbilityDefinitionDraftR3` sealed class hierarchy (§2). +- [ ] Define `ValidationIssue` record + validator pipeline shell (§10). +- [ ] `BuildCanonicalJson()` with full serialization rules (§11). +- [ ] `ParseFromJson()` for round-trip. +- [ ] New standalone page `AbilityBuilderR3-Draft.razor` at `/cards/ability-builder-r3-draft`. +- [ ] Validation error panel component (sticky, click-to-navigate). + +### Phase B — Form parity (full ability authoring via form) + +- [ ] Common fields: Name, Description, Type, Limits, Presentation. +- [ ] Active section: Range, LOS, Linear, Uses/turn. +- [ ] Triggered section: Full trigger event picker (families → events), source zone gate, per-event filters. +- [ ] Passive section: Scope, Cadence, Leave policy. +- [ ] Aura section: Range, hooks, leave policy. +- [ ] Activation conditions: Full `LogicGroupDraft` nested editor (all domains per §6.2). +- [ ] Cost group editor: All cost types + PickMode per §7. +- [ ] Action group editor: All scopes + target types + typed filters. +- [ ] Full effect editor: All effect types per §9 + value expressions + StatModOperator. +- [ ] Read-only Mermaid.js flowchart rendering the compiled JSON. +- [ ] Presets: sample Active + Triggered preloaded. + +### Phase C — Card wizard + +- [ ] 5-step wizard for new card creation (§3). +- [ ] All card type fields and gates. +- [ ] Ability list integration: add/edit/reorder with inline Ability Builder. +- [ ] Review + validate + save step. + +### Phase D — Visual bubble canvas + +- [ ] Node palette + drag-drop onto canvas. +- [ ] Port type system + connection validation. +- [ ] Property sidebar per selected node. +- [ ] Real-time JSON sync from canvas. +- [ ] "Decompile from JSON" to re-render existing ability as nodes. +- [ ] Execution path highlight on node selection. +- [ ] Undo/redo. +- [ ] Canvas ↔ Form mode parity (both surfaces edit same draft). + +### Phase E — English / AI mode + +- [ ] Textarea + AI submit. +- [ ] Draft loader from AI response. +- [ ] Confidence indicators + TODO slot UX. +- [ ] Diff panel (AI proposed vs confirmed). +- [ ] "Apply to Canvas" hand-off to visual mode. +- [ ] Save gated on TODO resolution. + +### Phase F — Hardening + +- [ ] Round-trip regression suite: Form → JSON → Parse → Form (all ability types). +- [ ] Visual → JSON → Visual (semantic equivalence). +- [ ] Legacy JSON load: existing ability JSON loads cleanly into R3 draft. +- [ ] Loop risk detection in validator. +- [ ] Mobile UX polish: progressive disclosure, sticky errors, chip/tag inputs. +- [ ] Performance: large action groups, deep condition nesting. + +--- + +## 14) Acceptance Criteria + +- [ ] Designer authors a complete Active ability with cost, conditions, and effects via mobile form. +- [ ] Designer authors a complete Triggered ability with full source-zone gating and per-event filters. +- [ ] Visual canvas and form mode produce byte-equivalent canonical JSON for the same ability. +- [ ] Validation catches: missing source zone gate, loop risk, missing pick mode, invalid effect params. +- [ ] Existing saved ability JSON round-trips through R3 parser without mutation. +- [ ] All effect families per §9 are authorable (no "coming soon" stubs in Phase B+). +- [ ] Instinct/Repentance cards cannot add Passive or Aura ability types. +- [ ] ArchSpirit-only card fields (tier, channel range) are hidden for non-ArchSpirit cards. +- [ ] English mode draft loads into canvas with all TODO slots visible and resolvable. + +--- + +## 15) Open Questions + +| # | Question | Default Assumption | +|---|----------|-------------------| +| 1 | Do Triggered abilities support costs, or is that Active-only? | Active-only for now; Triggered costs via spec extension if needed | +| 2 | Max nesting depth for condition groups? | 3 | +| 3 | Max nesting depth for action groups? | 2 | +| 4 | Combined scopes (`Hand+Deck`) — are these first-class or derived? | First-class scope keys | +| 5 | Token template authoring — inline in effect, or separate card editor flow? | Inline for simple tokens; separate editor for complex | +| 6 | AI English mode — which model/API? | Defer to Phase E; API call abstracted behind `IAbilityAiDraftService` | +| 7 | Undo/redo scope — within-session only, or persistent? | Within-session only | +| 8 | Should read-only Mermaid diagram be in Form mode only, or also Visual mode? | Form mode only; Visual canvas IS the diagram in Visual mode | + +--- + +## Appendix A — Mermaid Flowchart Rendering Plan + +Phase B adds a read-only Mermaid.js flowchart in the Form mode right panel. + +**Implementation:** +1. Load Mermaid.js from CDN (UMD build) via ` + + + + + +
+
+ ⚡ Ability Builder R3 + + + + + + + @(_errors.Any(e=>e.Sev=="Error") ? $"✗ {_errors.Count(e=>e.Sev=="Error")} errors" : "✓ Valid") + +
+ + +
+ + + +
+ +
+ +@if (_mode == "form") +{ + +
+ + +
+

Common

+
+
+
+
+
+
+
+
+
+ + + @if (_draft.Type == "Active") + { +
+

Active — Range & Targeting

+
+
+
+
+
+ } + + @if (_draft.Type == "Triggered") + { +
+

Triggered — Event

+
+ + +
+
+ + +
+
+
+ @foreach (var z in new[]{"Battlefield","Hand","Discard","Deck"}) { + + } +
+
+
+ + @if (_draft.TriggerLimitMode != "Unlimited") { + + } +
+
+

Trigger Parameters

+ @RenderTriggerParams() +
+
+ } + + @if (_draft.Type == "Passive") + { +
+

Passive

+
+ +
+
+ +
+
+ +
+
+ } + + @if (_draft.Type == "Aura") + { +
+

Aura

+
+
+
+
+ + @if (_draft.AuraLingerDurationType == "ForNTurns") { + + } +
+
+ } + + +
+

Activation Conditions

+ @RenderLogicGroup(_draft.ActivationConditions, "activationConditions") +
+ + + @if (_draft.Type == "Active") + { +
+

Costs

+ @foreach (var (cost, ci) in _draft.Costs.Select((c,i)=>(c,i))) + { +
+
+ + + + +
+ @if (cost.TypeStr is "DiscardFromHand" or "SendSpiritFromBattlefieldToDiscard" or "DealDamageToOwnSpirit") + { +
+ + +
+
+ } +
+ } + +
+ } + + +
+

Actions

+ @foreach (var (action, ai) in _draft.Actions.Select((a,i)=>(a,i))) + { +
+
+ Action @(ai+1) + +
+
+ +
+
+ +
+
+ +
+
+ + + +
+ + +
+

Action Conditions

+ @RenderLogicGroup(action.Conditions, $"action_{ai}_conds") +
+ + +
+

Effects

+ @foreach (var (eff, ei) in action.Effects.Select((e,i)=>(e,i))) + { +
+
+ + + +
+ @RenderEffectParams(eff) +
+ } + +
+ + +
+

Action Duration

+
+ + @if (action.DurationType == "ForNTurns") { + + } +
+
+ +
+
+ + +
+

ChooseOne Branches (optional — overrides Effects)

+ @foreach (var (branch, bi) in action.Branches.Select((b,i)=>(b,i))) + { +
+
+ + + +
+ Nested branch actions — use JSON edit for now +
+ } + +
+
+ } + +
+ +
+} + +@if (_mode == "canvas") +{ +
+
DRAG TO CANVAS
+ @foreach (var n in NodeTypes) + { +
@n.Display
+ } +
+
+ + + + + + + + @foreach (var conn in _connections) + { + var from = _nodes.FirstOrDefault(n => n.Id == conn.FromId); + var to = _nodes.FirstOrDefault(n => n.Id == conn.ToId); + if (from != null && to != null) + { + double x1 = from.X + 120, y1 = from.Y + 20; + double x2 = to.X, y2 = to.Y + 20; + double cx = (x1 + x2) / 2; + + @((MarkupString)$"{conn.Label}") + } + } + + @foreach (var node in _nodes) + { + double tx = node.X, ty = node.Y; + + + @node.Kind + @(node.Label?.Length > 16 ? node.Label[..16]+"…" : node.Label) + + + + } + + @if (_wiringFrom != null) + { + + } + + + @if (_selectedNode != null) + { +
+
@_selectedNode.Kind Properties
+
+ @if (_selectedNode.Kind == "Effect") + { +
+ +
+
+ } + @if (_selectedNode.Kind is "Trigger") + { +
+ +
+ } + +
+
Connect: drag from blue port → another node
+
+ } +
+} + +@if (_mode == "mermaid") +{ +
+
+
+ @((MarkupString)$"
{BuildMermaidDiagram()}
") +
+
+
+} + + +
+

Engine JSON Output

+
+
@_compiledJson
+
+
+ + +
+
+ +
+ + +@if (_errors.Any()) +{ +
+ @foreach (var e in _errors) + { +
[@e.Sev] @e.Message
+ } +
+} + +
+ +@code { + +// ══════════════════════════════════════════════════════════════════ +// DRAFT MODEL +// ══════════════════════════════════════════════════════════════════ + +private sealed class AbilityDraft +{ + public string Name { get; set; } = "New Ability"; + public string Description { get; set; } = ""; + public string Type { get; set; } = "Active"; + + // Common limits + public int? LimitPerTurn { get; set; } + public int? LimitPerGame { get; set; } + public int UsesPerTurn { get; set; } = 1; + + // Presentation + public string? AnimKey { get; set; } + public string? CastSfx { get; set; } + public string? ImpactSfx { get; set; } + + // Active + public int RangeMin { get; set; } = 1; + public int RangeMax { get; set; } = 1; + public bool RequiresLos { get; set; } + public bool LinearOnly { get; set; } + + // Triggered + public string TriggerFamily { get; set; } = "Unit — Lifecycle"; + public string TriggerEvent { get; set; } = "OnUnitEnterBattlefield"; + public List SourceZoneGate { get; set; } = ["Battlefield"]; + public string TriggerLimitMode { get; set; } = "Unlimited"; + public int? TriggerLimitAmount { get; set; } + public string TriggerOwnership { get; set; } = "Any"; + // Extra trigger params (shared across triggers that have them) + public string? TriggerOwnership2 { get; set; } // SourceOwnership / TargetOwnership + public string? TriggerUnitType { get; set; } = "Unit"; + public int? TriggerAmount { get; set; } + public string? TriggerDamageType { get; set; } = "Any"; + public string? TriggerPlayer { get; set; } = "Owner"; + public string? TriggerStat { get; set; } + public string? TriggerCause { get; set; } + + // Passive + public string PassiveScope { get; set; } = "Battlefield"; + public string PassiveCadence { get; set; } = "OnAnyEvent"; + public string PassiveLeavePolicy { get; set; } = "Remove"; + + // Aura + public int AuraRangeMin { get; set; } = 1; + public int AuraRangeMax { get; set; } = 2; + public bool AuraClearOnLeave { get; set; } + public string AuraLingerDurationType { get; set; } = ""; + public int? AuraLingerN { get; set; } + + // Logic groups + public LogicGroupDraft ActivationConditions { get; set; } = new(); + + // Costs & Actions + public List Costs { get; set; } = new(); + public List Actions { get; set; } = new(); +} + +private sealed class LogicGroupDraft +{ + public string Logic { get; set; } = "AND"; + public List Rules { get; set; } = new(); + public List Groups { get; set; } = new(); +} + +private sealed class CondDraft +{ + public string Domain { get; set; } = "Unit"; + public string Field { get; set; } = "HasGenus"; + public string Comparator { get; set; } = "=="; + public string Value { get; set; } = ""; + public string Subject { get; set; } = "Self"; // Self | Target +} + +private sealed class CostDraft +{ + public string TypeStr { get; set; } = "SpiritPoints"; + public int Amount { get; set; } = 1; + public string PickMode { get; set; } = ""; + public string? FilterGenusTag { get; set; } +} + +private sealed class ActionDraft +{ + public string Scope { get; set; } = "Battlefield"; + public string TargetType { get; set; } = "Unit"; + public string Ownership { get; set; } = "Enemy"; + public int Count { get; set; } = 1; + public bool All { get; set; } + public bool UpTo { get; set; } + + public LogicGroupDraft Conditions { get; set; } = new(); + public List Effects { get; set; } = new(); + public List Branches { get; set; } = new(); + + public string DurationType { get; set; } = ""; + public int? DurationN { get; set; } + public string DurationPlayerScope { get; set; } = ""; +} + +private sealed class EffectDraft +{ + public string TypeKey { get; set; } = "DealDamage"; + // Stat mod fields + public int? Amount { get; set; } = 1; + public string? AmountRef { get; set; } // dynamic ValueExpr.Ref + public string StatModOp { get; set; } = "Add"; + public string StatTarget { get; set; } = "Current"; + // Bool flag effects + public bool BoolValue { get; set; } = true; + // String param effects + public string? StringParam { get; set; } // genus tag, ability name, affinity, etc. + // Zone effects + public string DeckPosition { get; set; } = "top"; + // Duration (for DOT/HOT/TakeControl) + public string DurationType { get; set; } = "UntilEndOfTurn"; + public int? DurationN { get; set; } + // Drawing / milling counts + public int? CountN { get; set; } = 1; + // Displacement + public int? Tiles { get; set; } = 1; + public string Direction { get; set; } = "North"; + public int? BlockedDamage { get; set; } + // BypassDefense + public bool BypassDefense { get; set; } + // Controller override + public string? Controller { get; set; } + // Multiplier + public double? CostMultiplier { get; set; } + public bool PayCost { get; set; } = true; + // Player targeting for zone effects + public string TargetPlayer { get; set; } = "Owner"; + // SetStatModMultiplier + public string? StatName { get; set; } + public double Multiplier { get; set; } = 1.0; + // MinAttackRange/Max + public int? RangeMin { get; set; } + public int? RangeMax { get; set; } + // Cost mod + public int? SpMod { get; set; } + public int? StMod { get; set; } + // Health minimum + public int? Minimum { get; set; } = 1; + // SetFixedSacrificeReturn + public int? StAmount { get; set; } + // GrantAdditionalAttack + public int AttackCount { get; set; } = 1; + // SummonToken + public string? TokenJson { get; set; } +} + +private sealed class BranchDraft +{ + public string Label { get; set; } = "Branch"; +} + +// ══════════════════════════════════════════════════════════════════ +// STATIC CATALOG DATA +// ══════════════════════════════════════════════════════════════════ + +private record Entry(string Key, string Display); + +private static readonly Dictionary> TriggerFamilies = new() +{ + ["Turn / Timing"] = [new("OnTurnStart","On Turn Start"), new("OnTurnEnd","On Turn End")], + ["Channeling"] = [new("OnChanneled","On Channeled")], + ["ArchSpirit"] = [new("OnAscend","On Ascend"), new("OnTransition","On Transition")], + ["Unit — Actions"] = [new("OnUnitMove","On Unit Move"), new("OnUnitAttack","On Unit Attack"), + new("OnUnitAbilityActivated","On Unit Ability Activated"), new("OnUnitMPSpent","On Unit MP Spent")], + ["Damage & Healing"] = [new("OnDamageDealt","On Damage Dealt"), new("OnDamagePrevented","On Damage Prevented"), + new("OnHealed","On Healed"), new("BeforeUnitDeath","Before Unit Death"), + new("BeforeDamageApplied","Before Damage Applied")], + ["Unit — Lifecycle"] = [new("OnUnitEnterBattlefield","On Unit Enter Battlefield"), + new("OnUnitLeaveBattlefield","On Unit Leave Battlefield"), + new("OnUnitDeath","On Unit Death"), new("OnUnitSentToDiscard","On Unit Sent To Discard"), + new("OnSpiritSacrificed","On Spirit Sacrificed"), new("OnTokenSummoned","On Token Summoned")], + ["Unit — State"] = [new("OnStatModified","On Stat Modified"), new("OnAbilityAdded","On Ability Added"), + new("OnAbilityRemoved","On Ability Removed"), new("OnGenusChanged","On Genus Changed")], + ["Ruin"] = [new("OnRuinActivation","On Ruin Activation"), new("OnUnitOccupyRuin","On Unit Occupy Ruin")], + ["Tile"] = [new("OnTileAffinityChanged","On Tile Affinity Changed")], + ["Player Resources"] = [new("OnSPGained","On SP Gained"), new("OnSPSpent","On SP Spent"), + new("OnSTGained","On ST Gained"), new("OnSTSpent","On ST Spent")], + ["Card Zone"] = [new("OnCardDrawn","On Card Drawn"), new("OnCardDiscarded","On Card Discarded"), + new("OnCardReturnedToHand","On Card Returned To Hand"), + new("OnCardReturnedToDeck","On Card Returned To Deck"), + new("OnDeckShuffled","On Deck Shuffled"), new("OnCardsRevealed","On Cards Revealed")], + ["Effect Lifecycle"] = [new("OnTargetedByAbility","On Targeted By Ability"), + new("OnEffectApplied","On Effect Applied"), + new("OnEnterAuraRange","On Enter Aura Range"), new("OnLeaveAuraRange","On Leave Aura Range")], +}; + +private static readonly Dictionary> EffectGroups = new() +{ + ["Stat Modification"] = [ + new("ModifyHealth","Modify Health"), new("ModifyDefense","Modify Defense"), + new("ModifyDamage","Modify Damage"), new("ModifyMP","Modify MP"), + new("ModifyMinAttackRange","Modify Min Attack Range"), new("ModifyMaxAttackRange","Modify Max Attack Range"), + new("SetAttackRange","Set Attack Range"), new("SetMovementType","Set Movement Type"), + new("ModifyCost","Modify SP/ST Cost"), new("SetAffinity","Set Affinity"), + new("GrantAdditionalAttack","Grant Additional Attack"), new("SetStatModMultiplier","Set Stat Mod Multiplier"), + ], + ["Unit Flags"] = [ + new("SetCanMove","Set Can Move"), new("SetCanAttack","Set Can Attack"), + new("SetCanDefend","Set Can Defend"), new("SetCanBeAttacked","Set Can Be Attacked"), + new("SetCanBeBlocked","Set Can Be Blocked"), new("SetCanBeObstructed","Set Can Be Obstructed"), + new("SetCanUseAbility","Set Can Use Ability"), new("SetCanBeSacrificed","Set Can Be Sacrificed"), + ], + ["Player Flags"] = [ + new("SetCanDrawCards","Set Can Draw Cards"), new("SetAccumulatesSP","Set Accumulates SP"), + new("SetCanChannelSpirit","Set Can Channel Spirit"), new("SetCanSacrificeSpirit","Set Can Sacrifice Spirit"), + new("SetCanAscendArchSpirit","Set Can Ascend ArchSpirit"), new("SetCanTransitionArchSpirit","Set Can Transition ArchSpirit"), + new("SetCanChannelRepentance","Set Can Channel Repentance"), new("SetCanChannelInstinct","Set Can Channel Instinct"), + new("SetCanChannelRuin","Set Can Channel Ruin"), + new("SetCanChannelTerramorphaMono","Set Can Channel Terramorpha Mono"), + new("SetCanChannelTerramorphaDi","Set Can Channel Terramorpha Di"), + new("SetCanChannelTerramorphaTri","Set Can Channel Terramorpha Tri"), + ], + ["Ability Modification"] = [ + new("AddAbility","Add Ability"), new("RemoveAbility","Remove Ability"), + new("EnableAbility","Enable Ability"), new("DisableAbility","Disable Ability"), + ], + ["Genus"] = [ + new("AddGenus","Add Genus"), new("RemoveGenus","Remove Genus"), + ], + ["Player Resources"] = [ + new("ModifySP","Modify SP"), new("ModifySPAccumulation","Modify SP Accumulation"), + new("ModifyST","Modify ST"), new("ModifyCardsDrawnPerTurn","Modify Cards Drawn Per Turn"), + ], + ["Tile"] = [ + new("SetBaseAffinity1","Set Base Affinity 1"), new("SetBaseAffinity2","Set Base Affinity 2"), + new("PushAffinity","Push Affinity"), new("PushFinalAffinity","Push Final Affinity"), + ], + ["Zone / Cards"] = [ + new("DrawCards","Draw Cards"), new("DiscardCards","Discard Cards"), + new("ReturnToHand","Return To Hand"), new("ReturnToDeck","Return To Deck"), + new("ReturnToBattlefield","Return To Battlefield"), new("SendToDiscard","Send To Discard"), + new("SearchDeck","Search Deck"), new("ShuffleDeck","Shuffle Deck"), + new("RevealCards","Reveal Cards"), new("PlaceOnDeck","Place On Deck"), + new("ChannelCard","Channel Card"), + ], + ["Combat / Damage"] = [ + new("DealDamage","Deal Damage"), new("Heal","Heal"), + new("DealDamageToSelf","Deal Damage To Self"), new("DOT","Damage Over Time"), + new("HOT","Heal Over Time"), new("PreventDeath","Prevent Death"), + new("PreventNextDamage","Prevent Next Damage"), new("SetHealthMinimum","Set Health Minimum"), + ], + ["Displacement"] = [ + new("PushUnit","Push Unit"), new("PullUnit","Pull Unit"), + new("DisplaceUnit","Displace Unit"), new("RepositionUnit","Reposition Unit"), + ], + ["Control"] = [ + new("TakeControl","Take Control"), new("GrantMovementControl","Grant Movement Control"), + new("SetFixedSacrificeReturn","Set Fixed Sacrifice Return"), + ], + ["Token"] = [ + new("SummonToken","Summon Token"), + ], + ["Deferred"] = [ + new("ApplyOnEvent","Apply On Event"), + ], +}; + +private static readonly Entry[] NodeTypes = +[ + new("Trigger","⚡ Trigger"), new("ConditionGroup","◆ Conditions"), new("CostGroup","◉ Costs"), + new("ActionGroup","▶ Actions"), new("Effect","✦ Effect"), +]; + +private static readonly string[] StatModOps = ["Add","Subtract","Multiply","Divide","Percent"]; +private static readonly string[] Affinities = ["Fire","Water","Earth","Air","Void","Neutral"]; +private static readonly string[] MovementTypes = ["Walk","Fly","Burrow","Swim","Phase"]; +private static readonly string[] Ownerships = ["Owner","Enemy","Any","Ally"]; +private static readonly string[] DurationTypes = ["Instant","UntilEndOfTurn","UntilStartOfOwnerTurn", + "UntilStartOfSourceOwnerTurn","ForNTurns","UntilEndOfSequence","WhileCondition", + "WhileSourceOnBattlefield","PermanentInMatch"]; + +// ══════════════════════════════════════════════════════════════════ +// STATE +// ══════════════════════════════════════════════════════════════════ + +private AbilityDraft _draft = new(); +private string _mode = "form"; +private string _compiledJson = "// Click Compile"; +private int _mermaidKey = 0; +private record ValidationError(string Sev, string Message); +private List _errors = new(); + +// Canvas state +private sealed class CanvasNode +{ + public string Id { get; set; } = Guid.NewGuid().ToString("N")[..8]; + public string Kind { get; set; } = "Effect"; + public string? Label { get; set; } + public double X { get; set; } + public double Y { get; set; } + public bool Selected { get; set; } + public string? EffectTypeKey { get; set; } = "DealDamage"; + public int? Amount { get; set; } + public string? TriggerEventKey { get; set; } = "OnUnitEnterBattlefield"; +} +private sealed class CanvasConnection +{ + public string FromId { get; set; } = ""; + public string ToId { get; set; } = ""; + public string Label { get; set; } = ""; +} +private List _nodes = new(); +private List _connections = new(); +private CanvasNode? _selectedNode; +private CanvasNode? _draggingNode; +private CanvasNode? _wiringFrom; +private double _wireX, _wireY; +private double _dragOffX, _dragOffY; +private string _paletteDragKind = ""; + +// ══════════════════════════════════════════════════════════════════ +// LIFECYCLE +// ══════════════════════════════════════════════════════════════════ + +protected override async Task OnAfterRenderAsync(bool firstRender) +{ + if (_mode == "mermaid") + { + try { await JS.InvokeVoidAsync("mermaid.run"); } catch { } + } +} + +// ══════════════════════════════════════════════════════════════════ +// HELPERS +// ══════════════════════════════════════════════════════════════════ + +private IEnumerable CurrentFamilyEvents => + TriggerFamilies.TryGetValue(_draft.TriggerFamily, out var list) ? list : []; + +private void OnTypeChanged(ChangeEventArgs e) +{ + _draft.Type = e.Value?.ToString() ?? "Active"; + Compile(); +} + +private void OnFamilyChanged(ChangeEventArgs e) +{ + _draft.TriggerFamily = e.Value?.ToString() ?? TriggerFamilies.Keys.First(); + _draft.TriggerEvent = CurrentFamilyEvents.FirstOrDefault()?.Key ?? ""; +} + +private void ToggleZoneGate(string zone, bool on) +{ + if (on) { if (!_draft.SourceZoneGate.Contains(zone)) _draft.SourceZoneGate.Add(zone); } + else _draft.SourceZoneGate.Remove(zone); +} + +private void SetMode(string m) { _mode = m; if (m == "mermaid") { _mermaidKey++; } } + +private void AddCost() => _draft.Costs.Add(new()); +private void AddAction() => _draft.Actions.Add(new()); + +private static IEnumerable GetTargetTypes(string scope) => scope switch +{ + "Battlefield" => ["Unit","ArchSpirit","Spirit","SpiritToken","Ruin","Tile"], + "Player" => ["Player"], + _ => ["Card","Spirit","ArchSpirit","SpiritToken","Ruin","Unit"], +}; + +private static string NodeColor(string kind) => kind switch +{ + "Trigger" => "#4a0070", + "ConditionGroup" => "#00305a", + "CostGroup" => "#5a3000", + "ActionGroup" => "#004a30", + "Effect" => "#5a0020", + _ => "#333", +}; + +// ══════════════════════════════════════════════════════════════════ +// CANVAS INTERACTIVITY +// ══════════════════════════════════════════════════════════════════ + +private void OnPaletteDragStart(string kind) => _paletteDragKind = kind; + +private void OnCanvasDrop(DragEventArgs e) +{ + if (string.IsNullOrEmpty(_paletteDragKind)) return; + _nodes.Add(new CanvasNode { Kind = _paletteDragKind, X = e.OffsetX - 60, Y = e.OffsetY - 20 }); + _paletteDragKind = ""; +} + +private void OnNodeMouseDown(MouseEventArgs e, CanvasNode node) +{ + if (e.Button == 0) + { + foreach (var n in _nodes) n.Selected = false; + node.Selected = true; + _selectedNode = node; + _draggingNode = node; + _dragOffX = e.OffsetX - node.X; + _dragOffY = e.OffsetY - node.Y; + } +} + +private void OnPortMouseDown(MouseEventArgs e, CanvasNode node) +{ + _wiringFrom = node; + _wireX = node.X + 120; + _wireY = node.Y + 20; +} + +private void OnCanvasMouseDown(MouseEventArgs e) +{ + if (e.Button == 0 && _draggingNode == null) + { + foreach (var n in _nodes) n.Selected = false; + _selectedNode = null; + } +} + +private void OnCanvasMouseMove(MouseEventArgs e) +{ + if (_draggingNode != null) + { + _draggingNode.X = e.OffsetX - _dragOffX; + _draggingNode.Y = e.OffsetY - _dragOffY; + } + if (_wiringFrom != null) + { + _wireX = e.OffsetX; + _wireY = e.OffsetY; + } +} + +private void OnCanvasMouseUp(MouseEventArgs e) +{ + if (_wiringFrom != null) + { + // Find if mouse is over another node + var target = _nodes.FirstOrDefault(n => + n.Id != _wiringFrom.Id && + e.OffsetX >= n.X && e.OffsetX <= n.X + 120 && + e.OffsetY >= n.Y && e.OffsetY <= n.Y + 40); + if (target != null) + _connections.Add(new CanvasConnection { FromId = _wiringFrom.Id, ToId = target.Id }); + _wiringFrom = null; + } + _draggingNode = null; +} + +private void DeleteSelectedNode() +{ + if (_selectedNode == null) return; + _connections.RemoveAll(c => c.FromId == _selectedNode.Id || c.ToId == _selectedNode.Id); + _nodes.Remove(_selectedNode); + _selectedNode = null; +} + +// ══════════════════════════════════════════════════════════════════ +// FORM RENDERERS +// ══════════════════════════════════════════════════════════════════ + +private RenderFragment RenderLogicGroup(LogicGroupDraft group, string key) => __builder => +{ +
+
+ + +
+ @foreach (var (rule, ri) in group.Rules.Select((r,i)=>(r,i))) + { +
+
+ + + + + + +
+
+ } + + + @foreach (var sub in group.Groups) + { +
+ @RenderLogicGroup(sub, key + "_sub") +
+ } +
+}; + +private RenderFragment RenderTriggerParams() => __builder => +{ + var ev = _draft.TriggerEvent; + + // Ownership (most triggers have it) + if (ev is not ("OnTileAffinityChanged")) + { +
+ +
+ } + + // Unit Type (lifecycle triggers) + if (ev is "OnUnitEnterBattlefield" or "OnUnitLeaveBattlefield" or "OnUnitDeath" + or "OnUnitSentToDiscard" or "BeforeUnitDeath") + { +
+ +
+ } + + // CausedBy (OnUnitSentToDiscard) + if (ev == "OnUnitSentToDiscard") + { +
+ +
+ } + + // Source/Target ownership (damage triggers) + if (ev is "OnDamageDealt" or "BeforeDamageApplied") + { +
+ +
+
+ +
+ } + + // DamageType (OnDamageDealt) + if (ev == "OnDamageDealt") + { +
+ +
+ } + + // Amount (damage/heal/resource triggers) + if (ev is "OnDamageDealt" or "OnHealed" or "OnSPGained" or "OnSPSpent" + or "OnSTGained" or "OnSTSpent" or "OnUnitMPSpent") + { +
+ +
+ } + + // Player (turn/resource/card-zone triggers) + if (ev is "OnTurnStart" or "OnTurnEnd" or "OnSPGained" or "OnSPSpent" + or "OnSTGained" or "OnSTSpent" or "OnCardDrawn" or "OnCardDiscarded" + or "OnCardReturnedToHand" or "OnCardReturnedToDeck" or "OnDeckShuffled" or "OnCardsRevealed") + { +
+ +
+ } + + // Aura Ownership (aura triggers) + if (ev is "OnEnterAuraRange" or "OnLeaveAuraRange") + { +
+ +
+
+ +
+ } + + // Ruin ownership + if (ev == "OnRuinActivation") + { +
+ +
+
+ +
+ } + + // Stat name (OnStatModified) + if (ev == "OnStatModified") + { +
+ +
+ } + + // CardType (OnChanneled) + if (ev == "OnChanneled") + { +
+ +
+ } +}; + +private RenderFragment RenderEffectParams(EffectDraft eff) => __builder => +{ + var t = eff.TypeKey; + + // Stat mod effects: Amount + Operator + StatTarget + if (t is "ModifyHealth" or "ModifyDefense" or "ModifyDamage" or "ModifyMP" + or "ModifyMinAttackRange" or "ModifyMaxAttackRange") + { +
+ + + + +
+ if (t is "ModifyHealth" or "ModifyDefense" or "ModifyMP") + { +
+ +
+ } + } + + // SetAttackRange + else if (t == "SetAttackRange") + { +
+ + +
+ } + + // Movement type + else if (t == "SetMovementType") + { +
+ +
+ } + + // Affinity effects + else if (t is "SetAffinity" or "SetBaseAffinity1" or "SetBaseAffinity2" + or "PushAffinity" or "PushFinalAffinity") + { +
+ +
+ } + + // Bool flag effects (unit/player) + else if (t.StartsWith("SetCan") || t == "SetAccumulatesSP") + { +
+ +
+ } + + // Ability mod effects + else if (t is "RemoveAbility" or "EnableAbility" or "DisableAbility" or "AddGenus" or "RemoveGenus") + { +
+ +
+ } + + // ModifyCost + else if (t == "ModifyCost") + { +
+ + +
+ } + + // Player resource mods + else if (t is "ModifySP" or "ModifySPAccumulation" or "ModifyST" or "ModifyCardsDrawnPerTurn") + { +
+ + + +
+ } + + // Draw / discard / reveal / place + else if (t is "DrawCards" or "DiscardCards" or "RevealCards") + { +
+ + + +
+ } + + // ReturnToDeck / PlaceOnDeck + else if (t is "ReturnToDeck" or "PlaceOnDeck") + { +
+ +
+ } + + // ShuffleDeck + else if (t == "ShuffleDeck") + { +
+ +
+ } + + // ReturnToBattlefield + else if (t == "ReturnToBattlefield") + { +
+ +
+ } + + // ChannelCard + else if (t == "ChannelCard") + { +
+ + +
+ } + + // Damage effects + else if (t is "DealDamage" or "Heal" or "DealDamageToSelf" or "PreventNextDamage") + { +
+ + + +
+ if (t is "DealDamage" or "DealDamageToSelf") + { +
+ } + } + + // DOT / HOT + else if (t is "DOT" or "HOT") + { +
+ + +
+
+ + @if (eff.DurationType == "ForNTurns") { + + } +
+ if (t == "DOT") + { +
+ } + } + + // SetHealthMinimum + else if (t == "SetHealthMinimum") + { +
+ } + + // Displacement effects + else if (t is "PushUnit" or "PullUnit" or "DisplaceUnit") + { +
+ + @if (t != "PullUnit") + { + + } +
+ if (t == "DisplaceUnit") + { +
+ +
+ } + } + + // TakeControl + else if (t == "TakeControl") + { +
+ +
+ } + + // GrantMovementControl + else if (t == "GrantMovementControl") + { +
+ } + + // GrantAdditionalAttack + else if (t == "GrantAdditionalAttack") + { +
+ } + + // SetStatModMultiplier + else if (t == "SetStatModMultiplier") + { +
+ + +
+ } + + // SetFixedSacrificeReturn + else if (t == "SetFixedSacrificeReturn") + { +
+ } + + // SummonToken + else if (t == "SummonToken") + { +
+ } +}; + +// ══════════════════════════════════════════════════════════════════ +// COMPILE → ENGINE-NATIVE JSON +// ══════════════════════════════════════════════════════════════════ + +private void Compile() +{ + _errors = Validate(); + _compiledJson = BuildEngineJson(); + StateHasChanged(); +} + +private async Task CopyJson() +{ + try { await JS.InvokeVoidAsync("navigator.clipboard.writeText", _compiledJson); } catch { } +} + +private string BuildEngineJson() +{ + using var ms = new System.IO.MemoryStream(); + using var w = new System.Text.Json.Utf8JsonWriter(ms, + new System.Text.Json.JsonWriterOptions { Indented = true }); + w.WriteStartObject(); + + w.WriteString("Type", _draft.Type); + if (!string.IsNullOrWhiteSpace(_draft.Name)) w.WriteString("Name", _draft.Name); + if (!string.IsNullOrWhiteSpace(_draft.Description)) w.WriteString("Description", _draft.Description); + if (_draft.UsesPerTurn != 1) w.WriteNumber("UsesPerTurn", _draft.UsesPerTurn); + + // Per-turn / per-game limits (Triggered) + if (_draft.TriggerLimitMode == "PerTurn" && _draft.TriggerLimitAmount.HasValue) + w.WriteNumber("TriggerLimitPerTurn", _draft.TriggerLimitAmount.Value); + if (_draft.TriggerLimitMode == "PerGame" && _draft.TriggerLimitAmount.HasValue) + w.WriteNumber("TriggerLimitPerGame", _draft.TriggerLimitAmount.Value); + + // SourceZoneGate + if (_draft.Type == "Triggered" && _draft.SourceZoneGate.Any()) + { + w.WriteStartArray("SourceZoneGate"); + foreach (var z in _draft.SourceZoneGate) w.WriteStringValue(z); + w.WriteEndArray(); + } + + // Animation + if (!string.IsNullOrWhiteSpace(_draft.AnimKey) || !string.IsNullOrWhiteSpace(_draft.CastSfx)) + { + w.WriteStartObject("Animation"); + if (!string.IsNullOrWhiteSpace(_draft.AnimKey)) w.WriteString("Type", _draft.AnimKey); + if (!string.IsNullOrWhiteSpace(_draft.CastSfx)) w.WriteString("CastSfx", _draft.CastSfx); + if (!string.IsNullOrWhiteSpace(_draft.ImpactSfx)) w.WriteString("ImpactSfx", _draft.ImpactSfx); + w.WriteEndObject(); + } + + // Type-specific fields + if (_draft.Type == "Active") + { + w.WriteStartObject("Range"); + w.WriteNumber("Min", _draft.RangeMin); + w.WriteNumber("Max", _draft.RangeMax); + if (_draft.RequiresLos) w.WriteBoolean("RequiresLos", true); + if (_draft.LinearOnly) w.WriteBoolean("LinearOnly", true); + w.WriteEndObject(); + } + else if (_draft.Type == "Triggered") + { + WriteEngineTriggeredSection(w); + } + else if (_draft.Type == "Aura") + { + w.WriteStartObject("AuraRange"); + w.WriteNumber("Min", _draft.AuraRangeMin); + w.WriteNumber("Max", _draft.AuraRangeMax); + w.WriteEndObject(); + if (_draft.AuraClearOnLeave) w.WriteBoolean("ClearOnLeave", true); + if (!string.IsNullOrEmpty(_draft.AuraLingerDurationType)) + { + w.WriteStartObject("LingerDuration"); + w.WriteString("DurationType", _draft.AuraLingerDurationType); + if (_draft.AuraLingerDurationType == "ForNTurns" && _draft.AuraLingerN.HasValue) + w.WriteNumber("N", _draft.AuraLingerN.Value); + w.WriteEndObject(); + } + } + + // Activation conditions + if (_draft.ActivationConditions.Rules.Any() || _draft.ActivationConditions.Groups.Any()) + { + w.WriteStartArray("ActivationConditions"); + WriteEngineLogicGroup(w, _draft.ActivationConditions); + w.WriteEndArray(); + } + + // Costs + if (_draft.Type == "Active" && _draft.Costs.Any()) + { + w.WriteStartArray("Cost"); + foreach (var cost in _draft.Costs) + { + w.WriteStartObject(); + w.WriteString("Type", cost.TypeStr); + w.WriteNumber("Amount", cost.Amount); + if (!string.IsNullOrEmpty(cost.PickMode)) w.WriteString("PickMode", cost.PickMode); + if (!string.IsNullOrWhiteSpace(cost.FilterGenusTag)) + { + w.WriteStartArray("Filters"); + w.WriteStartObject(); + w.WriteString("$type", "GenusContains"); + w.WriteString("Tag", cost.FilterGenusTag); + w.WriteEndObject(); + w.WriteEndArray(); + } + w.WriteEndObject(); + } + w.WriteEndArray(); + } + + // Actions + w.WriteStartArray("Actions"); + foreach (var action in _draft.Actions) + WriteEngineAction(w, action); + w.WriteEndArray(); + + w.WriteEndObject(); + w.Flush(); + return System.Text.Encoding.UTF8.GetString(ms.ToArray()); +} + +private void WriteEngineTriggeredSection(System.Text.Json.Utf8JsonWriter w) +{ + var ev = _draft.TriggerEvent; + w.WriteStartObject("TriggerEvent"); + w.WriteString("$type", ev); + + // Per-event params + var ownershipFieldName = ev switch + { + "OnDamageDealt" or "BeforeDamageApplied" => "SourceOwnership", + "OnDamagePrevented" or "OnHealed" or "OnTargetedByAbility" or "OnEffectApplied" + => "TargetOwnership", + "OnRuinActivation" => "RuinOwnership", + "OnUnitOccupyRuin" => "UnitOwnership", + "OnEnterAuraRange" or "OnLeaveAuraRange" => "AuraOwnership", + "OnTurnStart" or "OnTurnEnd" or "OnSPGained" or "OnSPSpent" + or "OnSTGained" or "OnSTSpent" or "OnCardDrawn" or "OnCardDiscarded" + or "OnCardReturnedToHand" or "OnCardReturnedToDeck" + or "OnDeckShuffled" or "OnCardsRevealed" => "Player", + _ => "Ownership", + }; + + if (ev is not "OnTileAffinityChanged") + w.WriteString(ownershipFieldName, _draft.TriggerOwnership); + + // Secondary ownership + if (!string.IsNullOrEmpty(_draft.TriggerOwnership2)) + { + var f2 = ev switch + { + "OnDamageDealt" or "BeforeDamageApplied" => "TargetOwnership", + "OnTargetedByAbility" or "OnEffectApplied" => "SourceOwnership", + "OnEnterAuraRange" or "OnLeaveAuraRange" => "UnitOwnership", + "OnRuinActivation" => "OccupantOwnership", + _ => null, + }; + if (f2 != null) w.WriteString(f2, _draft.TriggerOwnership2); + } + + // Unit type + if (ev is "OnUnitEnterBattlefield" or "OnUnitLeaveBattlefield" or "OnUnitDeath" + or "OnUnitSentToDiscard" or "BeforeUnitDeath" && !string.IsNullOrEmpty(_draft.TriggerUnitType)) + w.WriteString("UnitType", _draft.TriggerUnitType); + + if (ev == "OnChanneled" && !string.IsNullOrEmpty(_draft.TriggerUnitType)) + w.WriteString("CardType", _draft.TriggerUnitType); + + // Amount + if (_draft.TriggerAmount.HasValue && ev is "OnDamageDealt" or "OnHealed" + or "OnSPGained" or "OnSPSpent" or "OnSTGained" or "OnSTSpent" or "OnUnitMPSpent") + w.WriteNumber("Amount", _draft.TriggerAmount.Value); + + // DamageType + if (ev == "OnDamageDealt" && !string.IsNullOrEmpty(_draft.TriggerDamageType)) + w.WriteString("DamageType", _draft.TriggerDamageType); + + // CausedBy + if (ev == "OnUnitSentToDiscard" && !string.IsNullOrWhiteSpace(_draft.TriggerCause)) + w.WriteString("CausedBy", _draft.TriggerCause); + + // Stat + if (ev == "OnStatModified" && !string.IsNullOrEmpty(_draft.TriggerStat)) + w.WriteString("Stat", _draft.TriggerStat); + + w.WriteEndObject(); +} + +private void WriteEngineLogicGroup(System.Text.Json.Utf8JsonWriter w, LogicGroupDraft group) +{ + if (group.Rules.Count == 1 && !group.Groups.Any()) + { + WriteEngineCondition(w, group.Rules[0]); + return; + } + w.WriteStartObject(); + w.WriteString("$type", group.Logic); + w.WriteStartArray("Conditions"); + foreach (var rule in group.Rules) WriteEngineCondition(w, rule); + foreach (var sub in group.Groups) WriteEngineLogicGroup(w, sub); + w.WriteEndArray(); + w.WriteEndObject(); +} + +private void WriteEngineCondition(System.Text.Json.Utf8JsonWriter w, CondDraft cond) +{ + // Map draft domain/field to engine $type + var typeStr = MapConditionType(cond.Domain, cond.Field); + w.WriteStartObject(); + w.WriteString("$type", typeStr); + if (cond.Subject == "Target") w.WriteString("Subject", "Target"); + // Write field-specific params + WriteConditionParams(w, cond, typeStr); + w.WriteEndObject(); +} + +private static string MapConditionType(string domain, string field) => field switch +{ + "HasGenus" => "HasGenus", + "HasAbility" => "HasAbility", + "HealthBelow" => "HealthBelow", + "HealthAbove" => "HealthAbove", + "SPAtLeast" => "SPAtLeast", + "SPAtMost" => "SPAtMost", + "STAtLeast" => "STAtLeast", + "STAtMost" => "STAtMost", + "HandSizeAtLeast" => "HandSizeAtLeast", + "HandSizeAtMost" => "HandSizeAtMost", + "DeckSizeAtLeast" => "DeckSizeAtLeast", + "DiscardSizeAtLeast" => "DiscardSizeAtLeast", + "IsOwnTurn" => "IsOwnTurn", + "IsOpponentTurn" => "IsOpponentTurn", + "TileAffinityMatches" => "TileAffinityMatches", + "TileIsOccupied" => "TileIsOccupied", + "TileIsUnoccupied" => "TileIsUnoccupied", + "UnitCountOnBattlefield" => "UnitCountOnBattlefield", + "CardInZone" => "CardInZone", + "IsAdjacentTo" => "IsAdjacentTo", + "WithinRangeOf" => "WithinRangeOf", + "IsOnTileWithAffinity" => "IsOnTileWithAffinity", + "MovementTypeIs" => "MovementTypeIs", + "IsCurrentlyMoving" => "IsCurrentlyMoving", + _ => field, +}; + +private static void WriteConditionParams(System.Text.Json.Utf8JsonWriter w, CondDraft cond, string typeStr) +{ + var val = cond.Value; + switch (typeStr) + { + case "HasGenus": if (!string.IsNullOrEmpty(val)) w.WriteString("Tag", val); break; + case "HasAbility": if (!string.IsNullOrEmpty(val)) w.WriteString("AbilityRef", val); break; + case "HealthBelow": + case "HealthAbove": if (int.TryParse(val, out var hi)) w.WriteNumber("N", hi); break; + case "SPAtLeast": case "SPAtMost": + case "STAtLeast": case "STAtMost": + case "HandSizeAtLeast": case "HandSizeAtMost": + case "DeckSizeAtLeast": case "DiscardSizeAtLeast": + if (int.TryParse(val, out var ni)) w.WriteNumber("N", ni); break; + case "TileAffinityMatches": + case "IsOnTileWithAffinity": w.WriteString("Affinity", val); break; + case "MovementTypeIs": w.WriteString("MovementType", val); break; + case "IsAdjacentTo": w.WriteString("Ownership", cond.Comparator); break; + } +} + +private void WriteEngineAction(System.Text.Json.Utf8JsonWriter w, ActionDraft action) +{ + w.WriteStartObject(); + + // Target selector + w.WriteStartObject("Target"); + w.WriteString("Scope", action.Scope); + w.WriteString("Type", action.TargetType); + w.WriteString("Ownership", action.Ownership); + w.WriteStartObject("Count"); + w.WriteNumber("N", action.Count); + if (action.All) w.WriteBoolean("All", true); + if (action.UpTo) w.WriteBoolean("UpTo", true); + w.WriteEndObject(); + w.WriteEndObject(); + + // Per-action conditions + if (action.Conditions.Rules.Any() || action.Conditions.Groups.Any()) + { + w.WriteStartArray("Conditions"); + WriteEngineLogicGroup(w, action.Conditions); + w.WriteEndArray(); + } + + // Duration + if (!string.IsNullOrEmpty(action.DurationType)) + { + w.WriteStartObject("Duration"); + w.WriteString("DurationType", action.DurationType); + if (action.DurationType == "ForNTurns" && action.DurationN.HasValue) + w.WriteNumber("N", action.DurationN.Value); + if (!string.IsNullOrEmpty(action.DurationPlayerScope)) + w.WriteString("PlayerScope", action.DurationPlayerScope); + w.WriteEndObject(); + } + + // ChooseOne branches (if any) + if (action.Branches.Any()) + { + w.WriteStartObject("ChooseOne"); + w.WriteStartArray("Branches"); + foreach (var b in action.Branches) + { + w.WriteStartObject(); + w.WriteString("Label", b.Label); + w.WriteStartArray("Actions"); + w.WriteEndArray(); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + + // Effects + w.WriteStartArray("Effects"); + foreach (var eff in action.Effects) + WriteEngineEffect(w, eff); + w.WriteEndArray(); + + w.WriteEndObject(); +} + +private void WriteEngineEffect(System.Text.Json.Utf8JsonWriter w, EffectDraft eff) +{ + w.WriteStartObject(); + w.WriteString("$type", eff.TypeKey); + + var t = eff.TypeKey; + + // ValueExpr helper + void WriteAmount(string propName, int? fixedVal, string? refVal) + { + w.WriteStartObject(propName); + if (!string.IsNullOrEmpty(refVal)) w.WriteString("Ref", refVal); + else if (fixedVal.HasValue) w.WriteNumber("Fixed", fixedVal.Value); + else w.WriteNumber("Fixed", 0); + w.WriteEndObject(); + } + + if (t is "ModifyHealth" or "ModifyDefense" or "ModifyDamage" or "ModifyMP" + or "ModifyMinAttackRange" or "ModifyMaxAttackRange") + { + WriteAmount("Amount", eff.Amount, eff.AmountRef); + if (eff.StatModOp != "Add") w.WriteString("Operator", eff.StatModOp); + if ((t is "ModifyHealth" or "ModifyDefense" or "ModifyMP") && eff.StatTarget == "Max") + w.WriteString("StatTarget", "Max"); + } + else if (t == "SetAttackRange") + { + w.WriteNumber("Min", eff.RangeMin ?? 1); + w.WriteNumber("Max", eff.RangeMax ?? 1); + } + else if (t == "SetMovementType") + { + if (!string.IsNullOrEmpty(eff.StringParam)) + { + w.WriteStartObject("MovementType"); w.WriteString("$type", eff.StringParam); w.WriteEndObject(); + } + } + else if (t is "SetAffinity" or "SetBaseAffinity1" or "SetBaseAffinity2" or "PushAffinity" or "PushFinalAffinity") + { + w.WriteStartObject("Affinity"); + w.WriteString("Fixed", eff.StringParam ?? "Fire"); + w.WriteEndObject(); + } + else if (t.StartsWith("SetCan") || t == "SetAccumulatesSP") + { + w.WriteBoolean("Value", eff.BoolValue); + } + else if (t is "RemoveAbility" or "EnableAbility" or "DisableAbility") + { + w.WriteString("AbilityRef", eff.StringParam ?? ""); + } + else if (t is "AddGenus" or "RemoveGenus") + { + w.WriteString("Tag", eff.StringParam ?? ""); + } + else if (t == "ModifyCost") + { + if (eff.SpMod.HasValue) w.WriteNumber("Sp", eff.SpMod.Value); + if (eff.StMod.HasValue) w.WriteNumber("St", eff.StMod.Value); + } + else if (t is "ModifySP" or "ModifySPAccumulation" or "ModifyST" or "ModifyCardsDrawnPerTurn") + { + WriteAmount("Amount", eff.Amount, eff.AmountRef); + } + else if (t is "DrawCards" or "DiscardCards" or "RevealCards") + { + w.WriteNumber("N", eff.CountN ?? 1); + w.WriteString("Player", eff.TargetPlayer); + } + else if (t is "ReturnToDeck" or "PlaceOnDeck") + { + w.WriteString("Position", eff.DeckPosition); + } + else if (t == "ShuffleDeck") + { + w.WriteString("Player", eff.TargetPlayer); + } + else if (t == "ReturnToBattlefield") + { + if (!string.IsNullOrEmpty(eff.Controller)) w.WriteString("Controller", eff.Controller); + } + else if (t == "ChannelCard") + { + w.WriteBoolean("PayCost", eff.PayCost); + if (eff.CostMultiplier.HasValue) w.WriteNumber("CostMultiplier", eff.CostMultiplier.Value); + } + else if (t is "DealDamage" or "Heal" or "DealDamageToSelf") + { + WriteAmount("Amount", eff.Amount, eff.AmountRef); + if (eff.BypassDefense) w.WriteBoolean("BypassDefense", true); + } + else if (t is "DOT" or "HOT") + { + WriteAmount("Amount", eff.Amount, null); + w.WriteStartObject("Duration"); + w.WriteString("DurationType", eff.DurationType); + if (eff.DurationType == "ForNTurns" && eff.DurationN.HasValue) w.WriteNumber("N", eff.DurationN.Value); + w.WriteEndObject(); + if (t == "DOT" && eff.BypassDefense) w.WriteBoolean("BypassDefense", true); + } + else if (t == "PreventNextDamage") + { + if (eff.Amount.HasValue) WriteAmount("MaxAmount", eff.Amount, eff.AmountRef); + } + else if (t == "SetHealthMinimum") + { + w.WriteNumber("Minimum", eff.Minimum ?? 1); + } + else if (t is "PushUnit" or "PullUnit") + { + w.WriteNumber("Tiles", eff.Tiles ?? 1); + w.WriteNumber("BlockedDamage", eff.BlockedDamage ?? 0); + } + else if (t == "DisplaceUnit") + { + w.WriteNumber("Tiles", eff.Tiles ?? 1); + w.WriteString("Direction", eff.Direction); + } + else if (t == "TakeControl") + { + w.WriteStartObject("Duration"); + w.WriteString("DurationType", eff.DurationType); + w.WriteEndObject(); + } + else if (t == "GrantMovementControl") + { + w.WriteNumber("N", eff.CountN ?? 1); + } + else if (t == "GrantAdditionalAttack") + { + w.WriteNumber("N", eff.AttackCount); + } + else if (t == "SetStatModMultiplier") + { + w.WriteString("Stat", eff.StatName ?? ""); + w.WriteNumber("Multiplier", eff.Multiplier); + } + else if (t == "SetFixedSacrificeReturn") + { + w.WriteNumber("StAmount", eff.StAmount ?? 0); + } + else if (t == "SummonToken" && !string.IsNullOrEmpty(eff.TokenJson)) + { + w.WritePropertyName("TokenDefJson"); + var doc = System.Text.Json.JsonDocument.Parse(eff.TokenJson); + doc.WriteTo(w); + } + + w.WriteEndObject(); +} + +// ══════════════════════════════════════════════════════════════════ +// VALIDATION +// ══════════════════════════════════════════════════════════════════ + +private List Validate() +{ + var errs = new List(); + if (string.IsNullOrWhiteSpace(_draft.Name)) + errs.Add(new("Error", "Name is required.")); + if (_draft.Type == "Active" && _draft.RangeMin > _draft.RangeMax) + errs.Add(new("Error", "Range Min must be ≤ Range Max.")); + if (_draft.Type == "Triggered") + { + if (string.IsNullOrEmpty(_draft.TriggerEvent)) + errs.Add(new("Error", "Trigger event is required.")); + if (!_draft.SourceZoneGate.Any()) + errs.Add(new("Warning", "No Source Zone Gate set. Trigger fires from any zone (legacy behaviour).")); + } + if (_draft.Type == "Aura" && _draft.AuraRangeMin > _draft.AuraRangeMax) + errs.Add(new("Error", "Aura Range Min must be ≤ Range Max.")); + if (!_draft.Actions.Any() && _draft.Type != "Passive") + errs.Add(new("Warning", "No actions defined — ability will have no effect.")); + foreach (var (action, i) in _draft.Actions.Select((a, i) => (a, i))) + { + if (!action.Effects.Any() && !action.Branches.Any()) + errs.Add(new("Warning", $"Action {i+1} has no effects or branches.")); + // Loop risk: triggered ability that fires on an event it can produce + if (_draft.Type == "Triggered") + { + var potentialLoopEvents = action.Effects + .Select(e => e.TypeKey) + .Any(k => k is "DealDamage" or "Heal" or "ModifyDamage" or "ModifyHealth"); + var sensitiveEvents = _draft.TriggerEvent is "OnDamageDealt" or "OnHealed" or "OnStatModified"; + if (potentialLoopEvents && sensitiveEvents) + errs.Add(new("Warning", $"Action {i+1}: potential loop — triggered by damage/heal and also applies damage/stat effects. Consider adding TriggerLimitPerTurn.")); + } + foreach (var (eff, ei) in action.Effects.Select((e,i)=>(e,i))) + { + if (eff.TypeKey is "SummonToken" && string.IsNullOrWhiteSpace(eff.TokenJson)) + errs.Add(new("Error", $"Action {i+1}, Effect {ei+1}: SummonToken requires Token JSON.")); + if (eff.TypeKey == "SetStatModMultiplier" && string.IsNullOrWhiteSpace(eff.StatName)) + errs.Add(new("Warning", $"Action {i+1}, Effect {ei+1}: SetStatModMultiplier missing Stat name.")); + } + } + foreach (var (cost, ci) in _draft.Costs.Select((c,i)=>(c,i))) + { + if (cost.TypeStr is "DiscardFromHand" or "SendSpiritFromBattlefieldToDiscard" or "DealDamageToOwnSpirit" + && string.IsNullOrEmpty(cost.PickMode)) + errs.Add(new("Info", $"Cost {ci+1} ({cost.TypeStr}) has no PickMode — engine will auto-pick first valid candidate.")); + } + return errs; +} + +// ══════════════════════════════════════════════════════════════════ +// MERMAID DIAGRAM +// ══════════════════════════════════════════════════════════════════ + +private string BuildMermaidDiagram() +{ + var sb = new System.Text.StringBuilder(); + sb.AppendLine("graph TD"); + sb.AppendLine($" START([\"⚡ {EscapeMermaid(_draft.Name)}\"])"); + sb.AppendLine(" style START fill:#4a0070,color:#fff"); + + if (_draft.Type == "Triggered") + { + sb.AppendLine($" TRIGGER[\"{_draft.TriggerEvent}\"]"); + sb.AppendLine(" style TRIGGER fill:#2a006a,color:#ddf"); + sb.AppendLine(" START --> TRIGGER"); + if (_draft.SourceZoneGate.Any()) + { + var zones = string.Join("/", _draft.SourceZoneGate); + sb.AppendLine($" ZONE{{\"Zone Gate:\\n{zones}\"}}"); + sb.AppendLine(" style ZONE fill:#003050,color:#adf"); + sb.AppendLine(" TRIGGER --> ZONE"); + } + } + + var hasConds = _draft.ActivationConditions.Rules.Any() || _draft.ActivationConditions.Groups.Any(); + string prevId = _draft.Type == "Triggered" + ? (_draft.SourceZoneGate.Any() ? "ZONE" : "TRIGGER") + : "START"; + + if (hasConds) + { + sb.AppendLine($" COND{{\"Conditions ({_draft.ActivationConditions.Logic})\"}}"); + sb.AppendLine(" style COND fill:#00305a,color:#adf"); + sb.AppendLine($" {prevId} --> COND"); + prevId = "COND"; + } + + if (_draft.Type == "Active" && _draft.Costs.Any()) + { + sb.AppendLine(" COSTS[\"Costs\"]"); + sb.AppendLine(" style COSTS fill:#5a3000,color:#fda"); + sb.AppendLine($" {prevId} --> COSTS"); + prevId = "COSTS"; + } + + for (int i = 0; i < _draft.Actions.Count; i++) + { + var action = _draft.Actions[i]; + var aId = $"A{i}"; + sb.AppendLine($" {aId}[\"{action.Scope}: {action.TargetType} ({action.Ownership})\"]"); + sb.AppendLine($" style {aId} fill:#004a30,color:#afa"); + sb.AppendLine($" {prevId} --> {aId}"); + for (int j = 0; j < action.Effects.Count; j++) + { + var eff = action.Effects[j]; + var eId = $"E{i}_{j}"; + sb.AppendLine($" {eId}([\"{EscapeMermaid(eff.TypeKey)}\"])"); + sb.AppendLine($" style {eId} fill:#5a0020,color:#faa"); + sb.AppendLine($" {aId} --> {eId}"); + } + prevId = aId; + } + + return sb.ToString(); +} + +private static string EscapeMermaid(string? s) => + (s ?? "").Replace("\"", "'").Replace("<", "<").Replace(">", ">"); + +// ══════════════════════════════════════════════════════════════════ +// SAMPLE PRESETS +// ══════════════════════════════════════════════════════════════════ + +private void LoadActiveSample() +{ + _draft = new AbilityDraft + { + Name = "Pulse Lance", + Description = "Deal 3 damage to a target enemy unit.", + Type = "Active", + RangeMin = 1, + RangeMax = 3, + Costs = [new CostDraft { TypeStr = "SpiritPoints", Amount = 2 }], + Actions = + [ + new ActionDraft + { + Scope = "Battlefield", + TargetType = "Unit", + Ownership = "Enemy", + Count = 1, + Effects = [new EffectDraft { TypeKey = "DealDamage", Amount = 3 }], + } + ], + }; + Compile(); +} + +private void LoadTriggeredSample() +{ + _draft = new AbilityDraft + { + Name = "Ashwake Response", + Description = "When an ally spirit enters the battlefield, heal it for 2.", + Type = "Triggered", + TriggerFamily = "Unit — Lifecycle", + TriggerEvent = "OnUnitEnterBattlefield", + TriggerOwnership = "Ally", + TriggerUnitType = "Spirit", + SourceZoneGate = ["Battlefield"], + TriggerLimitMode = "PerTurn", + TriggerLimitAmount = 1, + Actions = + [ + new ActionDraft + { + Scope = "Battlefield", + TargetType = "Unit", + Ownership = "Target", + Count = 1, + Effects = [new EffectDraft { TypeKey = "Heal", Amount = 2 }], + } + ], + }; + Compile(); +} +} diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index 78c4c94..32f0ea3 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -36,6 +36,9 @@ public static class AbilitySystem // Runtime limiter for Triggered abilities: (source instance, ability key, turn) -> count private static readonly Dictionary<(string SourceInstanceId, string AbilityKey, int Turn), int> _triggerCountsPerTurn = new(); + // Per-game trigger limiter: (session+source instance, ability key) -> count; never resets mid-game + private static readonly Dictionary<(string SessionAndSource, string AbilityKey), int> _triggerCountsPerGame = new(); + // Transient prevention markers. private static readonly Dictionary _preventNextDamageByUnit = new(); private static readonly HashSet _preventDeathUnits = new(); @@ -106,11 +109,14 @@ public static class AbilitySystem if (!ValidateSourceActivationConditions(def, ctx, source)) throw new GameException("ABILITY_CONDITION_NOT_MET"); - if (def.Cost is { Length: > 0 }) - PayCost(def.Cost, ctx); - source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1; + if (def.Cost is { Length: > 0 }) + { + bool paused = PayCosts(def.Cost, ctx, abilityIndex, def.Actions, def.Range, def.Duration); + if (paused) return state; // waiting for client cost pick + } + ExecuteActions(def.Actions, ctx, clientTargets, requireClientTargets: true, activationRange: def.Range, forceDuration: def.Duration); return state; @@ -185,56 +191,98 @@ public static class AbilitySystem } /// - /// Scans every battlefield unit for Triggered abilities matching the occurrence - /// and fires each matching one. Called inline from GameEngine mutation methods. + /// Scans every battlefield unit (and, when SourceZoneGate is set, hand/discard/deck cards) + /// for Triggered abilities matching the occurrence and fires each matching one. + /// Called inline from GameEngine mutation methods. /// public static GameState FireTrigger(GameState state, TriggerOccurrence occurrence) { foreach (var (ownerId, player) in state.Players) { - var units = player.Field.OfType().ToList(); // snapshot - foreach (var unit in units) - { - // SetCanUseAbility(false) suppresses triggered ability firing for this unit. - if (!unit.CanUseAbility) continue; + // Build the set of cards to scan for triggered abilities. + // Always include battlefield units. Cards with SourceZoneGate including + // Hand/Discard/Deck are scanned from those zones too. + var scanTargets = new List<(CardInstance Card, string Zone)>(); + foreach (var fc in player.Field.OfType()) + scanTargets.Add((fc, "Battlefield")); + foreach (var c in player.Hand) + scanTargets.Add((c, "Hand")); + foreach (var c in player.Discard) + scanTargets.Add((c, "Discard")); + foreach (var c in player.Deck) + scanTargets.Add((c, "Deck")); - var abilities = ParseAbilities(unit.AbilitiesJson); + foreach (var (card, zone) in scanTargets) + { + // SetCanUseAbility(false) suppresses triggered ability firing. + if (card is FieldCard fc2 && !fc2.CanUseAbility) continue; + + var abilities = ParseAbilities(card.AbilitiesJson); for (int i = 0; i < abilities.Length; i++) { var def = abilities[i]; if (def.Type != AbilityType.Triggered) continue; if (def.TriggerEvent is null) continue; - if (!TriggerMatches(def.TriggerEvent, occurrence, state, ownerId, unit)) continue; + + // ── SourceZoneGate ──────────────────────────────────────── + // When a gate is configured, only fire when the card is in one of the + // specified zones. When no gate is configured, apply the legacy rule: + // only battlefield cards fire (skip non-battlefield cards). + if (def.SourceZoneGate is { Length: > 0 }) + { + if (!def.SourceZoneGate.Contains(zone, StringComparer.OrdinalIgnoreCase)) + continue; + } + else + { + // No gate → legacy: only battlefield cards trigger. + if (zone != "Battlefield") continue; + } + + if (!TriggerMatches(def.TriggerEvent, occurrence, state, ownerId, + card is FieldCard fc3 ? fc3 : null)) continue; var ctx = new AbilityContext { State = state, ActorId = ownerId, - Source = unit, + Source = card, EventData = occurrence.Data, }; if (def.ActivationConditions is { Length: > 0 }) - if (def.ActivationConditions.Any(c => !EvaluateCondition(c, ctx, unit))) + if (def.ActivationConditions.Any(c => !EvaluateCondition(c, ctx, card))) continue; + // ── Per-turn limit ──────────────────────────────────────── if (def.TriggerLimitPerTurn is > 0) { var abilityKey = !string.IsNullOrWhiteSpace(def.Name) ? def.Name! : $"idx:{i}"; - var key = (unit.InstanceId, abilityKey, state.TurnNumber); + var key = (card.InstanceId, abilityKey, state.TurnNumber); _triggerCountsPerTurn.TryGetValue(key, out var used); if (used >= def.TriggerLimitPerTurn.Value) continue; _triggerCountsPerTurn[key] = used + 1; } + // ── Per-game limit ──────────────────────────────────────── + if (def.TriggerLimitPerGame is > 0) + { + var abilityKey = !string.IsNullOrWhiteSpace(def.Name) ? def.Name! : $"idx:{i}"; + var gameKey = ($"{state.SessionId}:{card.InstanceId}", abilityKey); + _triggerCountsPerGame.TryGetValue(gameKey, out var usedGame); + if (usedGame >= def.TriggerLimitPerGame.Value) + continue; + _triggerCountsPerGame[gameKey] = usedGame + 1; + } + // If any action needs a human pick, pause and request client input. if (def.Actions.Any(ActionNeedsClientTargets)) { state.PendingTriggeredTarget = new PendingTriggeredTarget { ActorId = ownerId, - SourceInstanceId = unit.InstanceId, + SourceInstanceId = card.InstanceId, AbilityName = def.Name ?? "Triggered Ability", ActionsJson = JsonSerializer.Serialize(def.Actions, _jsonOpts), RangeJson = def.Range is not null @@ -370,81 +418,240 @@ public static class AbilitySystem // ── Cost payment ────────────────────────────────────────────────────────── - private static void PayCost(CostEntry[] costs, AbilityContext ctx) + /// + /// Pays all costs in that can be auto-resolved. + /// When an interactive pick-mode cost is encountered, stores + /// on .State and returns true (caller must stop and return state). + /// Returns false when all costs are paid without pausing. + /// + private static bool PayCosts( + CostEntry[] costs, + AbilityContext ctx, + int abilityIndex, + Models.Action[] pendingActions, + AbilityRange? range, + DurationModel? forceDuration) { var player = ctx.State.Players[ctx.ActorId]; - foreach (var cost in costs) + for (int ci = 0; ci < costs.Length; ci++) { - switch (cost.Type) + var cost = costs[ci]; + + // Interactive costs: pause for player pick. + if (cost.PickMode is CostPickMode.SelfPick or CostPickMode.EnemySeePick + or CostPickMode.EnemyRandomPick or CostPickMode.EnemyPick) { - case CostType.SpiritPoints: - if (player.CurrentSp < cost.Amount) throw new GameException("INSUFFICIENT_SP"); - player.CurrentSp -= cost.Amount; - break; - - case CostType.SacrificeTokens: - if (player.CurrentSt < cost.Amount) throw new GameException("INSUFFICIENT_ST"); - player.CurrentSt -= cost.Amount; - break; - - case CostType.DiscardFromHand: + // Only DiscardFromHand / SendSpiritFromBattlefieldToDiscard / DealDamageToOwnSpirit + // support interactive pick. Auto-resolve all others even if PickMode is set. + if (cost.Type is CostType.DiscardFromHand + or CostType.SendSpiritFromBattlefieldToDiscard + or CostType.DealDamageToOwnSpirit) { - var candidates = player.Hand - .Where(c => cost.Filters is null || FiltersMatch(cost.Filters, c, ctx)) - .Take(cost.Amount).ToList(); - if (candidates.Count < cost.Amount) - throw new GameException("INSUFFICIENT_CARDS_TO_DISCARD"); - foreach (var c in candidates) { player.Hand.Remove(c); player.Discard.Add(c); } - break; - } + // Determine who picks. + var pickerActorId = cost.PickMode is CostPickMode.SelfPick + ? ctx.ActorId + : ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId; - case CostType.MillTopOfDeck: - for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++) + // Remaining costs after this one. + var remaining = costs.Skip(ci + 1).ToArray(); + + ctx.State.PendingCostPick = new PendingCostPick { - var top = player.Deck[^1]; - player.Deck.RemoveAt(player.Deck.Count - 1); - player.Discard.Add(top); - } - break; - - case CostType.MillBottomOfDeck: - for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++) - { - var bottom = player.Deck[0]; - player.Deck.RemoveAt(0); - player.Discard.Add(bottom); - } - break; - - case CostType.DealDamageToOwnArchSpirit: - if (player.ArchSpirit is null) throw new GameException("NO_ARCHSPIRIT"); - ApplyDamageToUnit(player.ArchSpirit, cost.Amount, bypassDefense: false, ctx); - break; - - case CostType.DealDamageToOwnSpirit: - { - var spirit = player.Field.OfType() - .FirstOrDefault(f => !f.IsLeader - && (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx))); - if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST"); - ApplyDamageToUnit(spirit, cost.Amount, bypassDefense: false, ctx); - break; - } - - case CostType.SendSpiritFromBattlefieldToDiscard: - { - var spirit = player.Field.OfType() - .FirstOrDefault(f => !f.IsLeader - && (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx))); - if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST"); - ctx.State.Board?.RemoveUnit(spirit.InstanceId); - player.Field.Remove(spirit); - player.Discard.Add(spirit); - break; + ActorId = ctx.ActorId, + SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty, + AbilityIndex = abilityIndex, + PickerActorId = pickerActorId, + CostType = cost.Type.ToString(), + Amount = cost.Amount, + PickMode = cost.PickMode.ToString()!, + FiltersJson = cost.Filters is not null + ? JsonSerializer.Serialize(cost.Filters, _jsonOpts) : null, + RemainingCostsJson = JsonSerializer.Serialize(remaining, _jsonOpts), + ActionsJson = JsonSerializer.Serialize(pendingActions, _jsonOpts), + RangeJson = range is not null + ? JsonSerializer.Serialize(range, _jsonOpts) : null, + ForceDurationJson = forceDuration is not null + ? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null, + }; + return true; // paused } } + + // Auto-resolve the cost. + PaySingleCost(cost, player, ctx); } + return false; // all paid + } + + private static void PaySingleCost(CostEntry cost, PlayerState player, AbilityContext ctx) + { + switch (cost.Type) + { + case CostType.SpiritPoints: + if (player.CurrentSp < cost.Amount) throw new GameException("INSUFFICIENT_SP"); + player.CurrentSp -= cost.Amount; + break; + + case CostType.SacrificeTokens: + if (player.CurrentSt < cost.Amount) throw new GameException("INSUFFICIENT_ST"); + player.CurrentSt -= cost.Amount; + break; + + case CostType.DiscardFromHand: + { + var pool = player.Hand + .Where(c => cost.Filters is null || FiltersMatch(cost.Filters, c, ctx)) + .ToList(); + if (cost.PickMode == CostPickMode.Random) + pool = pool.OrderBy(_ => Random.Shared.Next()).ToList(); + var candidates = pool.Take(cost.Amount).ToList(); + if (candidates.Count < cost.Amount) + throw new GameException("INSUFFICIENT_CARDS_TO_DISCARD"); + foreach (var c in candidates) { player.Hand.Remove(c); player.Discard.Add(c); } + break; + } + + case CostType.MillTopOfDeck: + for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++) + { + var top = player.Deck[^1]; + player.Deck.RemoveAt(player.Deck.Count - 1); + player.Discard.Add(top); + } + break; + + case CostType.MillBottomOfDeck: + for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++) + { + var bottom = player.Deck[0]; + player.Deck.RemoveAt(0); + player.Discard.Add(bottom); + } + break; + + case CostType.DealDamageToOwnArchSpirit: + if (player.ArchSpirit is null) throw new GameException("NO_ARCHSPIRIT"); + ApplyDamageToUnit(player.ArchSpirit, cost.Amount, bypassDefense: false, ctx); + break; + + case CostType.DealDamageToOwnSpirit: + { + var spirit = player.Field.OfType() + .FirstOrDefault(f => !f.IsLeader + && (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx))); + if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST"); + ApplyDamageToUnit(spirit, cost.Amount, bypassDefense: false, ctx); + break; + } + + case CostType.SendSpiritFromBattlefieldToDiscard: + { + var spirit = player.Field.OfType() + .FirstOrDefault(f => !f.IsLeader + && (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx))); + if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST"); + ctx.State.Board?.RemoveUnit(spirit.InstanceId); + player.Field.Remove(spirit); + player.Discard.Add(spirit); + break; + } + } + } + + /// + /// Resumes an Active ability after the picker has submitted their cost-pick selections. + /// Called by GameCostPickHandler. + /// + public static GameState ResumeCostPick( + GameState state, + string actorId, + string requestId, + IReadOnlyList selectedInstanceIds) + { + var pending = state.PendingCostPick + ?? throw new GameException("NO_PENDING_COST_PICK"); + + if (pending.RequestId != requestId) + throw new GameException("REQUEST_ID_MISMATCH"); + + // Allow both the actor and the designated picker to respond. + if (actorId != pending.ActorId && actorId != pending.PickerActorId) + throw new GameException("NOT_YOUR_COST_PICK"); + + state.PendingCostPick = null; + + var player = state.Players[pending.ActorId]; + + // Validate and pay the interactive cost using the client-selected IDs. + switch (pending.CostType) + { + case nameof(CostType.DiscardFromHand): + { + var toDiscard = selectedInstanceIds + .Select(id => player.Hand.FirstOrDefault(c => c.InstanceId == id)) + .OfType() + .Take(pending.Amount) + .ToList(); + if (toDiscard.Count < pending.Amount) + throw new GameException("INVALID_COST_PICK_SELECTION"); + foreach (var c in toDiscard) { player.Hand.Remove(c); player.Discard.Add(c); } + break; + } + case nameof(CostType.SendSpiritFromBattlefieldToDiscard): + { + var picked = selectedInstanceIds.FirstOrDefault() + ?? throw new GameException("INVALID_COST_PICK_SELECTION"); + var spirit = player.Field.OfType() + .FirstOrDefault(f => f.InstanceId == picked) + ?? throw new GameException("INVALID_COST_PICK_SELECTION"); + state.Board?.RemoveUnit(spirit.InstanceId); + player.Field.Remove(spirit); + player.Discard.Add(spirit); + break; + } + case nameof(CostType.DealDamageToOwnSpirit): + { + var picked = selectedInstanceIds.FirstOrDefault() + ?? throw new GameException("INVALID_COST_PICK_SELECTION"); + var spirit = player.Field.OfType() + .FirstOrDefault(f => f.InstanceId == picked) + ?? throw new GameException("INVALID_COST_PICK_SELECTION"); + // Temporary context for damage application. + var dmgCtx = new AbilityContext { State = state, ActorId = pending.ActorId }; + ApplyDamageToUnit(spirit, pending.Amount, bypassDefense: false, dmgCtx); + break; + } + } + + // Find the source unit (may have left the field while waiting — skip if gone). + var source = state.Players.Values + .SelectMany(p => p.Field).OfType() + .FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId); + if (source is null) return state; + + var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source }; + + // Pay any remaining non-interactive costs. + var remainingCosts = JsonSerializer.Deserialize( + pending.RemainingCostsJson, _jsonOpts) ?? []; + foreach (var c in remainingCosts) + PaySingleCost(c, player, ctx); + + // Execute the ability actions. + var actions = JsonSerializer.Deserialize( + pending.ActionsJson, _jsonOpts) ?? []; + DurationModel? forceDuration = pending.ForceDurationJson is not null + ? JsonSerializer.Deserialize(pending.ForceDurationJson, _jsonOpts) + : null; + AbilityRange? range = pending.RangeJson is not null + ? JsonSerializer.Deserialize(pending.RangeJson, _jsonOpts) + : null; + + ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: false, + activationRange: range, forceDuration: forceDuration); + + return state; } // ── Action execution ────────────────────────────────────────────────────── @@ -842,50 +1049,83 @@ public static class AbilitySystem // ── §5.1 Stat modification ───────────────────────────────────────── case ModifyHealthEffect mh when target is CardInstance ci: { - int amt = ResolveValue(mh.Amount, ctx); + int raw = ResolveValue(mh.Amount, ctx); if (mh.StatTarget == StatTarget.Current) { - ci.CurrentHealth = (ci.CurrentHealth ?? 0) + amt; - if (ci.MaxHealth.HasValue) - ci.CurrentHealth = Math.Min(ci.CurrentHealth.Value, ci.MaxHealth.Value); + int cur = ci.CurrentHealth ?? 0; + int newVal = ApplyStatOperator(cur, raw, mh.Operator); + if (ci.MaxHealth.HasValue) newVal = Math.Min(newVal, ci.MaxHealth.Value); + int delta = newVal - cur; + ci.CurrentHealth = newVal; if (ci.CurrentHealth <= 0) KillUnit(ci, ctx, ctx.Source?.InstanceId); + TrackEffect(new ModifyHealthEffect { Amount = V(-delta), StatTarget = mh.StatTarget }, + ci.InstanceId, duration, ctx); } else { - ci.MaxHealth = (ci.MaxHealth ?? 0) + amt; + int cur = ci.MaxHealth ?? 0; + int newVal = Math.Max(0, ApplyStatOperator(cur, raw, mh.Operator)); + int delta = newVal - cur; + ci.MaxHealth = newVal; if (ci.CurrentHealth > ci.MaxHealth) ci.CurrentHealth = ci.MaxHealth; + TrackEffect(new ModifyHealthEffect { Amount = V(-delta), StatTarget = mh.StatTarget }, + ci.InstanceId, duration, ctx); } - TrackEffect(new ModifyHealthEffect { Amount = V(-amt), StatTarget = mh.StatTarget }, - ci.InstanceId, duration, ctx); break; } case ModifyDefenseEffect md when target is CardInstance ci: { - int amt = ResolveValue(md.Amount, ctx); + int raw = ResolveValue(md.Amount, ctx); if (md.StatTarget == StatTarget.Current) - ci.CurrentDefense = Math.Max(0, (ci.CurrentDefense ?? 0) + amt); + { + int cur = ci.CurrentDefense ?? 0; + int newVal = Math.Max(0, ApplyStatOperator(cur, raw, md.Operator)); + int delta = newVal - cur; + ci.CurrentDefense = newVal; + TrackEffect(new ModifyDefenseEffect { Amount = V(-delta), StatTarget = md.StatTarget }, + ci.InstanceId, duration, ctx); + } else - ci.MaxDefense = (ci.MaxDefense ?? 0) + amt; - TrackEffect(new ModifyDefenseEffect { Amount = V(-amt), StatTarget = md.StatTarget }, - ci.InstanceId, duration, ctx); + { + int cur = ci.MaxDefense ?? 0; + int newVal = Math.Max(0, ApplyStatOperator(cur, raw, md.Operator)); + int delta = newVal - cur; + ci.MaxDefense = newVal; + TrackEffect(new ModifyDefenseEffect { Amount = V(-delta), StatTarget = md.StatTarget }, + ci.InstanceId, duration, ctx); + } break; } case ModifyDamageEffect mdam when target is CardInstance ci: { - int amt = ResolveValue(mdam.Amount, ctx); - ci.Damage = Math.Max(0, (ci.Damage ?? 0) + amt); - TrackEffect(new ModifyDamageEffect { Amount = V(-amt) }, ci.InstanceId, duration, ctx); + int cur = ci.Damage ?? 0; + int newVal = Math.Max(0, ApplyStatOperator(cur, ResolveValue(mdam.Amount, ctx), mdam.Operator)); + int delta = newVal - cur; + ci.Damage = newVal; + TrackEffect(new ModifyDamageEffect { Amount = V(-delta) }, ci.InstanceId, duration, ctx); break; } case ModifyMPEffect mmp when target is CardInstance ci: { - int amt = ResolveValue(mmp.Amount, ctx); + int raw = ResolveValue(mmp.Amount, ctx); if (mmp.StatTarget == StatTarget.Current && ci is FieldCard fc) - fc.CurrentMp = Math.Max(0, fc.CurrentMp + amt); + { + int cur = fc.CurrentMp; + int newVal = Math.Max(0, ApplyStatOperator(cur, raw, mmp.Operator)); + int delta = newVal - cur; + fc.CurrentMp = newVal; + TrackEffect(new ModifyMPEffect { Amount = V(-delta), StatTarget = mmp.StatTarget }, + ci.InstanceId, duration, ctx); + } else - ci.MaxMp = Math.Max(0, (ci.MaxMp ?? 0) + amt); - TrackEffect(new ModifyMPEffect { Amount = V(-amt), StatTarget = mmp.StatTarget }, - ci.InstanceId, duration, ctx); + { + int cur = ci.MaxMp ?? 0; + int newVal = Math.Max(0, ApplyStatOperator(cur, raw, mmp.Operator)); + int delta = newVal - cur; + ci.MaxMp = newVal; + TrackEffect(new ModifyMPEffect { Amount = V(-delta), StatTarget = mmp.StatTarget }, + ci.InstanceId, duration, ctx); + } break; } case SetMovementTypeEffect smt when target is CardInstance ci: @@ -908,19 +1148,21 @@ public static class AbilitySystem } case ModifyMinAttackRangeEffect mmar when target is CardInstance ci: { - int orig = ci.MinAttackRange ?? 0; - int newVal = Math.Max(0, orig + ResolveValue(mmar.Amount, ctx)); + int cur = ci.MinAttackRange ?? 0; + int newVal = Math.Max(0, ApplyStatOperator(cur, ResolveValue(mmar.Amount, ctx), mmar.Operator)); + int delta = newVal - cur; ci.MinAttackRange = newVal; - TrackEffect(new ModifyMinAttackRangeEffect { Amount = V(orig - newVal) }, + TrackEffect(new ModifyMinAttackRangeEffect { Amount = V(-delta) }, ci.InstanceId, duration, ctx); break; } case ModifyMaxAttackRangeEffect mmax when target is CardInstance ci: { - int orig = ci.MaxAttackRange ?? 1; - int newVal = Math.Max(0, orig + ResolveValue(mmax.Amount, ctx)); + int cur = ci.MaxAttackRange ?? 1; + int newVal = Math.Max(0, ApplyStatOperator(cur, ResolveValue(mmax.Amount, ctx), mmax.Operator)); + int delta = newVal - cur; ci.MaxAttackRange = newVal; - TrackEffect(new ModifyMaxAttackRangeEffect { Amount = V(orig - newVal) }, + TrackEffect(new ModifyMaxAttackRangeEffect { Amount = V(-delta) }, ci.InstanceId, duration, ctx); break; } @@ -2350,6 +2592,20 @@ public static class AbilitySystem // ── Value / affinity resolution ─────────────────────────────────────────── + /// + /// Applies a to a current stat value. + /// Returns the new value (pre-clamping). The caller stores delta = newVal - oldVal + /// so the reversal can be expressed as a simple Add(-delta). + /// + private static int ApplyStatOperator(int current, int amount, StatModOperator op) => op switch + { + StatModOperator.Subtract => current - amount, + StatModOperator.Multiply => current * amount, + StatModOperator.Divide => amount == 0 ? current : current / amount, + StatModOperator.Percent => current + current * amount / 100, + _ => current + amount, // Add (default) + }; + private static int ResolveValue(ValueExpr expr, AbilityContext ctx) { if (expr.Fixed.HasValue) return expr.Fixed.Value; diff --git a/Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs b/Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs index 6a5cb9b..83a1765 100644 --- a/Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs +++ b/Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs @@ -53,10 +53,24 @@ public sealed class AbilityDefinition /// /// Maximum number of times this Triggered ability may resolve per turn. - /// Null or <= 0 means unlimited. + /// Null or <= 0 means unlimited. /// public int? TriggerLimitPerTurn { get; set; } + /// + /// Maximum number of times this Triggered ability may resolve for the entire game. + /// Null or <= 0 means unlimited. + /// + public int? TriggerLimitPerGame { get; set; } + + /// + /// Restricts which zones the source card must be in for the trigger to be active. + /// Valid values: "Battlefield", "Hand", "Discard", "Deck". + /// Null or empty means the trigger fires regardless of the source card's zone. + /// Default behaviour (null) retains the existing battlefield-only scan. + /// + public string[]? SourceZoneGate { get; set; } + /// /// Optional display name shown in the admin tool and client ability list. /// Not required for game logic. diff --git a/Server/src/SOR.Game/Abilities/Models/Action.cs b/Server/src/SOR.Game/Abilities/Models/Action.cs index 2fb1d0a..bb3c15e 100644 --- a/Server/src/SOR.Game/Abilities/Models/Action.cs +++ b/Server/src/SOR.Game/Abilities/Models/Action.cs @@ -113,16 +113,40 @@ public enum CostType DealDamageToOwnSpirit, } +/// +/// How the player(s) resolve the selection for an interactive cost (e.g. DiscardFromHand). +/// Null / absent: server auto-resolves (picks first N valid candidates). +/// +public enum CostPickMode +{ + /// Server picks randomly from valid candidates. + Random, + /// Controlling player sees and picks which cards to pay. + SelfPick, + /// Opponent picks on behalf of the controlling player (sees all options). + EnemySeePick, + /// Opponent picks randomly from the controlling player's valid candidates. + EnemyRandomPick, + /// Opponent has free choice of which cards the controlling player pays. + EnemyPick, +} + /// /// A single cost element for an Active ability. /// Multiple CostEntry items must all be paid simultaneously before the ability resolves. /// public sealed class CostEntry { - public CostType Type { get; set; } - public int Amount { get; set; } = 1; + public CostType Type { get; set; } + public int Amount { get; set; } = 1; /// Optional filter for targeted costs (e.g. "Discard a Spirit card from hand"). - public Filter[]? Filters { get; set; } + public Filter[]? Filters { get; set; } + /// + /// When set, the cost resolution is interactive: a player (controlling or opponent) + /// is prompted to pick which specific cards/units satisfy the cost. + /// Null = auto-resolve (engine picks first N matching candidates). + /// + public CostPickMode? PickMode { get; set; } } // ── Ability range ───────────────────────────────────────────────────────────── diff --git a/Server/src/SOR.Game/Abilities/Models/Effects.cs b/Server/src/SOR.Game/Abilities/Models/Effects.cs index 307f2e7..233e154 100644 --- a/Server/src/SOR.Game/Abilities/Models/Effects.cs +++ b/Server/src/SOR.Game/Abilities/Models/Effects.cs @@ -104,15 +104,24 @@ public abstract class Effect { } public enum StatTarget { Current, Max } -public sealed class ModifyHealthEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; } -public sealed class ModifyDefenseEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; } -public sealed class ModifyDamageEffect : Effect { public ValueExpr Amount { get; set; } = new(); } -public sealed class ModifyMPEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; } +/// +/// How to apply the Amount to the current stat value. +/// "Add" (default) and "Subtract" use the Amount directly (positive integer recommended; +/// Subtract flips the sign before applying). "Multiply" and "Divide" treat Amount as +/// the multiplier/divisor integer (e.g. Multiply 2 = ×2). "Percent" treats Amount as +/// a percentage (e.g. Percent 50 adds 50% of the base value). +/// +public enum StatModOperator { Add, Subtract, Multiply, Divide, Percent } + +public sealed class ModifyHealthEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; public StatModOperator Operator { get; set; } = StatModOperator.Add; } +public sealed class ModifyDefenseEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; public StatModOperator Operator { get; set; } = StatModOperator.Add; } +public sealed class ModifyDamageEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatModOperator Operator { get; set; } = StatModOperator.Add; } +public sealed class ModifyMPEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; public StatModOperator Operator { get; set; } = StatModOperator.Add; } public sealed class SetMovementTypeEffect : Effect { public MovementType MovementType { get; set; } } public sealed class SetAttackRangeEffect : Effect { public int Min { get; set; } public int Max { get; set; } } -public sealed class ModifyMinAttackRangeEffect : Effect { public ValueExpr Amount { get; set; } = new(); } -public sealed class ModifyMaxAttackRangeEffect : Effect { public ValueExpr Amount { get; set; } = new(); } +public sealed class ModifyMinAttackRangeEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatModOperator Operator { get; set; } = StatModOperator.Add; } +public sealed class ModifyMaxAttackRangeEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatModOperator Operator { get; set; } = StatModOperator.Add; } public sealed class ModifyCostEffect : Effect { public int? Sp { get; set; } public int? St { get; set; } } public sealed class SetAffinityEffect : Effect { public AffinityExpr Affinity { get; set; } = new(); } public sealed class GrantAdditionalAttackEffect : Effect { public int N { get; set; } = 1; } diff --git a/Server/src/SOR.Game/Abilities/Models/PendingCostPick.cs b/Server/src/SOR.Game/Abilities/Models/PendingCostPick.cs new file mode 100644 index 0000000..a3b473d --- /dev/null +++ b/Server/src/SOR.Game/Abilities/Models/PendingCostPick.cs @@ -0,0 +1,53 @@ +namespace SOR.Game.Abilities.Models; + +/// +/// Stored in GameState when an Active ability's cost requires interactive player selection +/// (e.g. "Discard a card of your choice from hand"). +/// +/// The engine pauses cost payment, pushes a CostPickRequestPush to the picker player, +/// then resumes via GameCostPickHandler once the player submits their selection. +/// +public sealed class PendingCostPick +{ + /// Correlation ID sent to the client so responses can be matched. + public string RequestId { get; set; } = Guid.NewGuid().ToString("N"); + + /// AccountId of the player who activated the ability. + public string ActorId { get; set; } = string.Empty; + + /// InstanceId of the unit whose ability cost is being resolved. + public string SourceInstanceId { get; set; } = string.Empty; + + /// 0-based index of the ability in the source unit's AbilitiesJson array. + public int AbilityIndex { get; set; } + + /// AccountId of the player who must pick (may differ from ActorId for EnemyPick modes). + public string PickerActorId { get; set; } = string.Empty; + + /// The cost type being interactively resolved. + public string CostType { get; set; } = string.Empty; + + /// Number of cards/units the picker must select. + public int Amount { get; set; } = 1; + + /// The pick mode driving who selects and how. + public string PickMode { get; set; } = string.Empty; + + /// JSON-serialized Filter[]? — constraints on what the picker may select. + public string? FiltersJson { get; set; } + + /// + /// JSON-serialized CostEntry[] of costs that still need paying after this pick resolves. + /// Empty when this is the last interactive cost. + /// + public string RemainingCostsJson { get; set; } = "[]"; + + /// JSON-serialized Action[] — the full action list to execute after all costs are paid. + public string ActionsJson { get; set; } = "[]"; + + /// JSON-serialized AbilityRange? — passed through to ExecuteActions on resume. + public string? RangeJson { get; set; } + + /// JSON-serialized DurationModel? — forceDuration passed to ExecuteActions on resume. + public string? ForceDurationJson { get; set; } +} diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index 906795f..8589868 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -831,3 +831,34 @@ public sealed record GameTriggeredTargetRequest( string RequestId, IReadOnlyList Targets); +/// +/// Pushed to the picker player when an Active ability cost requires interactive card/unit +/// selection (e.g. "Discard a Spirit card of your choice"). +/// The client shows a zone picker and replies with . +/// +public sealed record CostPickRequestPush( + /// Correlation ID — must be echoed back in the response. + string RequestId, + /// InstanceId of the unit whose ability cost is being resolved. + string SourceInstanceId, + /// The cost type being resolved (e.g. "DiscardFromHand"). + string CostType, + /// How many cards/units the picker must select. + int Amount, + /// Who is picking: "SelfPick", "EnemySeePick", "EnemyRandomPick", "EnemyPick". + string PickMode, + /// JSON-serialized Filter[]? constraining valid selections. Null = no constraint. + string? FiltersJson); + +/// +/// Sent by the picker to submit their card/unit selections for a pending cost. +/// +public sealed record GameCostPickRequest( + Guid SessionId, + string RequestId, + /// InstanceIds of the selected cards or units. + IReadOnlyList SelectedInstanceIds); + +/// Acknowledged response for a cost pick submission. +public sealed record GameCostPickResponse(bool Success); + diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs index 7d4cdeb..0171953 100644 --- a/Server/src/SOR.Game/GameState.cs +++ b/Server/src/SOR.Game/GameState.cs @@ -100,6 +100,13 @@ public sealed class GameState /// submits a game.triggered_target response. /// public Abilities.Models.PendingTriggeredTarget? PendingTriggeredTarget { get; set; } + + /// + /// Non-null when an Active ability's cost requires interactive card/unit selection + /// (CostPickMode.SelfPick / EnemyPick etc.). The game is effectively "paused" until + /// the picker submits a game.cost_pick response. + /// + public Abilities.Models.PendingCostPick? PendingCostPick { get; set; } } public sealed class PlayerState diff --git a/Server/src/SOR.Game/Handlers/GameCostPickHandler.cs b/Server/src/SOR.Game/Handlers/GameCostPickHandler.cs new file mode 100644 index 0000000..06a6233 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameCostPickHandler.cs @@ -0,0 +1,59 @@ +namespace SOR.Game.Handlers; + +using System.Text.Json; +using SOR.Database.Contexts; +using SOR.Game.Abilities; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.cost_pick — player (or opponent) submits their card/unit selections for a +/// paused Active ability cost (CostPickMode.SelfPick / EnemyPick etc.). +/// +/// This handler resumes and completes cost payment, then executes the ability actions +/// and broadcasts the updated game state to all players in the session. +/// +internal sealed class GameCostPickHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameCostPickHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.cost_pick"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var actorId = connection.UserId; + + var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct); + var prevStateJson = session.StateJson!; + var state = GameEngine.Deserialize(prevStateJson); + + var newState = AbilitySystem.ResumeCostPick( + state, actorId, req.RequestId, req.SelectedInstanceIds); + + await SaveStateAsync(_gameDb, session, newState, actorId, "game.cost_pick", + JsonSerializer.Serialize(req), ct); + + await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson); + + return ServerMessage.Reply("game.cost_pick.ack", message.Seq, + new GameCostPickResponse(true)); + } +} diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs index 7321502..6ff7853 100644 --- a/Server/src/SOR.Game/ServiceRegistration.cs +++ b/Server/src/SOR.Game/ServiceRegistration.cs @@ -100,6 +100,9 @@ public static class ServiceRegistration // Triggered ability target response (player submits picks for a paused trigger) services.AddTransient(); + // Interactive cost pick response (player submits card/unit selections for an interactive cost) + services.AddTransient(); + return services; } }