Implement triggered ability target prompting (Option D)
When a Triggered ability fires and any of its actions require a human target
pick, the server now pauses execution instead of auto-resolving:
Server:
- AbilitySystem.FireTrigger detects actions needing client input via
ActionNeedsClientTargets(); stores PendingTriggeredTarget in GameState and
returns early rather than executing the ability
- PushStateToPlayersAsync (GameHandlerBase) checks for PendingTriggeredTarget
after every state push and sends a game.ability.triggered_target_request push
to the owning player carrying the action definition and range
- New GameTriggeredTargetHandler (game.triggered_target) receives the player's
picks, calls AbilitySystem.ResumeTriggeredAbility, and broadcasts the result
- PendingTriggeredTarget model stored in GameState.PendingTriggeredTarget (JSONB)
Client:
- Game.gd handles the triggered_target_request push and emits a signal
- game_screen.gd connects the signal, re-uses the existing ABILITY_TARGET mode
and _start_ability_targeting() flow, then sends game.triggered_target instead
of game.activate_ability when done
- A brief banner ("Triggered: <name> — select a target") informs the player
"Warrant Cover" (OnChanneled, Owner unit pick) will now correctly prompt the
player to select which friendly unit gains +1 Defense.
Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -46,6 +46,10 @@ signal player_eliminated(session_id: String, eliminated_account_id: String, seat
|
||||
## event_type: "started" | "ended"
|
||||
signal game_activity(event_type: String, session_id: String)
|
||||
|
||||
## Emitted when a Triggered ability needs the local player to pick a target.
|
||||
## Payload keys: requestId, sourceInstanceId, abilityName, actionJson, rangeJson
|
||||
signal triggered_target_request(request_data: Dictionary)
|
||||
|
||||
# ── State ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
var session_id : String = ""
|
||||
@@ -333,6 +337,13 @@ func send_activate_ability(source_id: String, ability_index: int,
|
||||
payload["targets"] = targets
|
||||
_game_request("game.activate_ability", payload)
|
||||
|
||||
|
||||
func send_triggered_target_response(request_id: String, targets: Array) -> void:
|
||||
var payload : Dictionary = { "requestId": request_id }
|
||||
if not targets.is_empty():
|
||||
payload["targets"] = targets
|
||||
_game_request("game.triggered_target", payload)
|
||||
|
||||
# ── Private ───────────────────────────────────────────────────────────────────
|
||||
|
||||
func _game_request(msg_type: String, extra: Dictionary) -> void:
|
||||
@@ -648,3 +659,6 @@ func _on_server_push(type: String, payload: Variant) -> void:
|
||||
var ev_type : String = str(d.get("eventType", ""))
|
||||
var ev_sid : String = str(d.get("sessionId", ""))
|
||||
game_activity.emit(ev_type, ev_sid)
|
||||
|
||||
"game.ability.triggered_target_request":
|
||||
triggered_target_request.emit(payload as Dictionary)
|
||||
|
||||
@@ -152,6 +152,10 @@ var _ability_confirm_btn : Control = null # "Done" button shown for Up
|
||||
var _ability_branch_panel : Control = null # ChooseOne branch selector panel
|
||||
var _player_panel : Control = null
|
||||
|
||||
# Triggered ability target prompting
|
||||
var _is_triggered_target : bool = false # true when targeting for a server-paused trigger
|
||||
var _triggered_request_id : String = "" # requestId to echo back in the response
|
||||
|
||||
# Tile detail drawer (right-side slide-in panel)
|
||||
var _tile_drawer : PanelContainer = null
|
||||
var _tile_drawer_open : bool = false
|
||||
@@ -256,6 +260,7 @@ func _ready() -> void:
|
||||
get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn"))
|
||||
_hold_timer.timeout.connect(_on_hold_timer_fired)
|
||||
_create_tile_drawer()
|
||||
Game.triggered_target_request.connect(_on_triggered_target_request)
|
||||
|
||||
# Chat overlay — add to viewport root so it renders above everything.
|
||||
var _chat_overlay := _CHAT_OVERLAY_SCENE.instantiate()
|
||||
@@ -308,6 +313,8 @@ func _exit_tree() -> void:
|
||||
Game.player_eliminated.disconnect(_on_player_eliminated)
|
||||
if Game.game_activity.is_connected(_on_game_activity):
|
||||
Game.game_activity.disconnect(_on_game_activity)
|
||||
if Game.triggered_target_request.is_connected(_on_triggered_target_request):
|
||||
Game.triggered_target_request.disconnect(_on_triggered_target_request)
|
||||
if Settings.settings_changed.is_connected(_on_skybox_setting_changed):
|
||||
Settings.settings_changed.disconnect(_on_skybox_setting_changed)
|
||||
_reset_unit_hover_glow()
|
||||
@@ -3220,13 +3227,73 @@ func _hide_branch_panel() -> void:
|
||||
|
||||
## Fire the ability request with all collected targets.
|
||||
func _send_ability() -> void:
|
||||
if not _ability_card_id.is_empty():
|
||||
if _is_triggered_target:
|
||||
_is_triggered_target = false
|
||||
var rid := _triggered_request_id
|
||||
_triggered_request_id = ""
|
||||
Game.send_triggered_target_response(rid, _ability_targets)
|
||||
elif not _ability_card_id.is_empty():
|
||||
Game.send_play_card_with_targets(_ability_card_id, _ability_targets)
|
||||
else:
|
||||
Game.send_activate_ability(_ability_unit_id, _ability_idx, _ability_targets)
|
||||
_set_mode(Mode.NONE)
|
||||
|
||||
|
||||
## Called when the server pushes a triggered_target_request for this player.
|
||||
## Sets up the standard ability-targeting UI re-using the existing ABILITY_TARGET mode.
|
||||
func _on_triggered_target_request(req: Dictionary) -> void:
|
||||
# If already in a targeting mode, cancel it first to avoid stacking.
|
||||
if _mode != Mode.NONE:
|
||||
_set_mode(Mode.NONE)
|
||||
|
||||
_is_triggered_target = true
|
||||
_triggered_request_id = str(req.get("requestId", ""))
|
||||
_ability_unit_id = str(req.get("sourceInstanceId", ""))
|
||||
_ability_idx = -1
|
||||
_ability_card_id = ""
|
||||
_ability_target_conditions = []
|
||||
|
||||
# Parse and normalise the action definition sent by the server.
|
||||
var action_json : String = str(req.get("actionJson", "{}"))
|
||||
var action_raw = JSON.parse_string(action_json)
|
||||
if action_raw is Dictionary:
|
||||
_ability_def = [_normalize_keys(action_raw)]
|
||||
elif action_raw is Array:
|
||||
_ability_def = _normalize_keys(action_raw) as Array
|
||||
else:
|
||||
_ability_def = []
|
||||
|
||||
var range_json : String = str(req.get("rangeJson", ""))
|
||||
if not range_json.is_empty() and range_json != "null":
|
||||
var r = JSON.parse_string(range_json)
|
||||
_ability_range = _normalize_keys(r) as Dictionary if r is Dictionary else {}
|
||||
else:
|
||||
_ability_range = {}
|
||||
|
||||
_ability_targets = []
|
||||
_ability_cur_action_idx = 0
|
||||
_ability_target_n = 1
|
||||
_ability_target_up_to = false
|
||||
_ability_targets_this_action = 0
|
||||
|
||||
_show_triggered_banner(str(req.get("abilityName", "Triggered Ability")))
|
||||
_start_ability_targeting()
|
||||
|
||||
|
||||
## Brief top-centre banner indicating a triggered ability needs player input.
|
||||
func _show_triggered_banner(ability_name: String) -> void:
|
||||
var lbl := Label.new()
|
||||
lbl.text = "Triggered: %s — select a target" % ability_name
|
||||
lbl.set_anchors_preset(Control.PRESET_TOP_WIDE)
|
||||
lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
|
||||
lbl.position = Vector2(0, 72)
|
||||
lbl.add_theme_font_size_override("font_size", 15)
|
||||
lbl.modulate = Color(1.0, 0.85, 0.2)
|
||||
_hud.add_child(lbl)
|
||||
get_tree().create_timer(4.0).timeout.connect(func() -> void:
|
||||
if is_instance_valid(lbl): lbl.queue_free())
|
||||
|
||||
|
||||
## Show a left-side panel to let the player select a player (and optionally a
|
||||
## zone) as the ability target.
|
||||
func _show_player_panel(scope: String, ownership: String) -> void:
|
||||
|
||||
@@ -228,6 +228,26 @@ public static class AbilitySystem
|
||||
_triggerCountsPerTurn[key] = used + 1;
|
||||
}
|
||||
|
||||
// If any action needs a human pick, pause and request client input.
|
||||
if (def.Actions.Any(ActionNeedsClientTargets))
|
||||
{
|
||||
state.PendingTriggeredTarget = new PendingTriggeredTarget
|
||||
{
|
||||
ActorId = ownerId,
|
||||
SourceInstanceId = unit.InstanceId,
|
||||
AbilityName = def.Name ?? "Triggered Ability",
|
||||
ActionsJson = JsonSerializer.Serialize(def.Actions, _jsonOpts),
|
||||
RangeJson = def.Range is not null
|
||||
? JsonSerializer.Serialize(def.Range, _jsonOpts)
|
||||
: null,
|
||||
ForceDurationJson = def.Duration is not null
|
||||
? JsonSerializer.Serialize(def.Duration, _jsonOpts)
|
||||
: null,
|
||||
};
|
||||
// Return immediately — only one pending request at a time.
|
||||
return state;
|
||||
}
|
||||
|
||||
ExecuteActions(def.Actions, ctx, clientTargets: null, forceDuration: def.Duration);
|
||||
}
|
||||
}
|
||||
@@ -508,6 +528,89 @@ public static class AbilitySystem
|
||||
}
|
||||
}
|
||||
|
||||
// ── Triggered ability client-target detection & resume ────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Returns true when the action requires a human target pick rather than
|
||||
/// being fully server-auto-resolvable. Used by <see cref="FireTrigger"/> to
|
||||
/// decide whether to pause and request client input.
|
||||
/// Also called by <c>GameHandlerBase</c> to locate the first client-pick action
|
||||
/// for the <c>TriggeredTargetRequestPush</c> payload.
|
||||
/// </summary>
|
||||
internal static bool ActionNeedsClientTargets_Public(Models.Action action)
|
||||
=> ActionNeedsClientTargets(action);
|
||||
|
||||
private static bool ActionNeedsClientTargets(Models.Action action)
|
||||
{
|
||||
// ChooseOne always needs the player to pick a branch.
|
||||
if (action.ChooseOne is { Branches.Length: > 0 })
|
||||
return true;
|
||||
|
||||
var sel = action.Target;
|
||||
|
||||
// Player-type targets are always server-resolved.
|
||||
if (sel.Type == TargetType.Player)
|
||||
return false;
|
||||
|
||||
// "All" targets are enumerated server-side with no player choice.
|
||||
if (sel.Count.All)
|
||||
return false;
|
||||
|
||||
// These ownerships are auto-resolved: self, random, chained from prior action.
|
||||
return sel.Ownership is not (
|
||||
TargetOwnership.Self or
|
||||
TargetOwnership.ExactSelf or
|
||||
TargetOwnership.Target or
|
||||
TargetOwnership.Random);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resumes a triggered ability that was paused for client target input.
|
||||
/// Called by <c>GameTriggeredTargetHandler</c> once the player submits their picks.
|
||||
/// </summary>
|
||||
public static GameState ResumeTriggeredAbility(
|
||||
GameState state,
|
||||
string actorId,
|
||||
string requestId,
|
||||
IReadOnlyList<AbilityTarget> clientTargets)
|
||||
{
|
||||
var pending = state.PendingTriggeredTarget
|
||||
?? throw new GameException("NO_PENDING_TRIGGER");
|
||||
|
||||
if (pending.RequestId != requestId)
|
||||
throw new GameException("REQUEST_ID_MISMATCH");
|
||||
|
||||
if (pending.ActorId != actorId)
|
||||
throw new GameException("NOT_YOUR_TRIGGER");
|
||||
|
||||
// Clear before executing so any nested triggers don't see a stale request.
|
||||
state.PendingTriggeredTarget = null;
|
||||
|
||||
var actions = JsonSerializer.Deserialize<Models.Action[]>(pending.ActionsJson, _jsonOpts) ?? [];
|
||||
|
||||
// Source unit may have left the battlefield while waiting — skip silently if so.
|
||||
var source = state.Players.Values
|
||||
.SelectMany(p => p.Field).OfType<FieldCard>()
|
||||
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
|
||||
if (source is null) return state;
|
||||
|
||||
var ctx = new AbilityContext
|
||||
{
|
||||
State = state,
|
||||
ActorId = pending.ActorId,
|
||||
Source = source,
|
||||
};
|
||||
|
||||
DurationModel? forceDuration = pending.ForceDurationJson is not null
|
||||
? JsonSerializer.Deserialize<DurationModel>(pending.ForceDurationJson, _jsonOpts)
|
||||
: null;
|
||||
|
||||
ExecuteActions(actions, ctx, clientTargets, requireClientTargets: true,
|
||||
forceDuration: forceDuration);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
// ── Target resolution ─────────────────────────────────────────────────────
|
||||
|
||||
private static List<object> ResolveTargets(
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace SOR.Game.Abilities.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Stored in GameState when a Triggered ability fires but needs a human target pick.
|
||||
/// The engine pauses execution, pushes a request to the owning player, then resumes
|
||||
/// via GameTriggeredTargetHandler once the player submits their selection.
|
||||
/// </summary>
|
||||
public sealed class PendingTriggeredTarget
|
||||
{
|
||||
/// <summary>Correlation ID sent to the client so responses can be matched.</summary>
|
||||
public string RequestId { get; set; } = Guid.NewGuid().ToString("N");
|
||||
|
||||
/// <summary>AccountId of the player who must pick the target.</summary>
|
||||
public string ActorId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>InstanceId of the unit whose triggered ability is paused.</summary>
|
||||
public string SourceInstanceId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Display name of the ability (for client UI).</summary>
|
||||
public string AbilityName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// JSON-serialized <see cref="Action"/>[] — the full action list to execute on resume.
|
||||
/// </summary>
|
||||
public string ActionsJson { get; set; } = "[]";
|
||||
|
||||
/// <summary>JSON-serialized <see cref="AbilityRange"/>? — for client-side highlighting.</summary>
|
||||
public string? RangeJson { get; set; }
|
||||
|
||||
/// <summary>JSON-serialized <see cref="DurationModel"/>? — forceDuration applied to all actions.</summary>
|
||||
public string? ForceDurationJson { get; set; }
|
||||
}
|
||||
@@ -753,3 +753,32 @@ public sealed record AbilityTarget(
|
||||
CoordDto? Coord = null,
|
||||
/// <summary>Set for ChooseOne actions: the 0-based index of the chosen branch.</summary>
|
||||
int? BranchIndex = null);
|
||||
|
||||
// ── Triggered ability target prompting ───────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Pushed to the owning player when a Triggered ability fires and requires a
|
||||
/// manual target selection before it can complete.
|
||||
/// The client should enter ability-targeting mode using the provided action definition,
|
||||
/// then reply with <see cref="GameTriggeredTargetRequest"/>.
|
||||
/// </summary>
|
||||
public sealed record TriggeredTargetRequestPush(
|
||||
/// <summary>Correlation ID — must be echoed back in the response.</summary>
|
||||
string RequestId,
|
||||
/// <summary>InstanceId of the unit whose triggered ability is waiting.</summary>
|
||||
string SourceInstanceId,
|
||||
/// <summary>Display name of the ability, for UI labelling.</summary>
|
||||
string AbilityName,
|
||||
/// <summary>JSON-serialized <c>Action</c> for the first client-pick action.</summary>
|
||||
string ActionJson,
|
||||
/// <summary>JSON-serialized <c>AbilityRange</c>? — for client highlight validation. Null if no range.</summary>
|
||||
string? RangeJson);
|
||||
|
||||
/// <summary>
|
||||
/// Sent by the client to submit target picks for a pending triggered ability.
|
||||
/// </summary>
|
||||
public sealed record GameTriggeredTargetRequest(
|
||||
Guid SessionId,
|
||||
string RequestId,
|
||||
IReadOnlyList<AbilityTarget> Targets);
|
||||
|
||||
|
||||
@@ -93,6 +93,13 @@ public sealed class GameState
|
||||
/// Consumed on firing; cancelled when source unit leaves the battlefield.
|
||||
/// </summary>
|
||||
public List<PendingDeferredEffect> PendingDeferredEffects { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Non-null when a Triggered ability has fired but requires a human target selection
|
||||
/// before it can complete. The game is effectively "paused" until the owning player
|
||||
/// submits a <c>game.triggered_target</c> response.
|
||||
/// </summary>
|
||||
public Abilities.Models.PendingTriggeredTarget? PendingTriggeredTarget { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PlayerState
|
||||
|
||||
@@ -2,6 +2,7 @@ namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Game.Abilities;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Game;
|
||||
using SOR.Database.Enums;
|
||||
@@ -246,6 +247,31 @@ internal abstract class GameHandlerBase
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
// After the state update is sent to all players, check whether a triggered ability
|
||||
// is waiting for client target input and push the request to the owning player.
|
||||
if (state.PendingTriggeredTarget is { } pending)
|
||||
{
|
||||
// Build the ActionJson for the first client-pick action in the pending list.
|
||||
// We serialize only the first action that actually needs input so the client
|
||||
// gets a minimal, unambiguous definition (N=1 unit pick for "Warrant Cover", etc.)
|
||||
var firstClientPickAction = JsonSerializer
|
||||
.Deserialize<Abilities.Models.Action[]>(pending.ActionsJson)
|
||||
?.FirstOrDefault(AbilitySystem.ActionNeedsClientTargets_Public);
|
||||
|
||||
var actionJson = firstClientPickAction is not null
|
||||
? JsonSerializer.Serialize(firstClientPickAction)
|
||||
: pending.ActionsJson; // fallback: send raw actions list
|
||||
|
||||
await clientPush.PushAsync(pending.ActorId,
|
||||
ServerMessage.Push("game.ability.triggered_target_request",
|
||||
new TriggeredTargetRequestPush(
|
||||
pending.RequestId,
|
||||
pending.SourceInstanceId,
|
||||
pending.AbilityName,
|
||||
actionJson,
|
||||
pending.RangeJson)), ct);
|
||||
}
|
||||
}
|
||||
|
||||
// OP config snapshot — read from RuleSnapshotJson at finalization time.
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Game.Abilities;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.triggered_target — player submits target picks for a paused triggered ability.
|
||||
///
|
||||
/// This handler is the counterpart to the <c>game.ability.triggered_target_request</c> push
|
||||
/// that the server sends whenever a Triggered ability fires and needs a human target pick.
|
||||
/// On receipt it resumes and fully resolves the paused ability, then broadcasts the
|
||||
/// updated game state to all players.
|
||||
/// </summary>
|
||||
internal sealed class GameTriggeredTargetHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
|
||||
public GameTriggeredTargetHandler(
|
||||
IMessageSerializer serializer,
|
||||
GameDbContext gameDb,
|
||||
IClientPush clientPush)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_clientPush = clientPush;
|
||||
}
|
||||
|
||||
public string MessageType => "game.triggered_target";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameTriggeredTargetRequest>(message.Payload);
|
||||
var actorId = connection.UserId;
|
||||
|
||||
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
|
||||
var prevStateJson = session.StateJson!;
|
||||
var state = GameEngine.Deserialize(prevStateJson);
|
||||
|
||||
var newState = AbilitySystem.ResumeTriggeredAbility(
|
||||
state, actorId, req.RequestId, req.Targets);
|
||||
|
||||
await SaveStateAsync(_gameDb, session, newState, actorId, "game.triggered_target",
|
||||
JsonSerializer.Serialize(req), ct);
|
||||
|
||||
var dto = GameEngine.ToDto(newState, actorId);
|
||||
await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson);
|
||||
|
||||
return ServerMessage.Reply("game.triggered_target.ack", message.Seq,
|
||||
new GameActivateAbilityResponse(dto));
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,9 @@ public static class ServiceRegistration
|
||||
// Team assignment handler (host reassigns seats to teams)
|
||||
services.AddTransient<IMessageHandler, GameReassignTeamHandler>();
|
||||
|
||||
// Triggered ability target response (player submits picks for a paused trigger)
|
||||
services.AddTransient<IMessageHandler, GameTriggeredTargetHandler>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user