feat: add active effects inspector to tile drawer

- Track active effects with human-readable labels in AbilitySystem
  (LabelFromReversal/LabelFromTick for stat mods, status flags, DOT/HOT)
- Add ActiveEffectDto to GameStateDto and GameStateDelta; delta now
  always includes the full effects list so clients are never stale
- Add ResolveLabelFromEffectJson fallback for effects stored before the
  Label field was introduced (old game sessions show correct labels)
- Client _append_active_effect_lines helper filters activeEffects by
  targetRef and appends formatted lines to the tile drawer for spirits,
  archspirits, spirit tokens, and ruins

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:
dingo
2026-04-14 11:52:37 -04:00
co-authored by Claude Happy
parent 144ad84cac
commit b4062d8179
8 changed files with 239 additions and 6 deletions
+5
View File
@@ -551,6 +551,11 @@ func _apply_delta(delta: Dictionary) -> void:
if meta.has("activePlayerAccountId") and meta["activePlayerAccountId"] != null: state["activePlayerAccountId"] = meta["activePlayerAccountId"] if meta.has("activePlayerAccountId") and meta["activePlayerAccountId"] != null: state["activePlayerAccountId"] = meta["activePlayerAccountId"]
if meta.has("turnNumber") and meta["turnNumber"] != null: state["turnNumber"] = int(meta["turnNumber"]) if meta.has("turnNumber") and meta["turnNumber"] != null: state["turnNumber"] = int(meta["turnNumber"])
# 10. Active effects (full replacement when changed)
var active_effects = delta.get("activeEffects")
if active_effects is Array:
state["activeEffects"] = active_effects
_state_version = int(delta.get("stateVersion", _state_version)) _state_version = int(delta.get("stateVersion", _state_version))
if debug_output: if debug_output:
print("[Game] delta applied ver=", _state_version, print("[Game] delta applied ver=", _state_version,
@@ -2964,12 +2964,49 @@ func _build_unit_detail_lines(unit: Dictionary, owner_id: String,
lines.append("Ability: %s" % ability_name) lines.append("Ability: %s" % ability_name)
tooltips.append(ability_desc) tooltips.append(ability_desc)
var unit_id: String = str(unit.get("instanceId", ""))
if not unit_id.is_empty():
_append_active_effect_lines(unit_id, lines, tooltips)
return { return {
"lines": lines, "lines": lines,
"tooltips": tooltips, "tooltips": tooltips,
} }
## Appends any active effects targeting [param target_ref] (unit instanceId or ruinId)
## into the provided [param lines] and [param tooltips] arrays.
func _append_active_effect_lines(target_ref: String, lines: Array, tooltips: Array) -> void:
if target_ref.is_empty():
return
var all_effects: Variant = Game.state.get("activeEffects")
if not all_effects is Array:
return
for ae: Dictionary in (all_effects as Array):
if str(ae.get("targetRef", "")) != target_ref:
continue
var label: String = str(ae.get("label", "?"))
var source_name: String = str(ae.get("sourceName", ""))
var dur_type: String = str(ae.get("durationType", ""))
var turns: int = int(ae.get("turnsRemaining", 0))
var dur_text: String
match dur_type:
"ForNTurns": dur_text = "%d turn%s" % [turns, "s" if turns != 1 else ""]
"UntilEndOfTurn": dur_text = "until end of turn"
"UntilStartOfOwnerTurn": dur_text = "until owner's next turn"
"UntilStartOfSourceOwnerTurn": dur_text = "until source's next turn"
"WhileSourceOnBattlefield": dur_text = "while source lives"
"WhileCondition": dur_text = "conditional"
_: dur_text = dur_type.to_lower().replace("_", " ")
var line: String
if source_name.is_empty() or source_name == ae.get("sourceInstanceId", ""):
line = "[Effect] %s (%s)" % [label, dur_text]
else:
line = "[Effect] %s (%s, from %s)" % [label, dur_text, source_name]
lines.append(line)
tooltips.append("")
func _set_tile_drawer_content(tile: Dictionary) -> void: func _set_tile_drawer_content(tile: Dictionary) -> void:
_tile_drawer_last_tile = tile.duplicate(true) _tile_drawer_last_tile = tile.duplicate(true)
_set_tile_drawer_button_state() _set_tile_drawer_button_state()
@@ -3043,7 +3080,9 @@ func _set_tile_drawer_content(tile: Dictionary) -> void:
"Ruin: %s" % ruin_id, "Ruin: %s" % ruin_id,
"Owner: %s" % Game.get_display_name(ruin_owner_id), "Owner: %s" % Game.get_display_name(ruin_owner_id),
] ]
_set_tile_drawer_lines(_tile_drawer_ruin_section, _tile_drawer_ruin_labels, ruin_lines) var ruin_tooltips : Array = ["", ""]
_append_active_effect_lines(ruin_id, ruin_lines, ruin_tooltips)
_set_tile_drawer_lines(_tile_drawer_ruin_section, _tile_drawer_ruin_labels, ruin_lines, ruin_tooltips)
else: else:
_set_tile_drawer_lines(_tile_drawer_ruin_section, _tile_drawer_ruin_labels, []) _set_tile_drawer_lines(_tile_drawer_ruin_section, _tile_drawer_ruin_labels, [])
@@ -2460,6 +2460,7 @@ public static class AbilitySystem
OwnerAccountId = ctx.ActorId, OwnerAccountId = ctx.ActorId,
}, _jsonOpts), }, _jsonOpts),
TurnsRemaining = duration.N ?? 0, TurnsRemaining = duration.N ?? 0,
Label = LabelFromReversal(reversal),
}); });
} }
@@ -2487,9 +2488,80 @@ public static class AbilitySystem
IsTick = true, IsTick = true,
}, _jsonOpts), }, _jsonOpts),
TurnsRemaining = duration.N ?? 0, TurnsRemaining = duration.N ?? 0,
Label = LabelFromTick(tickEffect),
}); });
} }
/// <summary>
/// Generates a human-readable label for the original applied effect,
/// given the stored reversal effect. E.g., ModifyDamageEffect{-2} → "ATK +2".
/// </summary>
private static string LabelFromReversal(Effect reversal) => reversal switch
{
ModifyHealthEffect e => $"HP {FormatDelta(-(e.Amount.Fixed ?? 0))}",
ModifyDefenseEffect e => $"DEF {FormatDelta(-(e.Amount.Fixed ?? 0))}",
ModifyDamageEffect e => $"ATK {FormatDelta(-(e.Amount.Fixed ?? 0))}",
ModifyMPEffect e => $"MP {FormatDelta(-(e.Amount.Fixed ?? 0))}",
ModifyMinAttackRangeEffect e => $"Min Range {FormatDelta(-(e.Amount.Fixed ?? 0))}",
ModifyMaxAttackRangeEffect e => $"Max Range {FormatDelta(-(e.Amount.Fixed ?? 0))}",
ModifyCostEffect e => LabelCostReversal(e),
ModifySPAccumulationEffect e => $"SP Acc {FormatDelta(-(e.Amount.Fixed ?? 0))}",
ModifyCardsDrawnPerTurnEffect e => $"Draw {FormatDelta(-(e.Amount.Fixed ?? 0))}/T",
SetMovementTypeEffect _ => "Move Type Changed",
SetAttackRangeEffect _ => "ATK Range Changed",
SetCanMoveEffect e => e.Value ? "Rooted" : "Move Granted",
SetCanAttackEffect e => e.Value ? "Can't Attack" : "Atk Granted",
SetCanDefendEffect e => e.Value ? "Can't Defend" : "Def Granted",
SetCanBeAttackedEffect e => e.Value ? "Untargetable" : "Targetable",
SetCanBeBlockedEffect e => e.Value ? "Unblockable" : "Blockable",
SetCanBeObstructedEffect e => e.Value ? "Unobstructed" : "Obstructed",
SetCanUseAbilityEffect e => e.Value ? "Ability Off" : "Ability On",
SetCanBeSacrificedEffect e => e.Value ? "No Sacrifice" : "Sacrifice OK",
SetCanDrawCardsEffect e => e.Value ? "No Draw" : "Draw Restored",
SetAccumulatesSPEffect e => e.Value ? "No SP Gain" : "SP Gain",
SetCanChannelSpiritEffect e => e.Value ? "No Channel" : "Channel OK",
SetCanSacrificeSpiritEffect e => e.Value ? "No Sacrifice" : "Sacrifice OK",
SetCanAscendArchSpiritEffect e => e.Value ? "No Ascend" : "Ascend OK",
SetCanTransitionArchSpiritEffect e => e.Value ? "No Transition" : "Transition OK",
SetCanChannelRepentanceEffect e => e.Value ? "No Repentance" : "Repentance OK",
SetCanChannelInstinctEffect e => e.Value ? "No Instinct" : "Instinct OK",
SetCanChannelRuinEffect e => e.Value ? "No Ruin" : "Ruin OK",
SetCanChannelTerramorphaMonoEffect e => e.Value ? "No T-Mono" : "T-Mono OK",
SetCanChannelTerramorphaDiEffect e => e.Value ? "No T-Di" : "T-Di OK",
SetCanChannelTerramorphaTriEffect e => e.Value ? "No T-Tri" : "T-Tri OK",
AddAbilityEffect e => $"Bonus: {e.AbilityDef.Name ?? "Ability"}",
RemoveAbilityEffect e => $"Stripped: {e.AbilityRef}",
EnableAbilityEffect e => $"Ability Off: {e.AbilityRef}",
DisableAbilityEffect e => $"Ability On: {e.AbilityRef}",
AddGenusEffect e => $"Genus: -{e.Tag}",
RemoveGenusEffect e => $"Genus: +{e.Tag}",
SetAffinityEffect _ => "Affinity Changed",
SetBaseAffinity1Effect _ => "Affinity Overridden",
SetBaseAffinity2Effect _ => "Affinity Overridden",
ClearPreventDeathEffect _ => "Death Shield",
ClearPreventNextDamageEffect _ => "Damage Block",
SetFixedSacrificeReturnEffect _ => "Sacrifice Override",
SetHealthMinimumEffect e => $"HP Min {e.Minimum}",
_ => reversal.GetType().Name.Replace("Effect", ""),
};
private static string LabelFromTick(Effect tick) => tick switch
{
DealDamageEffect e => $"Burn {e.Amount.Fixed ?? 0}/T",
HealEffect e => $"Regen {e.Amount.Fixed ?? 0}/T",
_ => tick.GetType().Name.Replace("Effect", ""),
};
private static string FormatDelta(int n) => n >= 0 ? $"+{n}" : $"{n}";
private static string LabelCostReversal(ModifyCostEffect e)
{
var parts = new System.Collections.Generic.List<string>();
if (e.Sp is { } sp && sp != 0) parts.Add($"SP {FormatDelta(-sp)}");
if (e.St is { } st && st != 0) parts.Add($"ST {FormatDelta(-st)}");
return parts.Count > 0 ? string.Join(", ", parts) : "Cost Changed";
}
/// <summary> /// <summary>
/// Fires DOT/HOT tick effects for the given player's turn. /// Fires DOT/HOT tick effects for the given player's turn.
/// Call at TurnEnd before expiry processing. /// Call at TurnEnd before expiry processing.
+84 -1
View File
@@ -1094,6 +1094,16 @@ public static class GameEngine
var boardDto = state.Board is not null ? ToBoardDto(state.Board) : null; var boardDto = state.Board is not null ? ToBoardDto(state.Board) : null;
var activeEffectDtos = state.ActiveEffects.Select(ae => new ActiveEffectDto(
SourceInstanceId : ae.SourceInstanceId,
SourceName : ResolveInstanceName(state, ae.SourceInstanceId),
TargetRef : ae.TargetRef,
Label : string.IsNullOrEmpty(ae.Label)
? ResolveLabelFromEffectJson(ae.EffectJson)
: ae.Label,
DurationType : ResolveDurationType(ae.DurationJson),
TurnsRemaining : ae.TurnsRemaining));
return new GameStateDto( return new GameStateDto(
SessionId : state.SessionId, SessionId : state.SessionId,
Phase : state.Phase.ToString(), Phase : state.Phase.ToString(),
@@ -1105,7 +1115,80 @@ public static class GameEngine
Board : boardDto, Board : boardDto,
SeatOrder : state.SeatOrder, SeatOrder : state.SeatOrder,
GameMode : state.GameMode, GameMode : state.GameMode,
TeamColors : state.TeamColors); TeamColors : state.TeamColors,
ActiveEffects : activeEffectDtos);
}
internal static string ResolveInstanceName(GameState state, string instanceId)
{
if (string.IsNullOrEmpty(instanceId)) return "";
foreach (var p in state.Players.Values)
{
foreach (var card in p.Field.OfType<CardInstance>())
if (card.InstanceId == instanceId) return card.Name;
if (p.ArchSpirit?.InstanceId == instanceId) return p.ArchSpirit.Name;
}
return instanceId;
}
/// <summary>
/// Fallback label for <see cref="ActiveEffect"/> entries stored before the Label field existed.
/// Parses the stored reversal/tick effect JSON using the $type discriminator.
/// NOTE: the stored effect is the *reversal*, so numeric amounts are negated to show the original.
/// </summary>
internal static string ResolveLabelFromEffectJson(string effectJson)
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(effectJson);
var root = doc.RootElement;
var type = root.TryGetProperty("$type", out var t) ? t.GetString() ?? "" : "";
static int NegAmount(System.Text.Json.JsonElement r)
{
if (r.TryGetProperty("amount", out var a) || r.TryGetProperty("Amount", out a))
if (a.TryGetProperty("fixed", out var f) || a.TryGetProperty("Fixed", out f))
if (f.TryGetInt32(out int v)) return -v;
return 0;
}
static string Fmt(int n) => n >= 0 ? $"+{n}" : $"{n}";
return type switch
{
"ModifyHealth" => $"HP {Fmt(NegAmount(root))}",
"ModifyDefense" => $"DEF {Fmt(NegAmount(root))}",
"ModifyDamage" => $"ATK {Fmt(NegAmount(root))}",
"ModifyMP" => $"MP {Fmt(NegAmount(root))}",
"DealDamage" => $"Burn {-NegAmount(root)}/T",
"Heal" => $"Regen {-NegAmount(root)}/T",
"SetCanMove" => "Rooted",
"SetCanAttack" => "Can't Attack",
"SetCanUseAbility" => "Ability Off",
"SetCanBeAttacked" => "Untargetable",
"__ClearPreventDeath" => "Death Shield",
"__ClearPreventNextDamage" => "Damage Block",
_ when !string.IsNullOrEmpty(type) => type,
_ => "Effect",
};
}
catch { return "Effect"; }
}
internal static string ResolveDurationType(string durationJson)
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(durationJson);
if (doc.RootElement.TryGetProperty("duration", out var dur) ||
doc.RootElement.TryGetProperty("Duration", out dur))
{
if (dur.TryGetProperty("type", out var t) ||
dur.TryGetProperty("Type", out t))
return t.GetString() ?? "Unknown";
}
}
catch { /* malformed — fall through */ }
return "Unknown";
} }
// ── Deck validation ─────────────────────────────────────────────────────── // ── Deck validation ───────────────────────────────────────────────────────
+15 -2
View File
@@ -519,7 +519,8 @@ public sealed record GameStateDelta(
IReadOnlyDictionary<string, PlayerStatsDelta>? PlayerStatsByAccount, IReadOnlyDictionary<string, PlayerStatsDelta>? PlayerStatsByAccount,
IReadOnlyDictionary<string, PublicCountsDelta>? PublicCountsByAccount, IReadOnlyDictionary<string, PublicCountsDelta>? PublicCountsByAccount,
PrivateViewerDelta? PrivateByViewer, PrivateViewerDelta? PrivateByViewer,
GameMetaDelta? MetaDelta); GameMetaDelta? MetaDelta,
IReadOnlyList<ActiveEffectDto>? ActiveEffects = null); // full replacement when changed
public sealed record TileDelta( public sealed record TileDelta(
int X, int X,
@@ -624,7 +625,19 @@ public sealed record GameStateDto(
BoardDto? Board, // full board state including tile affinities BoardDto? Board, // full board state including tile affinities
IEnumerable<string> SeatOrder, // account IDs in seat/turn order; empty = legacy 1v1 IEnumerable<string> SeatOrder, // account IDs in seat/turn order; empty = legacy 1v1
string GameMode, // "FFA" | "Teams" | "MultiTeam" string GameMode, // "FFA" | "Teams" | "MultiTeam"
Dictionary<int, string> TeamColors); // teamIndex → hex color e.g. "4488FF" Dictionary<int, string> TeamColors, // teamIndex → hex color e.g. "4488FF"
IEnumerable<ActiveEffectDto> ActiveEffects); // currently tracked duration effects
/// <summary>
/// Client-facing view of a single duration-tracked active effect.
/// </summary>
public sealed record ActiveEffectDto(
string SourceInstanceId,
string SourceName, // resolved display name of the source unit
string TargetRef, // InstanceId of target unit or AccountId of target player
string Label, // human-readable description of the applied effect e.g. "ATK +2"
string DurationType, // e.g. "UntilEndOfTurn", "ForNTurns", "WhileSourceOnBattlefield"
int TurnsRemaining); // non-zero only for ForNTurns
public sealed record PlayerStateDto( public sealed record PlayerStateDto(
Guid AccountId, Guid AccountId,
+3
View File
@@ -391,4 +391,7 @@ public sealed class ActiveEffect
/// <summary>Remaining turns for ForNTurns durations. Decremented at turn start.</summary> /// <summary>Remaining turns for ForNTurns durations. Decremented at turn start.</summary>
public int TurnsRemaining { get; set; } public int TurnsRemaining { get; set; }
/// <summary>Human-readable label describing the original applied effect (e.g. "ATK +2", "Rooted").</summary>
public string Label { get; set; } = string.Empty;
} }
+19 -2
View File
@@ -72,7 +72,8 @@ internal static class GameStateDiffer
PlayerStatsByAccount: statsByAccount, PlayerStatsByAccount: statsByAccount,
PublicCountsByAccount: countsByAccount, PublicCountsByAccount: countsByAccount,
PrivateByViewer: privateByViewer, PrivateByViewer: privateByViewer,
MetaDelta: metaDelta); MetaDelta: metaDelta,
ActiveEffects: DiffActiveEffects(next));
} }
/// <summary> /// <summary>
@@ -98,11 +99,27 @@ internal static class GameStateDiffer
PlayerStatsByAccount: statsByAccount, PlayerStatsByAccount: statsByAccount,
PublicCountsByAccount: countsByAccount, PublicCountsByAccount: countsByAccount,
PrivateByViewer: null, PrivateByViewer: null,
MetaDelta: metaDelta); MetaDelta: metaDelta,
ActiveEffects: DiffActiveEffects(next));
} }
// ── Helpers ─────────────────────────────────────────────────────────────── // ── Helpers ───────────────────────────────────────────────────────────────
/// <summary>
/// Always returns the full current active-effects list so every delta keeps the client in sync.
/// Active effects are a small collection; the overhead of always including them is negligible.
/// </summary>
private static IReadOnlyList<ActiveEffectDto> DiffActiveEffects(GameState next)
=> next.ActiveEffects.Select(ae => new ActiveEffectDto(
SourceInstanceId : ae.SourceInstanceId,
SourceName : GameEngine.ResolveInstanceName(next, ae.SourceInstanceId),
TargetRef : ae.TargetRef,
Label : string.IsNullOrEmpty(ae.Label)
? GameEngine.ResolveLabelFromEffectJson(ae.EffectJson)
: ae.Label,
DurationType : GameEngine.ResolveDurationType(ae.DurationJson),
TurnsRemaining : ae.TurnsRemaining)).ToList();
private static List<TileDelta>? DiffTiles(GameState prev, GameState next) private static List<TileDelta>? DiffTiles(GameState prev, GameState next)
{ {
if (prev.Board == null || next.Board == null) return null; if (prev.Board == null || next.Board == null) return null;
@@ -171,6 +171,7 @@ internal abstract class GameHandlerBase
d.PlayerStatsByAccount == null && d.PlayerStatsByAccount == null &&
d.PublicCountsByAccount == null && d.PublicCountsByAccount == null &&
d.PrivateByViewer == null; d.PrivateByViewer == null;
// ActiveEffects is excluded: it is always populated in every delta
var deltas = allIds.ToDictionary( var deltas = allIds.ToDictionary(
pid => pid, pid => pid,