diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..a58ab02 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "godotTools.editorPath.godot4": "c:\\Users\\tazj2\\OneDrive\\Desktop\\Godot_v4.5.1-stable_win64.exe\\Godot_v4.5.1-stable_win64_console.exe" +} \ No newline at end of file diff --git a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilderR2-Draft.razor b/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilderR2-Draft.razor deleted file mode 100644 index 5c942e7..0000000 --- a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilderR2-Draft.razor +++ /dev/null @@ -1,1517 +0,0 @@ -@page "/cards/ability-builder-r2-draft" -@using System.Text.Json -@using System.Text.Json.Serialization -@using Microsoft.AspNetCore.Components.Rendering - -Ability Builder R2 Draft - SOR Admin - -@{ - var issues = BuildValidationIssues(); - var previewJson = BuildCanonicalJson(); -} - -
-
-
- - Cards - -

Ability Builder R2 Draft

-

In-memory staging page for the BuilderR2 structure and canonical JSON output.

-
-
- - - -
-
- -
-
-
-
- Core -
-
-
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
-
-
- -
-
- Activation Conditions - Root @(_draft.ActivationConditions.Logic) -
-
- @RenderConditionGroup(_draft.ActivationConditions, "activationConditions", "Activation logic group") -
-
- - @if (_draft.Type == "Active") - { -
-
- Active Details -
-
-
-
- - -
-
- - -
-
- - -
-
-
-
- - -
-
- - -
-
-
-
-
-
- } - - @if (_draft.Type == "Triggered") - { -
-
- Triggered Details -
-
-
-
- - -
-
- - -
-
- - -
-
- -
- -
- @foreach (var zone in SourceZones) - { -
- - -
- } -
-
- -
-
- - -
-
- - -
-
- - -
-
- -
-
- - -
- @if (_draft.Triggered.Filters.Count == 0) - { -

No trigger filters configured.

- } - else - { - @for (var i = 0; i < _draft.Triggered.Filters.Count; i++) - { - var filter = _draft.Triggered.Filters[i]; - var filterIndex = i; -
-
-
- - -
-
- - -
-
- - -
-
- - -
-
- -
-
-
-
- - -
-
- - -
-
-
- } - } -
-
-
- } - - @if (_draft.Type == "Passive") - { -
-
- Passive Details -
-
-
-
- - -
-
- - -
-
- - -
-
-
-
- } - - @if (_draft.Type == "Aura") - { -
-
- Aura Details -
-
-
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
-
-
- } - -
-
- Cost Authoring - -
-
- @RenderCostGroup(_draft.Costs, "costs", "Cost root group") -
-
- -
-
- Action Authoring - -
-
- @RenderActionGroup(_draft.Actions, "actions", "Action root group") -
-
-
- -
-
-
- Validation - @issues.Count issues -
-
- @if (issues.Count == 0) - { -

No issues detected for the current draft.

- } - else - { - @foreach (var issue in issues) - { -
-
-
-
@issue.Code
-
@issue.Message
-
- @issue.Severity -
-
@issue.Path
-
@issue.SuggestedFix
-
- } - } -
-
- -
-
- Structure Summary -
-
-
-
Ability Type
-
@_draft.Type
-
Activation Rules
-
@CountConditionRules(_draft.ActivationConditions)
-
Cost Entries
-
@CountCosts(_draft.Costs)
-
Action Entries
-
@CountActions(_draft.Actions)
-
Effect Entries
-
@CountEffects(_draft.Actions)
- @if (_draft.Type == "Triggered") - { -
Source Zones
-
@string.Join(", ", _draft.Triggered.SourceZoneGate)
- } -
-
-
- -
-
- Canonical JSON Preview -
-
- -
-
-
-
-
- - - -@code { - private readonly string[] AbilityTypes = ["Active", "Triggered", "Passive", "Aura"]; - private readonly string[] LogicOperators = ["AND", "OR", "XOR"]; - private readonly string[] Comparators = ["==", "!=", ">", ">=", "<", "<="]; - private readonly string[] FilterTypes = ["Property", "Tag", "Zone", "Affinity", "Genus", "StatThreshold"]; - private readonly string[] OwnershipScopes = ["Any", "Self", "Ally", "Opponent", "Owner"]; - private readonly string[] SourceZones = ["Battlefield", "Hand", "Discard", "Deck"]; - private readonly string[] TriggerFamilies = ["Lifecycle", "UnitCombatMoveAbility", "BattlefieldState", "AbilityMutationTargeting", "RuinOccupancy", "TileAffinity", "ResourceEconomy", "CardMovementVisibility", "AuraBoundary"]; - private readonly string[] TriggerLimitModes = ["Unlimited", "PerTurn", "PerGame"]; - private readonly string[] ContinuousScopes = ["Self", "OwnedUnits", "AlliedUnits", "EnemyUnits", "Battlefield", "Players"]; - private readonly string[] RecheckCadences = ["Continuous", "TurnStart", "TurnEnd", "OnRelevantEvent"]; - private readonly string[] LeavePolicies = ["Persist", "ClearImmediately", "LingerForDuration"]; - private readonly string[] CostTypes = ["SpiritPoints", "StatePoints", "DiscardFromHand", "SendSpiritFromBattlefieldToDiscard", "DealDamageToOwnSpirit"]; - private readonly string[] ChooserAuthorities = ["Self", "Opponent", "Random", "System"]; - private readonly string[] ActionScopes = ["Battlefield", "Hand", "Deck", "Discard", "Player", "Battlefield+Discard"]; - private readonly string[] TargetTypes = ["Spirit", "ArchSpirit", "SpiritToken", "Ruin", "Tile", "Card", "Player"]; - private readonly string[] EffectTypes = ["DealDamage", "Heal", "DrawCards", "MoveToDiscard", "MoveToHand", "ModifyStat", "CreateToken", "SetTileAffinity"]; - private readonly string[] DurationModes = ["Immediate", "UntilEndOfTurn", "UntilSourceLeaves", "ForNTurns"]; - private readonly string[] InteractivePickModes = ["Random", "SelfPick", "EnemySeePick", "EnemyRandomPick", "EnemyPick"]; - - private AbilityDefinitionDraftR2 _draft = CreateTriggeredSample(); - - private IReadOnlyList ConditionDomains => - [ - "TurnTiming", - "UnitOwnership", - "UnitProperties", - "ThisCardProperties", - "CardDefinitionProperties", - "CountInZone", - "LocationScope", - "TileProperties", - "SurroundingTileProperties", - "PlayerProperties", - "BattlefieldState" - ]; - - private void AddTriggerFilter() => _draft.Triggered.Filters.Add(new TypedFilterDraft()); - private void AddCostToRoot() => _draft.Costs.Costs.Add(new CostDraft()); - private void AddActionToRoot() => _draft.Actions.Actions.Add(new ActionDraft()); - - private void ToggleSourceZone(string zone) - { - if (_draft.Triggered.SourceZoneGate.Contains(zone)) - { - _draft.Triggered.SourceZoneGate.Remove(zone); - } - else - { - _draft.Triggered.SourceZoneGate.Add(zone); - } - } - - private void LoadBlankDraft() => _draft = new AbilityDefinitionDraftR2(); - private void LoadActiveSample() => _draft = CreateActiveSample(); - private void LoadTriggeredSample() => _draft = CreateTriggeredSample(); - - private IReadOnlyList GetEventTypes(string family) => family switch - { - "Lifecycle" => ["TurnStarted", "TurnEnded", "CardEnteredBattlefield", "CardLeftBattlefield"], - "UnitCombatMoveAbility" => ["UnitMoved", "AttackDeclared", "DamageDealt", "AbilityUsed"], - "BattlefieldState" => ["TileOccupied", "TileVacated", "ControlChanged"], - "AbilityMutationTargeting" => ["AbilityGranted", "AbilityRemoved", "TargetedByAbility"], - "RuinOccupancy" => ["RuinOccupied", "RuinVacated", "RuinActivated"], - "TileAffinity" => ["TileAffinityChanged", "TileAffinityPushed"], - "ResourceEconomy" => ["SpiritPointsGained", "StatePointsSpent", "CardDrawn"], - "CardMovementVisibility" => ["MovedToDiscard", "ReturnedToHand", "Revealed", "Shuffled"], - "AuraBoundary" => ["EnteredAuraRange", "LeftAuraRange"], - _ => ["CustomEvent"] - }; - - private List BuildValidationIssues() - { - var issues = new List(); - - if (string.IsNullOrWhiteSpace(_draft.Name)) - { - issues.Add(new ValidationIssue("Error", "ABILITY_NAME_REQUIRED", "name", "Ability name is required.", "Enter a display name for the draft.")); - } - - if (string.IsNullOrWhiteSpace(_draft.Description)) - { - issues.Add(new ValidationIssue("Warning", "ABILITY_DESCRIPTION_EMPTY", "description", "Description is blank.", "Add plain-English intent so the JSON is easier to review.")); - } - - if (_draft.Type == "Active" && - _draft.Active.RangeMin.HasValue && - _draft.Active.RangeMax.HasValue && - _draft.Active.RangeMin > _draft.Active.RangeMax) - { - issues.Add(new ValidationIssue("Error", "ACTIVE_RANGE_INVALID", "active.range", "Range min is greater than range max.", "Set a valid min/max pair.")); - } - - if (_draft.Type == "Triggered") - { - if (string.IsNullOrWhiteSpace(_draft.Triggered.EventType)) - { - issues.Add(new ValidationIssue("Error", "TRIGGER_EVENT_REQUIRED", "triggered.eventType", "Triggered abilities need an event type.", "Select an event family and event type.")); - } - - if (_draft.Triggered.SourceZoneGate.Count == 0) - { - issues.Add(new ValidationIssue("Error", "TRIGGER_ZONE_REQUIRED", "triggered.sourceZoneGate", "At least one source zone gate is required.", "Choose battlefield, hand, discard, deck, or a combination.")); - } - - if (_draft.Triggered.EventFamily == "RuinOccupancy" && _draft.Triggered.LimitMode == "Unlimited") - { - issues.Add(new ValidationIssue("Warning", "TRIGGER_LOOP_RISK", "triggered.limitMode", "Unlimited ruin occupancy triggers are high-risk for self-retrigger loops.", "Set a per-turn or per-game limit.")); - } - } - - if (_draft.Type == "Passive" && string.IsNullOrWhiteSpace(_draft.Passive.ContinuousScope)) - { - issues.Add(new ValidationIssue("Error", "PASSIVE_SCOPE_REQUIRED", "passive.continuousScope", "Passive abilities need a continuous scope.", "Select the scope the passive applies to.")); - } - - if (_draft.Type == "Aura" && - _draft.Aura.RangeMin.HasValue && - _draft.Aura.RangeMax.HasValue && - _draft.Aura.RangeMin > _draft.Aura.RangeMax) - { - issues.Add(new ValidationIssue("Error", "AURA_RANGE_INVALID", "aura.range", "Aura range min is greater than aura range max.", "Set a valid min/max pair.")); - } - - if (CountActions(_draft.Actions) == 0) - { - issues.Add(new ValidationIssue("Error", "ACTIONS_REQUIRED", "actions", "At least one action is required.", "Add an action or action subgroup.")); - } - - ValidateConditionGroup(_draft.ActivationConditions, "activationConditions", issues); - ValidateCostGroup(_draft.Costs, "costs", issues); - ValidateActionGroup(_draft.Actions, "actions", issues); - - return issues; - } - - private void ValidateConditionGroup(LogicGroupDraft group, string path, List issues) - { - for (var i = 0; i < group.Rules.Count; i++) - { - var rule = group.Rules[i]; - var rulePath = $"{path}.rules[{i}]"; - if (string.IsNullOrWhiteSpace(rule.Field)) - { - issues.Add(new ValidationIssue("Warning", "CONDITION_FIELD_EMPTY", $"{rulePath}.field", "Condition field is blank.", "Set the property or metric being checked.")); - } - if (string.IsNullOrWhiteSpace(rule.Value)) - { - issues.Add(new ValidationIssue("Warning", "CONDITION_VALUE_EMPTY", $"{rulePath}.value", "Condition value is blank.", "Set the comparison value.")); - } - } - - for (var i = 0; i < group.Groups.Count; i++) - { - ValidateConditionGroup(group.Groups[i], $"{path}.groups[{i}]", issues); - } - } - - private void ValidateCostGroup(CostGroupDraft group, string path, List issues) - { - for (var i = 0; i < group.Costs.Count; i++) - { - var cost = group.Costs[i]; - var costPath = $"{path}.costs[{i}]"; - if (cost.Amount is null or <= 0) - { - issues.Add(new ValidationIssue("Warning", "COST_AMOUNT_EMPTY", $"{costPath}.amount", "Cost amount should usually be greater than zero.", "Set a positive amount or remove the cost entry.")); - } - - if (RequiresInteractiveMetadata(cost.Type) && string.IsNullOrWhiteSpace(cost.PickMode)) - { - issues.Add(new ValidationIssue("Error", "COST_PICK_MODE_REQUIRED", $"{costPath}.pickMode", "Interactive cost metadata is incomplete.", "Choose a pick mode for this cost.")); - } - } - - for (var i = 0; i < group.Groups.Count; i++) - { - ValidateCostGroup(group.Groups[i], $"{path}.groups[{i}]", issues); - } - } - - private void ValidateActionGroup(ActionGroupDraft group, string path, List issues) - { - for (var i = 0; i < group.Actions.Count; i++) - { - var action = group.Actions[i]; - var actionPath = $"{path}.actions[{i}]"; - - if (action.Count is null or <= 0) - { - issues.Add(new ValidationIssue("Error", "ACTION_COUNT_REQUIRED", $"{actionPath}.count", "Action count must be greater than zero.", "Set a positive target count.")); - } - - if (action.Effects.Count == 0) - { - issues.Add(new ValidationIssue("Error", "ACTION_EFFECT_REQUIRED", $"{actionPath}.effects", "Each action needs at least one effect.", "Add an effect to the action.")); - } - - for (var filterIndex = 0; filterIndex < action.Filters.Count; filterIndex++) - { - var filter = action.Filters[filterIndex]; - var filterPath = $"{actionPath}.filters[{filterIndex}]"; - if (string.IsNullOrWhiteSpace(filter.Field)) - { - issues.Add(new ValidationIssue("Warning", "FILTER_FIELD_EMPTY", $"{filterPath}.field", "Typed filter field is blank.", "Set the field the filter should inspect.")); - } - } - - ValidateConditionGroup(action.Conditions, $"{actionPath}.conditions", issues); - - for (var effectIndex = 0; effectIndex < action.Effects.Count; effectIndex++) - { - var effect = action.Effects[effectIndex]; - var effectPath = $"{actionPath}.effects[{effectIndex}]"; - if (effect.Amount is null or <= 0) - { - issues.Add(new ValidationIssue("Warning", "EFFECT_AMOUNT_EMPTY", $"{effectPath}.amount", "Effect amount should usually be greater than zero.", "Set a positive amount or switch to a non-amount effect.")); - } - if (effect.DurationMode == "ForNTurns" && (effect.DurationN is null or <= 0)) - { - issues.Add(new ValidationIssue("Error", "EFFECT_DURATION_N_REQUIRED", $"{effectPath}.durationN", "ForNTurns requires a positive duration N.", "Set duration N to at least 1.")); - } - } - } - - for (var i = 0; i < group.Groups.Count; i++) - { - ValidateActionGroup(group.Groups[i], $"{path}.groups[{i}]", issues); - } - } - - private static bool RequiresInteractiveMetadata(string costType) => - costType is "DiscardFromHand" or "SendSpiritFromBattlefieldToDiscard" or "DealDamageToOwnSpirit"; - - private string BuildCanonicalJson() - { - var canonical = new - { - schema = "AbilityDefinitionDraftR2", - name = _draft.Name, - description = _draft.Description, - type = _draft.Type, - limits = new - { - perTurn = _draft.Limits.PerTurn, - perGame = _draft.Limits.PerGame - }, - presentation = new - { - animation = _draft.Presentation.Animation, - animationAsset = _draft.Presentation.AnimationAsset, - castSfx = _draft.Presentation.CastSfx, - impactSfx = _draft.Presentation.ImpactSfx - }, - activationConditions = MapConditionGroup(_draft.ActivationConditions), - typeData = _draft.Type switch - { - "Active" => (object)new - { - range = new { min = _draft.Active.RangeMin, max = _draft.Active.RangeMax }, - requiresLos = _draft.Active.RequiresLos, - linearOnly = _draft.Active.LinearOnly, - usesPerTurn = _draft.Active.UsesPerTurn - }, - "Triggered" => (object)new - { - eventFamily = _draft.Triggered.EventFamily, - eventType = _draft.Triggered.EventType, - limitMode = _draft.Triggered.LimitMode, - sourceZoneGate = _draft.Triggered.SourceZoneGate, - ownershipScope = _draft.Triggered.OwnershipScope, - amountGate = new - { - comparator = _draft.Triggered.AmountComparator, - value = _draft.Triggered.Amount - }, - filters = _draft.Triggered.Filters.Select(MapTypedFilter).ToList() - }, - "Passive" => (object)new - { - continuousScope = _draft.Passive.ContinuousScope, - recheckCadence = _draft.Passive.RecheckCadence, - sourceLeavePolicy = _draft.Passive.SourceLeavePolicy - }, - "Aura" => (object)new - { - range = new { min = _draft.Aura.RangeMin, max = _draft.Aura.RangeMax }, - enterHook = _draft.Aura.EnterHook, - leaveHook = _draft.Aura.LeaveHook, - leavePolicy = _draft.Aura.LeavePolicy, - lingerDuration = _draft.Aura.LingerDuration - }, - _ => (object)new { } - }, - costs = MapCostGroup(_draft.Costs), - actions = MapActionGroup(_draft.Actions) - }; - - return JsonSerializer.Serialize(canonical, new JsonSerializerOptions - { - WriteIndented = true, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }); - } - - private static object MapConditionGroup(LogicGroupDraft group) => new - { - logic = group.Logic, - rules = group.Rules.Select(r => new - { - domain = r.Domain, - field = r.Field, - comparator = r.Comparator, - value = r.Value, - parameters = string.IsNullOrWhiteSpace(r.ParameterKey) && string.IsNullOrWhiteSpace(r.ParameterValue) - ? null - : new Dictionary - { - ["key"] = r.ParameterKey, - ["value"] = r.ParameterValue - } - }).ToList(), - groups = group.Groups.Select(MapConditionGroup).ToList() - }; - - private static object MapCostGroup(CostGroupDraft group) => new - { - logic = group.Logic, - costs = group.Costs.Select(c => new - { - type = c.Type, - amount = c.Amount, - interactive = new - { - chooser = c.Chooser, - pickMode = c.PickMode - }, - metadata = string.IsNullOrWhiteSpace(c.MetadataKey) && string.IsNullOrWhiteSpace(c.MetadataValue) - ? null - : new Dictionary - { - ["key"] = c.MetadataKey, - ["value"] = c.MetadataValue - } - }).ToList(), - groups = group.Groups.Select(MapCostGroup).ToList() - }; - - private static object MapActionGroup(ActionGroupDraft group) => new - { - logic = group.Logic, - actions = group.Actions.Select(a => new - { - scope = a.Scope, - targetType = a.TargetType, - chooser = a.Chooser, - count = a.Count, - filters = a.Filters.Select(MapTypedFilter).ToList(), - conditions = MapConditionGroup(a.Conditions), - effects = a.Effects.Select(e => new - { - type = e.Type, - amount = e.Amount, - duration = new - { - mode = e.DurationMode, - n = e.DurationN - }, - parameters = string.IsNullOrWhiteSpace(e.ParameterKey) && string.IsNullOrWhiteSpace(e.ParameterValue) - ? null - : new Dictionary - { - ["key"] = e.ParameterKey, - ["value"] = e.ParameterValue - } - }).ToList() - }).ToList(), - groups = group.Groups.Select(MapActionGroup).ToList() - }; - - private static object MapTypedFilter(TypedFilterDraft filter) => new - { - type = filter.Type, - field = filter.Field, - comparator = filter.Comparator, - value = filter.Value, - parameters = string.IsNullOrWhiteSpace(filter.ParameterKey) && string.IsNullOrWhiteSpace(filter.ParameterValue) - ? null - : new Dictionary - { - ["key"] = filter.ParameterKey, - ["value"] = filter.ParameterValue - } - }; - - private static int CountConditionRules(LogicGroupDraft group) => - group.Rules.Count + group.Groups.Sum(CountConditionRules); - - private static int CountCosts(CostGroupDraft group) => - group.Costs.Count + group.Groups.Sum(CountCosts); - - private static int CountActions(ActionGroupDraft group) => - group.Actions.Count + group.Groups.Sum(CountActions); - - private static int CountEffects(ActionGroupDraft group) => - group.Actions.Sum(a => a.Effects.Count) + group.Groups.Sum(CountEffects); - - private static string SeverityBadge(string severity) => severity switch - { - "Error" => "text-bg-danger", - "Warning" => "text-bg-warning", - _ => "text-bg-info" - }; - - private static string BindInt(int? value) => value?.ToString() ?? string.Empty; - - private static int? ParseNullableInt(string? value) => - int.TryParse(value, out var parsed) ? parsed : null; - - private void BuildSelect(RenderTreeBuilder builder, ref int seq, string columnClass, string label, string value, IReadOnlyList options, Action setter) - { - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", columnClass); - builder.OpenElement(seq++, "label"); - builder.AddAttribute(seq++, "class", "form-label small"); - builder.AddContent(seq++, label); - builder.CloseElement(); - builder.OpenElement(seq++, "select"); - builder.AddAttribute(seq++, "class", "form-select form-select-sm"); - builder.AddAttribute(seq++, "value", value); - builder.AddAttribute(seq++, "onchange", EventCallback.Factory.Create(this, e => setter(e.Value?.ToString() ?? string.Empty))); - foreach (var option in options) - { - builder.OpenElement(seq++, "option"); - builder.AddAttribute(seq++, "value", option); - builder.AddContent(seq++, option); - builder.CloseElement(); - } - builder.CloseElement(); - builder.CloseElement(); - } - - private void BuildInput(RenderTreeBuilder builder, ref int seq, string columnClass, string label, string? value, Action setter) - { - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", columnClass); - builder.OpenElement(seq++, "label"); - builder.AddAttribute(seq++, "class", "form-label small"); - builder.AddContent(seq++, label); - builder.CloseElement(); - builder.OpenElement(seq++, "input"); - builder.AddAttribute(seq++, "class", "form-control form-control-sm"); - builder.AddAttribute(seq++, "value", value); - builder.AddAttribute(seq++, "oninput", EventCallback.Factory.Create(this, e => setter(e.Value?.ToString() ?? string.Empty))); - builder.CloseElement(); - builder.CloseElement(); - } - - private RenderFragment RenderConditionGroup(LogicGroupDraft group, string path, string title, int depth = 0) => builder => - { - var seq = 0; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", $"group-shell depth-{Math.Min(depth, 2)}"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3"); - builder.OpenElement(seq++, "div"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "fw-semibold"); - builder.AddContent(seq++, title); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "small text-muted"); - builder.AddContent(seq++, path); - builder.CloseElement(); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "d-flex flex-wrap gap-2 align-items-center"); - builder.OpenElement(seq++, "select"); - builder.AddAttribute(seq++, "class", "form-select form-select-sm"); - builder.AddAttribute(seq++, "style", "width:120px"); - builder.AddAttribute(seq++, "value", group.Logic); - builder.AddAttribute(seq++, "onchange", EventCallback.Factory.Create(this, e => group.Logic = e.Value?.ToString() ?? "AND")); - foreach (var logic in LogicOperators) - { - builder.OpenElement(seq++, "option"); - builder.AddAttribute(seq++, "value", logic); - builder.AddContent(seq++, logic); - builder.CloseElement(); - } - builder.CloseElement(); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-secondary btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Rules.Add(new ConditionRuleDraft()))); - builder.AddContent(seq++, "Add Rule"); - builder.CloseElement(); - if (depth < 1) - { - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-secondary btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Groups.Add(new LogicGroupDraft()))); - builder.AddContent(seq++, "Add Group"); - builder.CloseElement(); - } - builder.CloseElement(); - builder.CloseElement(); - - for (var i = 0; i < group.Rules.Count; i++) - { - var index = i; - var rule = group.Rules[index]; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "border rounded p-2 mb-2"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "row g-2 align-items-end"); - BuildSelect(builder, ref seq, "col-md-3", "Domain", rule.Domain, ConditionDomains, v => rule.Domain = v); - BuildInput(builder, ref seq, "col-md-3", "Field", rule.Field, v => rule.Field = v); - BuildSelect(builder, ref seq, "col-md-2", "Comparator", rule.Comparator, Comparators, v => rule.Comparator = v); - BuildInput(builder, ref seq, "col-md-3", "Value", rule.Value, v => rule.Value = v); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "col-md-1 text-end"); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-danger btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Rules.RemoveAt(index))); - builder.AddContent(seq++, "X"); - builder.CloseElement(); - builder.CloseElement(); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "row g-2 mt-1"); - BuildInput(builder, ref seq, "col-md-6", "Parameter Key", rule.ParameterKey, v => rule.ParameterKey = v); - BuildInput(builder, ref seq, "col-md-6", "Parameter Value", rule.ParameterValue, v => rule.ParameterValue = v); - builder.CloseElement(); - builder.CloseElement(); - } - - for (var i = 0; i < group.Groups.Count; i++) - { - var subgroup = group.Groups[i]; - var index = i; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "mb-2"); - builder.AddContent(seq++, RenderConditionGroup(subgroup, $"{path}.groups[{index}]", $"Nested Group {index + 1}", depth + 1)); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "text-end mt-2"); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-danger btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Groups.RemoveAt(index))); - builder.AddContent(seq++, "Remove Group"); - builder.CloseElement(); - builder.CloseElement(); - builder.CloseElement(); - } - - if (group.Rules.Count == 0 && group.Groups.Count == 0) - { - builder.OpenElement(seq++, "p"); - builder.AddAttribute(seq++, "class", "text-muted mb-0"); - builder.AddContent(seq++, "No rules in this group."); - builder.CloseElement(); - } - - builder.CloseElement(); - }; - - private RenderFragment RenderCostGroup(CostGroupDraft group, string path, string title, int depth = 0) => builder => - { - var seq = 0; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", $"group-shell depth-{Math.Min(depth, 2)}"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3"); - builder.OpenElement(seq++, "div"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "fw-semibold"); - builder.AddContent(seq++, title); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "small text-muted"); - builder.AddContent(seq++, path); - builder.CloseElement(); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "d-flex flex-wrap gap-2"); - builder.OpenElement(seq++, "select"); - builder.AddAttribute(seq++, "class", "form-select form-select-sm"); - builder.AddAttribute(seq++, "style", "width:120px"); - builder.AddAttribute(seq++, "value", group.Logic); - builder.AddAttribute(seq++, "onchange", EventCallback.Factory.Create(this, e => group.Logic = e.Value?.ToString() ?? "AND")); - foreach (var logic in LogicOperators) - { - builder.OpenElement(seq++, "option"); - builder.AddAttribute(seq++, "value", logic); - builder.AddContent(seq++, logic); - builder.CloseElement(); - } - builder.CloseElement(); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-secondary btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Costs.Add(new CostDraft()))); - builder.AddContent(seq++, "Add Cost"); - builder.CloseElement(); - if (depth < 1) - { - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-secondary btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Groups.Add(new CostGroupDraft()))); - builder.AddContent(seq++, "Add Group"); - builder.CloseElement(); - } - builder.CloseElement(); - builder.CloseElement(); - - for (var i = 0; i < group.Costs.Count; i++) - { - var index = i; - var cost = group.Costs[index]; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "border rounded p-2 mb-2"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "row g-2 align-items-end"); - BuildSelect(builder, ref seq, "col-md-3", "Cost Type", cost.Type, CostTypes, v => cost.Type = v); - BuildInput(builder, ref seq, "col-md-2", "Amount", BindInt(cost.Amount), v => cost.Amount = ParseNullableInt(v)); - BuildSelect(builder, ref seq, "col-md-3", "Pick Mode", cost.PickMode, InteractivePickModes, v => cost.PickMode = v); - BuildInput(builder, ref seq, "col-md-3", "Chooser", cost.Chooser, v => cost.Chooser = v); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "col-md-1 text-end"); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-danger btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Costs.RemoveAt(index))); - builder.AddContent(seq++, "X"); - builder.CloseElement(); - builder.CloseElement(); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "row g-2 mt-1"); - BuildInput(builder, ref seq, "col-md-6", "Metadata Key", cost.MetadataKey, v => cost.MetadataKey = v); - BuildInput(builder, ref seq, "col-md-6", "Metadata Value", cost.MetadataValue, v => cost.MetadataValue = v); - builder.CloseElement(); - builder.CloseElement(); - } - - for (var i = 0; i < group.Groups.Count; i++) - { - var subgroup = group.Groups[i]; - var index = i; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "mb-2"); - builder.AddContent(seq++, RenderCostGroup(subgroup, $"{path}.groups[{index}]", $"Nested Cost Group {index + 1}", depth + 1)); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "text-end mt-2"); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-danger btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Groups.RemoveAt(index))); - builder.AddContent(seq++, "Remove Group"); - builder.CloseElement(); - builder.CloseElement(); - builder.CloseElement(); - } - - if (group.Costs.Count == 0 && group.Groups.Count == 0) - { - builder.OpenElement(seq++, "p"); - builder.AddAttribute(seq++, "class", "text-muted mb-0"); - builder.AddContent(seq++, "No costs in this group."); - builder.CloseElement(); - } - - builder.CloseElement(); - }; - - private RenderFragment RenderActionGroup(ActionGroupDraft group, string path, string title, int depth = 0) => builder => - { - var seq = 0; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", $"group-shell depth-{Math.Min(depth, 2)}"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3"); - builder.OpenElement(seq++, "div"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "fw-semibold"); - builder.AddContent(seq++, title); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "small text-muted"); - builder.AddContent(seq++, path); - builder.CloseElement(); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "d-flex flex-wrap gap-2"); - builder.OpenElement(seq++, "select"); - builder.AddAttribute(seq++, "class", "form-select form-select-sm"); - builder.AddAttribute(seq++, "style", "width:120px"); - builder.AddAttribute(seq++, "value", group.Logic); - builder.AddAttribute(seq++, "onchange", EventCallback.Factory.Create(this, e => group.Logic = e.Value?.ToString() ?? "AND")); - foreach (var logic in LogicOperators) - { - builder.OpenElement(seq++, "option"); - builder.AddAttribute(seq++, "value", logic); - builder.AddContent(seq++, logic); - builder.CloseElement(); - } - builder.CloseElement(); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-secondary btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Actions.Add(new ActionDraft()))); - builder.AddContent(seq++, "Add Action"); - builder.CloseElement(); - if (depth < 1) - { - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-secondary btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Groups.Add(new ActionGroupDraft()))); - builder.AddContent(seq++, "Add Group"); - builder.CloseElement(); - } - builder.CloseElement(); - builder.CloseElement(); - - for (var i = 0; i < group.Actions.Count; i++) - { - var index = i; - var action = group.Actions[index]; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "border rounded p-3 mb-3"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "d-flex justify-content-between align-items-center mb-2"); - builder.OpenElement(seq++, "strong"); - builder.AddContent(seq++, $"Action {index + 1}"); - builder.CloseElement(); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-danger btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Actions.RemoveAt(index))); - builder.AddContent(seq++, "Remove"); - builder.CloseElement(); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "row g-2"); - BuildSelect(builder, ref seq, "col-md-3", "Scope", action.Scope, ActionScopes, v => action.Scope = v); - BuildSelect(builder, ref seq, "col-md-3", "Target Type", action.TargetType, TargetTypes, v => action.TargetType = v); - BuildSelect(builder, ref seq, "col-md-3", "Chooser", action.Chooser, ChooserAuthorities, v => action.Chooser = v); - BuildInput(builder, ref seq, "col-md-3", "Count", BindInt(action.Count), v => action.Count = ParseNullableInt(v)); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "mt-3"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "d-flex justify-content-between align-items-center mb-2"); - builder.OpenElement(seq++, "label"); - builder.AddAttribute(seq++, "class", "form-label mb-0"); - builder.AddContent(seq++, "Target Filters"); - builder.CloseElement(); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-secondary btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => action.Filters.Add(new TypedFilterDraft()))); - builder.AddContent(seq++, "Add Filter"); - builder.CloseElement(); - builder.CloseElement(); - for (var filterIndex = 0; filterIndex < action.Filters.Count; filterIndex++) - { - var typedFilter = action.Filters[filterIndex]; - var capturedIndex = filterIndex; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "border rounded p-2 mb-2"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "row g-2 align-items-end"); - BuildSelect(builder, ref seq, "col-md-3", "Type", typedFilter.Type, FilterTypes, v => typedFilter.Type = v); - BuildInput(builder, ref seq, "col-md-2", "Field", typedFilter.Field, v => typedFilter.Field = v); - BuildSelect(builder, ref seq, "col-md-2", "Comparator", typedFilter.Comparator, Comparators, v => typedFilter.Comparator = v); - BuildInput(builder, ref seq, "col-md-2", "Value", typedFilter.Value, v => typedFilter.Value = v); - BuildInput(builder, ref seq, "col-md-2", "Param Key", typedFilter.ParameterKey, v => typedFilter.ParameterKey = v); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "col-md-1 text-end"); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-danger btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => action.Filters.RemoveAt(capturedIndex))); - builder.AddContent(seq++, "X"); - builder.CloseElement(); - builder.CloseElement(); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "row g-2 mt-1"); - BuildInput(builder, ref seq, "col-md-12", "Param Value", typedFilter.ParameterValue, v => typedFilter.ParameterValue = v); - builder.CloseElement(); - builder.CloseElement(); - } - if (action.Filters.Count == 0) - { - builder.OpenElement(seq++, "p"); - builder.AddAttribute(seq++, "class", "text-muted mb-0"); - builder.AddContent(seq++, "No target filters configured."); - builder.CloseElement(); - } - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "mt-3"); - builder.OpenElement(seq++, "label"); - builder.AddAttribute(seq++, "class", "form-label mb-2"); - builder.AddContent(seq++, "Action Conditions"); - builder.CloseElement(); - builder.AddContent(seq++, RenderConditionGroup(action.Conditions, $"{path}.actions[{index}].conditions", "Action condition group", 1)); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "mt-3"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "d-flex justify-content-between align-items-center mb-2"); - builder.OpenElement(seq++, "label"); - builder.AddAttribute(seq++, "class", "form-label mb-0"); - builder.AddContent(seq++, "Effects"); - builder.CloseElement(); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-secondary btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => action.Effects.Add(new EffectDraft()))); - builder.AddContent(seq++, "Add Effect"); - builder.CloseElement(); - builder.CloseElement(); - for (var effectIndex = 0; effectIndex < action.Effects.Count; effectIndex++) - { - var effect = action.Effects[effectIndex]; - var capturedEffectIndex = effectIndex; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "border rounded p-2 mb-2"); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "row g-2 align-items-end"); - BuildSelect(builder, ref seq, "col-md-3", "Effect Type", effect.Type, EffectTypes, v => effect.Type = v); - BuildInput(builder, ref seq, "col-md-2", "Amount", BindInt(effect.Amount), v => effect.Amount = ParseNullableInt(v)); - BuildSelect(builder, ref seq, "col-md-3", "Duration", effect.DurationMode, DurationModes, v => effect.DurationMode = v); - BuildInput(builder, ref seq, "col-md-3", "Duration N", BindInt(effect.DurationN), v => effect.DurationN = ParseNullableInt(v)); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "col-md-1 text-end"); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-danger btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => action.Effects.RemoveAt(capturedEffectIndex))); - builder.AddContent(seq++, "X"); - builder.CloseElement(); - builder.CloseElement(); - builder.CloseElement(); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "row g-2 mt-1"); - BuildInput(builder, ref seq, "col-md-6", "Param Key", effect.ParameterKey, v => effect.ParameterKey = v); - BuildInput(builder, ref seq, "col-md-6", "Param Value", effect.ParameterValue, v => effect.ParameterValue = v); - builder.CloseElement(); - builder.CloseElement(); - } - if (action.Effects.Count == 0) - { - builder.OpenElement(seq++, "p"); - builder.AddAttribute(seq++, "class", "text-muted mb-0 mt-2"); - builder.AddContent(seq++, "No effects configured."); - builder.CloseElement(); - } - builder.CloseElement(); - builder.CloseElement(); - } - - for (var i = 0; i < group.Groups.Count; i++) - { - var subgroup = group.Groups[i]; - var index = i; - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "mb-2"); - builder.AddContent(seq++, RenderActionGroup(subgroup, $"{path}.groups[{index}]", $"Nested Action Group {index + 1}", depth + 1)); - builder.OpenElement(seq++, "div"); - builder.AddAttribute(seq++, "class", "text-end mt-2"); - builder.OpenElement(seq++, "button"); - builder.AddAttribute(seq++, "type", "button"); - builder.AddAttribute(seq++, "class", "btn btn-outline-danger btn-sm"); - builder.AddAttribute(seq++, "onclick", EventCallback.Factory.Create(this, () => group.Groups.RemoveAt(index))); - builder.AddContent(seq++, "Remove Group"); - builder.CloseElement(); - builder.CloseElement(); - builder.CloseElement(); - } - - if (group.Actions.Count == 0 && group.Groups.Count == 0) - { - builder.OpenElement(seq++, "p"); - builder.AddAttribute(seq++, "class", "text-muted mb-0"); - builder.AddContent(seq++, "No actions in this group."); - builder.CloseElement(); - } - - builder.CloseElement(); - }; - - private static AbilityDefinitionDraftR2 CreateActiveSample() - { - return new AbilityDefinitionDraftR2 - { - Name = "Pulse Lance", - Description = "Deal damage to an enemy spirit in range.", - Type = "Active", - Limits = new LimitDraft { PerTurn = 1 }, - Presentation = new PresentationDraft { Animation = "Projectile", AnimationAsset = "fx/pulse-lance", CastSfx = "sfx/cast/pulse", ImpactSfx = "sfx/hit/pulse" }, - Active = new ActiveDraft { RangeMin = 1, RangeMax = 3, RequiresLos = true, UsesPerTurn = 1 }, - ActivationConditions = new LogicGroupDraft - { - Logic = "AND", - Rules = [new ConditionRuleDraft { Domain = "TurnTiming", Field = "IsOwnTurn", Comparator = "==", Value = "true" }] - }, - Costs = new CostGroupDraft - { - Logic = "AND", - Costs = [new CostDraft { Type = "SpiritPoints", Amount = 2, PickMode = "SelfPick", Chooser = "Self" }] - }, - Actions = new ActionGroupDraft - { - Logic = "AND", - Actions = - [ - new ActionDraft - { - Scope = "Battlefield", - TargetType = "Spirit", - Chooser = "Self", - Count = 1, - Filters = [new TypedFilterDraft { Type = "Property", Field = "Ownership", Comparator = "==", Value = "Opponent" }], - Effects = [new EffectDraft { Type = "DealDamage", Amount = 3, DurationMode = "Immediate", ParameterKey = "damageType", ParameterValue = "Arcane" }] - } - ] - } - }; - } - - private static AbilityDefinitionDraftR2 CreateTriggeredSample() - { - return new AbilityDefinitionDraftR2 - { - Name = "Ashwake Response", - Description = "When an allied spirit leaves a ruin, deal damage to a nearby enemy.", - Type = "Triggered", - Limits = new LimitDraft { PerTurn = 2, PerGame = 6 }, - Presentation = new PresentationDraft { Animation = "Burst", AnimationAsset = "fx/ashwake", CastSfx = "sfx/cast/ashwake", ImpactSfx = "sfx/hit/ashwake" }, - Triggered = new TriggeredDraft - { - EventFamily = "RuinOccupancy", - EventType = "RuinVacated", - LimitMode = "PerTurn", - OwnershipScope = "Ally", - AmountComparator = ">=", - Amount = 1, - SourceZoneGate = ["Battlefield", "Hand"], - Filters = - [ - new TypedFilterDraft { Type = "Property", Field = "RuinAffinity", Comparator = "==", Value = "Ash", ParameterKey = "includeDisabled", ParameterValue = "false" } - ] - }, - ActivationConditions = new LogicGroupDraft - { - Logic = "AND", - Rules = [new ConditionRuleDraft { Domain = "TurnTiming", Field = "CurrentPlayer", Comparator = "==", Value = "Owner" }], - Groups = - [ - new LogicGroupDraft - { - Logic = "OR", - Rules = - [ - new ConditionRuleDraft { Domain = "PlayerProperties", Field = "SpiritPoints", Comparator = ">=", Value = "2" }, - new ConditionRuleDraft { Domain = "BattlefieldState", Field = "ControlledRuins", Comparator = ">=", Value = "1" } - ] - } - ] - }, - Costs = new CostGroupDraft - { - Logic = "OR", - Costs = - [ - new CostDraft { Type = "SpiritPoints", Amount = 1, PickMode = "SelfPick", Chooser = "Self" }, - new CostDraft { Type = "DiscardFromHand", Amount = 1, PickMode = "EnemySeePick", Chooser = "Owner", MetadataKey = "visibilityPolicy", MetadataValue = "RevealChosenCard" } - ] - }, - Actions = new ActionGroupDraft - { - Logic = "AND", - Actions = - [ - new ActionDraft - { - Scope = "Battlefield", - TargetType = "Spirit", - Chooser = "System", - Count = 1, - Filters = - [ - new TypedFilterDraft { Type = "Property", Field = "Ownership", Comparator = "==", Value = "Opponent" }, - new TypedFilterDraft { Type = "StatThreshold", Field = "DistanceFromSource", Comparator = "<=", Value = "2" } - ], - Effects = - [ - new EffectDraft { Type = "DealDamage", Amount = 2, DurationMode = "Immediate", ParameterKey = "damageType", ParameterValue = "Ash" }, - new EffectDraft { Type = "ModifyStat", Amount = 1, DurationMode = "UntilEndOfTurn", ParameterKey = "stat", ParameterValue = "DefenseDelta:-1" } - ] - } - ] - } - }; - } - - private sealed class AbilityDefinitionDraftR2 - { - public string Name { get; set; } = string.Empty; - public string Description { get; set; } = string.Empty; - public string Type { get; set; } = "Active"; - public LimitDraft Limits { get; set; } = new(); - public PresentationDraft Presentation { get; set; } = new(); - public LogicGroupDraft ActivationConditions { get; set; } = new(); - public ActiveDraft Active { get; set; } = new(); - public TriggeredDraft Triggered { get; set; } = new(); - public PassiveDraft Passive { get; set; } = new(); - public AuraDraft Aura { get; set; } = new(); - public CostGroupDraft Costs { get; set; } = new(); - public ActionGroupDraft Actions { get; set; } = new(); - } - - private sealed class LimitDraft { public int? PerTurn { get; set; } public int? PerGame { get; set; } } - private sealed class PresentationDraft { public string Animation { get; set; } = string.Empty; public string AnimationAsset { get; set; } = string.Empty; public string CastSfx { get; set; } = string.Empty; public string ImpactSfx { get; set; } = string.Empty; } - private sealed class ActiveDraft { public int? RangeMin { get; set; } public int? RangeMax { get; set; } public bool RequiresLos { get; set; } public bool LinearOnly { get; set; } public int? UsesPerTurn { get; set; } } - private sealed class TriggeredDraft { public string EventFamily { get; set; } = "Lifecycle"; public string EventType { get; set; } = "TurnStarted"; public string LimitMode { get; set; } = "Unlimited"; public List SourceZoneGate { get; set; } = ["Battlefield"]; public string OwnershipScope { get; set; } = "Any"; public string AmountComparator { get; set; } = ">="; public int? Amount { get; set; } public List Filters { get; set; } = new(); } - private sealed class PassiveDraft { public string ContinuousScope { get; set; } = "Self"; public string RecheckCadence { get; set; } = "Continuous"; public string SourceLeavePolicy { get; set; } = "Persist"; } - private sealed class AuraDraft { public int? RangeMin { get; set; } public int? RangeMax { get; set; } public string EnterHook { get; set; } = string.Empty; public string LeaveHook { get; set; } = string.Empty; public string LeavePolicy { get; set; } = "Persist"; public string LingerDuration { get; set; } = string.Empty; } - 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 ConditionRuleDraft { public string Domain { get; set; } = "TurnTiming"; public string Field { get; set; } = string.Empty; public string Comparator { get; set; } = "=="; public string Value { get; set; } = string.Empty; public string ParameterKey { get; set; } = string.Empty; public string ParameterValue { get; set; } = string.Empty; } - private sealed class CostGroupDraft { public string Logic { get; set; } = "AND"; public List Costs { get; set; } = new(); public List Groups { get; set; } = new(); } - private sealed class CostDraft { public string Type { get; set; } = "SpiritPoints"; public int? Amount { get; set; } = 1; public string PickMode { get; set; } = "SelfPick"; public string Chooser { get; set; } = "Self"; public string MetadataKey { get; set; } = string.Empty; public string MetadataValue { get; set; } = string.Empty; } - private sealed class ActionGroupDraft { public string Logic { get; set; } = "AND"; public List Actions { get; set; } = new(); public List Groups { get; set; } = new(); } - private sealed class ActionDraft { public string Scope { get; set; } = "Battlefield"; public string TargetType { get; set; } = "Spirit"; public string Chooser { get; set; } = "Self"; public int? Count { get; set; } = 1; public List Filters { get; set; } = new(); public LogicGroupDraft Conditions { get; set; } = new(); public List Effects { get; set; } = new(); } - private sealed class TypedFilterDraft { public string Type { get; set; } = "Property"; public string Field { get; set; } = string.Empty; public string Comparator { get; set; } = "=="; public string Value { get; set; } = string.Empty; public string ParameterKey { get; set; } = string.Empty; public string ParameterValue { get; set; } = string.Empty; } - private sealed class EffectDraft { public string Type { get; set; } = "DealDamage"; public int? Amount { get; set; } = 1; public string DurationMode { get; set; } = "Immediate"; public int? DurationN { get; set; } = 1; public string ParameterKey { get; set; } = string.Empty; public string ParameterValue { get; set; } = string.Empty; } - private sealed record ValidationIssue(string Severity, string Code, string Path, string Message, string SuggestedFix); -} diff --git a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilderR3.razor b/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilderR3.razor deleted file mode 100644 index 8611afd..0000000 --- a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilderR3.razor +++ /dev/null @@ -1,2042 +0,0 @@ -@page "/cards/ability-builder-r3" -@rendermode InteractiveServer -@inject IJSRuntime JS - -Ability Builder R3 - - - - - - - - -
-
- ⚡ 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(); -} -}