diff --git a/Server/src/SOR.Ai/Core/AiPlayerSession.cs b/Server/src/SOR.Ai/Core/AiPlayerSession.cs index edf5913..204700c 100644 --- a/Server/src/SOR.Ai/Core/AiPlayerSession.cs +++ b/Server/src/SOR.Ai/Core/AiPlayerSession.cs @@ -328,6 +328,10 @@ internal sealed class AiPlayerSession : IAsyncDisposable { return action switch { + AiActivateAbilityAction abil => + Msg("game.activate_ability", + new GameActivateAbilityRequest(SessionId, abil.UnitInstanceId, abil.AbilityIndex, abil.Targets)), + AiDrawAction => Msg("game.draw", new GameDrawRequest(SessionId)), diff --git a/Server/src/SOR.Ai/Engine/IAiDecisionEngine.cs b/Server/src/SOR.Ai/Engine/IAiDecisionEngine.cs index 322f9dc..e1195b4 100644 --- a/Server/src/SOR.Ai/Engine/IAiDecisionEngine.cs +++ b/Server/src/SOR.Ai/Engine/IAiDecisionEngine.cs @@ -1,6 +1,7 @@ namespace SOR.Ai.Engine; using SOR.Ai.Core; +using SOR.Game; using SOR.Game.Grid; /// @@ -50,10 +51,15 @@ internal sealed record AiAttackAction( string AttackerInstanceId, string TargetInstanceId) : AiAction; -/// Activate an active ability (no target required for Phase 2). +/// +/// Activate an Active ability on a field unit. +/// Targets is null when all actions are auto-resolved (Random/Self/All). +/// One AbilityTarget per client-pick action when player input is required. +/// internal sealed record AiActivateAbilityAction( - string UnitInstanceId, - int AbilityIndex) : AiAction; + string UnitInstanceId, + int AbilityIndex, + IReadOnlyList? Targets = null) : AiAction; /// Sacrifice a Spirit adjacent to the AI's ArchSpirit. internal sealed record AiSacrificeAction(string UnitInstanceId) : AiAction; diff --git a/Server/src/SOR.Ai/Heuristics/ActionCandidateGenerator.cs b/Server/src/SOR.Ai/Heuristics/ActionCandidateGenerator.cs index b978218..47b0981 100644 --- a/Server/src/SOR.Ai/Heuristics/ActionCandidateGenerator.cs +++ b/Server/src/SOR.Ai/Heuristics/ActionCandidateGenerator.cs @@ -4,8 +4,11 @@ using SOR.Ai.Core; using SOR.Ai.Engine; using SOR.Database.Enums; using SOR.Game; +using SOR.Game.Abilities; +using SOR.Game.Abilities.Models; using SOR.Game.Combat; using SOR.Game.Grid; +using AbilityAction = SOR.Game.Abilities.Models.Action; /// /// Enumerates every legal action available to the AI on its current turn. @@ -34,6 +37,7 @@ internal static class ActionCandidateGenerator result.AddRange(AllAttacks(ctx)); result.AddRange(Sacrifices(ctx)); result.AddRange(AscendCandidates(ctx)); + result.AddRange(ActivateAbilityCandidates(ctx)); return result; } @@ -326,6 +330,190 @@ internal static class ActionCandidateGenerator return candidates; } + // ── Activate Ability ────────────────────────────────────────────────────── + + /// + /// Enumerates all usable Active abilities on the AI's field units, with target + /// candidates for abilities that require player-chosen targets. + /// + /// For abilities where all targeting is auto-resolved (Random, Self, All, chained), + /// one targetless candidate is emitted. For abilities with a single client-pick + /// action, one candidate is emitted per valid target. Multi-pick and ChooseOne + /// abilities emit a single null-target candidate (server resolves best-effort). + /// + /// Invalid candidates are silently discarded by the heuristic engine's simulation + /// try/catch, so over-generation is safe. + /// + public static IReadOnlyList ActivateAbilityCandidates(AiTurnContext ctx) + { + var result = new List(); + var player = ctx.AiPlayer; + var board = ctx.State.Board; + + foreach (var unit in AllFieldUnits(player)) + { + if (unit.IsExhausted || !unit.CanUseAbility) continue; + if (unit.AbilitiesJson is null) continue; + + AbilityDefinition[] abilities; + try { abilities = AbilitySystem.ParseAbilities(unit.AbilitiesJson); } + catch { continue; } + + for (int abilityIndex = 0; abilityIndex < abilities.Length; abilityIndex++) + { + var def = abilities[abilityIndex]; + if (def.Type != AbilityType.Active) continue; + + // Uses per turn. + int used = 0; + unit.AbilityUsesThisTurn?.TryGetValue(abilityIndex, out used); + if (used >= def.UsesPerTurn) continue; + + // Disabled by another effect. + if (def.Name is not null && unit.DisabledAbilities?.Contains(def.Name) == true) continue; + + // Cost check (SP and ST; other costs assumed payable — simulation validates). + if (!CanAffordCost(def.Cost, player)) continue; + + // Emit one candidate per valid target combination. + foreach (var targets in BuildTargetCandidates(def, unit, ctx, board)) + result.Add(new AiActivateAbilityAction(unit.InstanceId, abilityIndex, targets)); + } + } + + return result; + } + + private static bool CanAffordCost(CostEntry[]? costs, PlayerState player) + { + if (costs is null) return true; + foreach (var cost in costs) + { + switch (cost.Type) + { + case CostType.SpiritPoints: if (player.CurrentSp < cost.Amount) return false; break; + case CostType.SacrificeTokens: if (player.CurrentSt < cost.Amount) return false; break; + case CostType.DiscardFromHand: if (player.Hand.Count < cost.Amount) return false; break; + } + } + return true; + } + + /// + /// Yields one IReadOnlyList<AbilityTarget>? per target combination. + /// null means "no client targets" (server auto-resolves all actions). + /// + private static IEnumerable?> BuildTargetCandidates( + AbilityDefinition def, FieldCard source, AiTurnContext ctx, Board? board) + { + var clientPickActions = def.Actions + .Select((a, i) => (action: a, index: i)) + .Where(x => AbilityActionNeedsClientInput(x.action)) + .ToList(); + + // No client picks needed — one candidate, server auto-resolves. + if (clientPickActions.Count == 0) + { + yield return null; + yield break; + } + + // ChooseOne: server defaults to branch 0. + if (clientPickActions.Any(x => x.action.ChooseOne is { Branches.Length: > 0 })) + { + yield return null; + yield break; + } + + // Single client-pick action: one candidate per valid target. + if (clientPickActions.Count == 1) + { + var (action, actionIdx) = clientPickActions[0]; + bool any = false; + foreach (var tgt in EnumerateActionTargets(action, actionIdx, source, ctx, board, def.Range)) + { + any = true; + yield return [tgt]; + } + if (!any) yield return null; // no targets found — let simulation reject it + yield break; + } + + // Multiple client-pick actions: emit null and let simulation handle. + yield return null; + } + + /// + /// Replicates AbilitySystem.ActionNeedsClientTargets (internal) logic. + /// Returns true when the action requires a player-chosen target. + /// + private static bool AbilityActionNeedsClientInput(AbilityAction action) + { + if (action.ChooseOne is { Branches.Length: > 0 }) return true; + var sel = action.Target; + if (sel.Type == TargetType.Player) return false; + if (sel.Count.All) return false; + return sel.Ownership is not ( + TargetOwnership.Self or + TargetOwnership.ExactSelf or + TargetOwnership.Target or + TargetOwnership.Random); + } + + private static IEnumerable EnumerateActionTargets( + AbilityAction action, int actionIdx, + FieldCard source, AiTurnContext ctx, Board? board, + AbilityRange? range) + { + var sel = action.Target; + var state = ctx.State; + + if (sel.Scope == TargetScope.Battlefield) + { + bool wantEnemy = sel.Ownership is TargetOwnership.Enemy; + bool wantAlly = sel.Ownership is TargetOwnership.Ally or TargetOwnership.Owner; + bool wantAny = sel.Ownership is TargetOwnership.Any; + + var pool = new List(); + if (wantEnemy || wantAny) + foreach (var id in ctx.OpponentIds) + pool.AddRange(AllFieldUnits(state.Players[id])); + if (wantAlly || wantAny) + pool.AddRange(AllFieldUnits(ctx.AiPlayer)); + + foreach (var target in pool) + { + if (target.Position is null) continue; + + // Type filter. + if (sel.Type == TargetType.ArchSpirit && !target.IsLeader) continue; + if (sel.Type == TargetType.Spirit && target.IsLeader) continue; + + // Range filter. + if (range is not null && source.Position.HasValue && + !IsWithinAbilityRange(source.Position.Value, target.Position.Value, range, board)) + continue; + + yield return new AbilityTarget(actionIdx, InstanceId: target.InstanceId); + } + } + else if (sel.Scope == TargetScope.Hand) + { + // Hand targets: only the AI's own hand is pickable. + foreach (var card in ctx.AiPlayer.Hand) + yield return new AbilityTarget(actionIdx, InstanceId: card.InstanceId); + } + // Deck / Discard / AnyZone: too varied to enumerate safely — caller yields null. + } + + private static bool IsWithinAbilityRange(Coord from, Coord to, AbilityRange range, Board? board) + { + int dist = board?.HexSides > 0 + ? HexGrid.Distance(from, to, board.HexSides) + : from.ManhattanDistance(to); + return dist >= range.Min && dist <= range.Max; + } + // ── Helpers ─────────────────────────────────────────────────────────────── private static IEnumerable AllFieldUnits(PlayerState player) diff --git a/Server/src/SOR.Ai/Heuristics/HeuristicDecisionEngine.cs b/Server/src/SOR.Ai/Heuristics/HeuristicDecisionEngine.cs index 03b7d95..06dcd4f 100644 --- a/Server/src/SOR.Ai/Heuristics/HeuristicDecisionEngine.cs +++ b/Server/src/SOR.Ai/Heuristics/HeuristicDecisionEngine.cs @@ -135,6 +135,10 @@ internal sealed class HeuristicDecisionEngine : IAiDecisionEngine GameEngine.Attack(state, actorId, atk.AttackerInstanceId, atk.TargetInstanceId); break; + case AiActivateAbilityAction abil: + GameEngine.ActivateAbility(state, actorId, abil.UnitInstanceId, abil.AbilityIndex, abil.Targets); + break; + case AiSacrificeAction sac: GameEngine.Sacrifice(state, actorId, sac.UnitInstanceId); break;