feat(ability): implement AbilityBuilderR3 + engine additions
Engine: - AbilityDefinition: add SourceZoneGate (zone-restricted triggers) and TriggerLimitPerGame - Effects: add StatModOperator (Add/Subtract/Multiply/Divide/Percent) on all stat mod effects; reversal stored as delta - Action/CostEntry: add CostPickMode enum (Random/SelfPick/EnemySeePick/EnemyRandomPick/EnemyPick) - PendingCostPick: new model for interactive cost pause/resume (mirrors PendingTriggeredTarget) - GameState: PendingCostPick field - GameMessages: CostPickRequestPush, GameCostPickRequest, GameCostPickResponse records - AbilitySystem: FireTrigger scans Hand/Discard/Deck when SourceZoneGate set; per-game trigger limit tracking; ApplyStatOperator helper; PayCosts/ResumeCostPick for interactive cost flow - GameCostPickHandler + ServiceRegistration wiring Admin: - AbilityBuilderR3.razor: full ability builder at /cards/ability-builder-r3 (39 triggers, 69 effects, 32 conditions, form/canvas/mermaid modes, compiles to engine-native $type JSON) - AbilityBuilderR2-Draft.razor: fix switch expression no-best-type error Docs: - BuilderR3.md: master plan document Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
+1064
File diff suppressed because it is too large
Load Diff
@@ -67,6 +67,7 @@ var _message_poll_timer: Timer = null
|
||||
var _message_poll_in_flight: Dictionary = {}
|
||||
var _bubble_visible_requested := false
|
||||
var _bubble_host: Control = null
|
||||
var _bubble_visibility_owners: Dictionary = {}
|
||||
|
||||
const MESSAGE_POLL_INTERVAL_SEC := 0.2
|
||||
|
||||
@@ -112,6 +113,7 @@ func _on_auth_success(_uid: String, _dn: String) -> void:
|
||||
## (e.g. MainScreen._ready / _exit_tree).
|
||||
func set_bubble_visible(v: bool) -> void:
|
||||
_bubble_visible_requested = v
|
||||
_bubble_visibility_owners.clear()
|
||||
if is_instance_valid(_overlay):
|
||||
if _overlay.has_method("set_overlay_visible"):
|
||||
_overlay.call("set_overlay_visible", v)
|
||||
@@ -119,6 +121,20 @@ func set_bubble_visible(v: bool) -> void:
|
||||
_overlay.visible = v
|
||||
|
||||
|
||||
func claim_bubble_visibility(owner: Node) -> void:
|
||||
if not is_instance_valid(owner):
|
||||
return
|
||||
_bubble_visibility_owners[owner.get_instance_id()] = weakref(owner)
|
||||
_apply_bubble_visibility()
|
||||
|
||||
|
||||
func release_bubble_visibility(owner: Node) -> void:
|
||||
if not is_instance_valid(owner):
|
||||
return
|
||||
_bubble_visibility_owners.erase(owner.get_instance_id())
|
||||
_apply_bubble_visibility()
|
||||
|
||||
|
||||
func set_bubble_host(host: Control) -> void:
|
||||
_bubble_host = host
|
||||
if is_instance_valid(_overlay) and _overlay.has_method("set_bubble_host"):
|
||||
@@ -128,6 +144,7 @@ func set_bubble_host(host: Control) -> void:
|
||||
func _clear_state() -> void:
|
||||
_bubble_visible_requested = false
|
||||
_bubble_host = null
|
||||
_bubble_visibility_owners.clear()
|
||||
if is_instance_valid(_overlay):
|
||||
if _overlay.has_method("set_overlay_visible"):
|
||||
_overlay.call("set_overlay_visible", false)
|
||||
@@ -355,6 +372,27 @@ func _setup_message_polling() -> void:
|
||||
add_child(_message_poll_timer)
|
||||
|
||||
|
||||
func _apply_bubble_visibility() -> void:
|
||||
var stale_ids: Array = []
|
||||
var should_show := false
|
||||
for owner_id: Variant in _bubble_visibility_owners.keys():
|
||||
var owner_ref: WeakRef = _bubble_visibility_owners[owner_id]
|
||||
var owner : Variant = owner_ref.get_ref()
|
||||
if owner == null:
|
||||
stale_ids.append(owner_id)
|
||||
continue
|
||||
should_show = true
|
||||
for owner_id: Variant in stale_ids:
|
||||
_bubble_visibility_owners.erase(owner_id)
|
||||
|
||||
_bubble_visible_requested = should_show
|
||||
if is_instance_valid(_overlay):
|
||||
if _overlay.has_method("set_overlay_visible"):
|
||||
_overlay.call("set_overlay_visible", should_show)
|
||||
else:
|
||||
_overlay.visible = should_show
|
||||
|
||||
|
||||
func _start_message_polling() -> void:
|
||||
if is_instance_valid(_message_poll_timer):
|
||||
_message_poll_timer.start()
|
||||
|
||||
@@ -164,6 +164,9 @@ func _reload_collection() -> void:
|
||||
_coll_page = 1
|
||||
_coll_total = 0
|
||||
_has_more = false
|
||||
# A new query should supersede any in-flight collection request.
|
||||
# Stale responses are already filtered by request generation.
|
||||
_is_loading = false
|
||||
for child in _coll_list.get_children():
|
||||
child.queue_free()
|
||||
_load_more_btn.visible = false
|
||||
|
||||
@@ -128,7 +128,7 @@ func _build_fields(r: Dictionary) -> void:
|
||||
var sq_shape_row := fields_box.get_child(fields_box.get_child_count() - 1)
|
||||
|
||||
# Hex-only rows
|
||||
add_int.call("Hex Sides", "hexSides", 3, 10, 5, "Hexagon only: tiles per side (3–10)")
|
||||
add_int.call("Hex Sides", "hexSides", 3, 10, 6, "Hexagon only: tiles per side (3–10)")
|
||||
var hex_sides_row := fields_box.get_child(fields_box.get_child_count() - 1)
|
||||
|
||||
# Board template picker — filtered by current grid type.
|
||||
|
||||
@@ -41,14 +41,14 @@ var _deck_btn_group : ButtonGroup = null
|
||||
|
||||
func _ready() -> void:
|
||||
ContentCache.apply_scene_background(self)
|
||||
Chat.set_bubble_visible(true)
|
||||
Chat.claim_bubble_visibility(self)
|
||||
_setup_ui()
|
||||
_load_decks() # load decks first; lobbies load after decks arrive
|
||||
_refresh_lobbies()
|
||||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
Chat.set_bubble_visible(false)
|
||||
Chat.release_bubble_visibility(self)
|
||||
|
||||
# ── UI setup ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -56,12 +56,14 @@ var _team_panel : VBoxContainer = null # dynamically added team-controls
|
||||
|
||||
func _ready() -> void:
|
||||
ContentCache.apply_scene_background(self)
|
||||
Chat.claim_bubble_visibility(self)
|
||||
_setup_ui()
|
||||
_connect_signals()
|
||||
_refresh_display()
|
||||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
Chat.release_bubble_visibility(self)
|
||||
CustomLobby.guest_joined.disconnect(_on_guest_joined)
|
||||
CustomLobby.ready_status_changed.disconnect(_on_ready_status_changed)
|
||||
CustomLobby.lobby_rules_updated.disconnect(_on_rules_updated)
|
||||
|
||||
@@ -352,7 +352,7 @@ func _ready() -> void:
|
||||
HighlightConfig.texture_loaded.connect(_on_highlight_texture_loaded)
|
||||
|
||||
# Chat overlay — add to viewport root so it renders above everything.
|
||||
Chat.set_bubble_visible(true)
|
||||
Chat.claim_bubble_visibility(self)
|
||||
Chat.set_bubble_host(_chat_bubble_host)
|
||||
|
||||
if Game.is_spectating:
|
||||
@@ -410,7 +410,7 @@ func _exit_tree() -> void:
|
||||
func(_c: String, _m: String) -> void: pass)
|
||||
_clear_stars()
|
||||
Chat.set_bubble_host(null)
|
||||
Chat.set_bubble_visible(false)
|
||||
Chat.release_bubble_visibility(self)
|
||||
|
||||
|
||||
func _setup_spectator_ui() -> void:
|
||||
@@ -1215,6 +1215,14 @@ func _mouse_to_tile_coord(mouse_pos: Vector2) -> Vector2i:
|
||||
if body == null: return Vector2i(-1, -1)
|
||||
if body.has_meta("tile_coord"):
|
||||
return body.get_meta("tile_coord") as Vector2i
|
||||
if body.has_meta("unit_id"):
|
||||
var unit_id := str(body.get_meta("unit_id"))
|
||||
if not unit_id.is_empty():
|
||||
var unit := Game.get_unit_by_id(unit_id)
|
||||
if not unit.is_empty():
|
||||
var pos := unit.get("position", {}) as Dictionary
|
||||
if not pos.is_empty():
|
||||
return Vector2i(int(pos.get("x", -1)), int(pos.get("y", -1)))
|
||||
return Vector2i(-1, -1)
|
||||
|
||||
|
||||
@@ -1245,6 +1253,24 @@ func _is_friendly_unit(instance_id: String) -> bool:
|
||||
return _friendly_unit_ids.has(instance_id)
|
||||
|
||||
|
||||
func _is_ruin_unit(unit: Dictionary) -> bool:
|
||||
return str(unit.get("cardType", "")).to_lower() == "ruin"
|
||||
|
||||
|
||||
func _is_ruin_instance(instance_id: String) -> bool:
|
||||
if instance_id.is_empty():
|
||||
return false
|
||||
var unit := Game.get_unit_by_id(instance_id)
|
||||
return not unit.is_empty() and _is_ruin_unit(unit)
|
||||
|
||||
|
||||
func _tile_has_blocking_occupant(tile: Dictionary) -> bool:
|
||||
var occupant_id := str(tile.get("occupantId", ""))
|
||||
if occupant_id.is_empty() or occupant_id == "null":
|
||||
return false
|
||||
return not _is_ruin_instance(occupant_id)
|
||||
|
||||
|
||||
func _safe_arch(player: Dictionary) -> Dictionary:
|
||||
var arch = player.get("archSpirit")
|
||||
return arch as Dictionary if arch is Dictionary else {}
|
||||
@@ -1269,6 +1295,8 @@ func _rebuild_ownership(state: Dictionary) -> void:
|
||||
var is_ally : bool = (not is_mine) and (my_team_idx >= 0) and (team_idx == my_team_idx)
|
||||
var target : Dictionary = _friendly_unit_ids if (is_mine or is_ally) else _enemy_unit_ids
|
||||
for u: Dictionary in p.get("field", []):
|
||||
if _is_ruin_unit(u):
|
||||
continue
|
||||
var iid : String = u.get("instanceId", "")
|
||||
if not iid.is_empty():
|
||||
target[iid] = true
|
||||
@@ -2281,7 +2309,7 @@ func _update_prev_state(state: Dictionary) -> void:
|
||||
if unit.is_empty(): continue
|
||||
var iid := str(unit.get("instanceId", ""))
|
||||
if iid.is_empty(): continue
|
||||
_prev_unit_hp[iid] = int(unit.get("currentHealth", 0))
|
||||
_prev_unit_hp[iid] = int(unit.get("currentHealth") or 0)
|
||||
var pd = unit.get("position")
|
||||
if pd is Dictionary and not (pd as Dictionary).is_empty():
|
||||
_prev_unit_pos[iid] = Vector2i((pd as Dictionary).get("x", 0),
|
||||
@@ -2662,7 +2690,7 @@ func _valid_play_tiles(card: Dictionary) -> Array:
|
||||
var dist : int = _board_distance(tx, ty, ax, ay)
|
||||
if dist < min_r or dist > max_r: continue
|
||||
var tile : Dictionary = Game.get_tile(tx, ty)
|
||||
if tile.get("occupantId"): continue
|
||||
if _tile_has_blocking_occupant(tile): continue
|
||||
if card_affinity != "" and not _tile_matches_channel_affinity(tile, card_affinity): continue
|
||||
results.append(Vector2i(tx, ty))
|
||||
|
||||
@@ -2760,6 +2788,8 @@ func _valid_move_tiles(unit: Dictionary) -> Array:
|
||||
# Build blocked set from all occupants, excluding this unit.
|
||||
var blocked : Dictionary = {}
|
||||
for unit_dict : Dictionary in Game.get_field():
|
||||
if _is_ruin_unit(unit_dict):
|
||||
continue
|
||||
var up : Dictionary = unit_dict.get("position", {})
|
||||
if up.is_empty(): continue
|
||||
var cx : int = up.get("x", 0)
|
||||
@@ -2779,7 +2809,7 @@ func _valid_move_tiles(unit: Dictionary) -> Array:
|
||||
if not _tile_bodies.has("%d,%d" % [tx, ty]): continue
|
||||
var dist : int = _board_distance(tx, ty, ux, uy)
|
||||
if dist == 0 or dist > mp: continue
|
||||
if Game.get_tile(tx, ty).get("occupantId"): continue
|
||||
if _tile_has_blocking_occupant(Game.get_tile(tx, ty)): continue
|
||||
# Teleport additionally requires LOS to the destination.
|
||||
if mov == "teleport" and not _client_has_los(ux, uy, tx, ty): continue
|
||||
results.append(Vector2i(tx, ty))
|
||||
@@ -2792,12 +2822,14 @@ func _valid_attack_target_coords(unit: Dictionary) -> Array:
|
||||
if pos.is_empty(): return results
|
||||
var ux : int = pos.get("x", 0)
|
||||
var uy : int = pos.get("y", 0)
|
||||
var min_r : int = unit.get("minAttackRange", 1)
|
||||
var max_r : int = unit.get("maxAttackRange", 1)
|
||||
var min_r : int = int(unit.get("minAttackRange") or 1)
|
||||
var max_r : int = int(unit.get("maxAttackRange") or 1)
|
||||
var needs_los : bool = bool(unit.get("attackRequiresLos", false))
|
||||
if unit.get("isExhausted", false) and unit.get("extraAttacksRemaining", 0) == 0:
|
||||
return results
|
||||
for t: Dictionary in Game.get_all_enemy_units():
|
||||
if _is_ruin_unit(t):
|
||||
continue
|
||||
if not t.get("canBeAttacked", true): continue
|
||||
var _tpos = t.get("position")
|
||||
if not (_tpos is Dictionary): continue
|
||||
@@ -2818,8 +2850,8 @@ func _valid_attack_target_ids(unit: Dictionary) -> Array:
|
||||
if pos.is_empty(): return results
|
||||
var ux : int = pos.get("x", 0)
|
||||
var uy : int = pos.get("y", 0)
|
||||
var min_r : int = unit.get("minAttackRange", 1)
|
||||
var max_r : int = unit.get("maxAttackRange", 1)
|
||||
var min_r : int = int(unit.get("minAttackRange") or 1)
|
||||
var max_r : int = int(unit.get("maxAttackRange") or 1)
|
||||
var needs_los : bool = bool(unit.get("attackRequiresLos", false))
|
||||
if unit.get("isExhausted", false) and unit.get("extraAttacksRemaining", 0) == 0:
|
||||
return results
|
||||
@@ -2897,6 +2929,8 @@ func _valid_sacrifice_spirits() -> Array:
|
||||
var ax : int = arch_pos.get("x", 0)
|
||||
var ay : int = arch_pos.get("y", 0)
|
||||
for unit: Dictionary in Game.get_field():
|
||||
if _is_ruin_unit(unit):
|
||||
continue
|
||||
var up : Dictionary = unit.get("position", {})
|
||||
if up.is_empty(): continue
|
||||
var ux : int = up.get("x", 0)
|
||||
@@ -3402,7 +3436,7 @@ func _handle_board_click(mouse_pos: Vector2) -> void:
|
||||
var _t := Game.get_tile(coord.x, coord.y)
|
||||
var _raw_occ = _t.get("occupantId")
|
||||
var _occ : Variant = _raw_occ if _raw_occ is String else ""
|
||||
if not _occ.is_empty() and _occ != "null":
|
||||
if not _occ.is_empty() and _occ != "null" and not _is_ruin_instance(str(_occ)):
|
||||
unit_id = _occ
|
||||
# Show tile detail drawer and optionally pan camera.
|
||||
if coord.x >= 0:
|
||||
@@ -3479,7 +3513,7 @@ func _handle_board_click(mouse_pos: Vector2) -> void:
|
||||
var _t2 := Game.get_tile(coord.x, coord.y)
|
||||
var _raw_occ2 = _t2.get("occupantId")
|
||||
var _occ2 : Variant = _raw_occ2 if _raw_occ2 is String else ""
|
||||
if not _occ2.is_empty() and _occ2 != "null":
|
||||
if not _occ2.is_empty() and _occ2 != "null" and not _is_ruin_instance(str(_occ2)):
|
||||
unit_id = _occ2
|
||||
if not unit_id.is_empty():
|
||||
if _is_enemy_unit(unit_id):
|
||||
@@ -3546,6 +3580,7 @@ func _handle_board_click(mouse_pos: Vector2) -> void:
|
||||
func _select_unit(unit_id: String) -> void:
|
||||
var unit := Game.get_unit_by_id(unit_id)
|
||||
if unit.is_empty(): return
|
||||
if _is_ruin_unit(unit): return
|
||||
|
||||
_hide_ability_panel()
|
||||
_sel_unit_id = unit_id
|
||||
|
||||
@@ -22,7 +22,7 @@ extends Control
|
||||
func _ready() -> void:
|
||||
ContentCache.apply_scene_background(self)
|
||||
welcome_label.text = "Welcome, %s!" % Auth.display_name
|
||||
Chat.set_bubble_visible(true)
|
||||
Chat.claim_bubble_visibility(self)
|
||||
|
||||
Network.connected.connect(_update_status)
|
||||
Network.disconnected.connect(_update_status)
|
||||
@@ -56,7 +56,7 @@ func _ready() -> void:
|
||||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
Chat.set_bubble_visible(false)
|
||||
Chat.release_bubble_visibility(self)
|
||||
if Network.connected.is_connected(_update_status):
|
||||
Network.connected.disconnect(_update_status)
|
||||
if Network.disconnected.is_connected(_update_status):
|
||||
|
||||
@@ -449,7 +449,7 @@
|
||||
public int TimeLimitMinutes { get; set; } = 0;
|
||||
public int TurnLimit { get; set; } = 0;
|
||||
public int MpBuff { get; set; } = 0;
|
||||
public int StartingRandomTilePct { get; set; } = 0;
|
||||
public int StartingRandomTilePct { get; set; } = 75;
|
||||
public string BoardShape { get; set; } = "Default";
|
||||
public string GridType { get; set; } = "Square";
|
||||
public int HexSides { get; set; } = 6;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -36,6 +36,9 @@ public static class AbilitySystem
|
||||
// Runtime limiter for Triggered abilities: (source instance, ability key, turn) -> count
|
||||
private static readonly Dictionary<(string SourceInstanceId, string AbilityKey, int Turn), int> _triggerCountsPerTurn = new();
|
||||
|
||||
// Per-game trigger limiter: (session+source instance, ability key) -> count; never resets mid-game
|
||||
private static readonly Dictionary<(string SessionAndSource, string AbilityKey), int> _triggerCountsPerGame = new();
|
||||
|
||||
// Transient prevention markers.
|
||||
private static readonly Dictionary<string, int?> _preventNextDamageByUnit = new();
|
||||
private static readonly HashSet<string> _preventDeathUnits = new();
|
||||
@@ -106,11 +109,14 @@ public static class AbilitySystem
|
||||
if (!ValidateSourceActivationConditions(def, ctx, source))
|
||||
throw new GameException("ABILITY_CONDITION_NOT_MET");
|
||||
|
||||
if (def.Cost is { Length: > 0 })
|
||||
PayCost(def.Cost, ctx);
|
||||
|
||||
source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1;
|
||||
|
||||
if (def.Cost is { Length: > 0 })
|
||||
{
|
||||
bool paused = PayCosts(def.Cost, ctx, abilityIndex, def.Actions, def.Range, def.Duration);
|
||||
if (paused) return state; // waiting for client cost pick
|
||||
}
|
||||
|
||||
ExecuteActions(def.Actions, ctx, clientTargets, requireClientTargets: true, activationRange: def.Range, forceDuration: def.Duration);
|
||||
|
||||
return state;
|
||||
@@ -185,56 +191,98 @@ public static class AbilitySystem
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scans every battlefield unit for Triggered abilities matching the occurrence
|
||||
/// and fires each matching one. Called inline from GameEngine mutation methods.
|
||||
/// Scans every battlefield unit (and, when SourceZoneGate is set, hand/discard/deck cards)
|
||||
/// for Triggered abilities matching the occurrence and fires each matching one.
|
||||
/// Called inline from GameEngine mutation methods.
|
||||
/// </summary>
|
||||
public static GameState FireTrigger(GameState state, TriggerOccurrence occurrence)
|
||||
{
|
||||
foreach (var (ownerId, player) in state.Players)
|
||||
{
|
||||
var units = player.Field.OfType<FieldCard>().ToList(); // snapshot
|
||||
foreach (var unit in units)
|
||||
{
|
||||
// SetCanUseAbility(false) suppresses triggered ability firing for this unit.
|
||||
if (!unit.CanUseAbility) continue;
|
||||
// Build the set of cards to scan for triggered abilities.
|
||||
// Always include battlefield units. Cards with SourceZoneGate including
|
||||
// Hand/Discard/Deck are scanned from those zones too.
|
||||
var scanTargets = new List<(CardInstance Card, string Zone)>();
|
||||
foreach (var fc in player.Field.OfType<FieldCard>())
|
||||
scanTargets.Add((fc, "Battlefield"));
|
||||
foreach (var c in player.Hand)
|
||||
scanTargets.Add((c, "Hand"));
|
||||
foreach (var c in player.Discard)
|
||||
scanTargets.Add((c, "Discard"));
|
||||
foreach (var c in player.Deck)
|
||||
scanTargets.Add((c, "Deck"));
|
||||
|
||||
var abilities = ParseAbilities(unit.AbilitiesJson);
|
||||
foreach (var (card, zone) in scanTargets)
|
||||
{
|
||||
// SetCanUseAbility(false) suppresses triggered ability firing.
|
||||
if (card is FieldCard fc2 && !fc2.CanUseAbility) continue;
|
||||
|
||||
var abilities = ParseAbilities(card.AbilitiesJson);
|
||||
for (int i = 0; i < abilities.Length; i++)
|
||||
{
|
||||
var def = abilities[i];
|
||||
if (def.Type != AbilityType.Triggered) continue;
|
||||
if (def.TriggerEvent is null) continue;
|
||||
if (!TriggerMatches(def.TriggerEvent, occurrence, state, ownerId, unit)) continue;
|
||||
|
||||
// ── SourceZoneGate ────────────────────────────────────────
|
||||
// When a gate is configured, only fire when the card is in one of the
|
||||
// specified zones. When no gate is configured, apply the legacy rule:
|
||||
// only battlefield cards fire (skip non-battlefield cards).
|
||||
if (def.SourceZoneGate is { Length: > 0 })
|
||||
{
|
||||
if (!def.SourceZoneGate.Contains(zone, StringComparer.OrdinalIgnoreCase))
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
// No gate → legacy: only battlefield cards trigger.
|
||||
if (zone != "Battlefield") continue;
|
||||
}
|
||||
|
||||
if (!TriggerMatches(def.TriggerEvent, occurrence, state, ownerId,
|
||||
card is FieldCard fc3 ? fc3 : null)) continue;
|
||||
|
||||
var ctx = new AbilityContext
|
||||
{
|
||||
State = state,
|
||||
ActorId = ownerId,
|
||||
Source = unit,
|
||||
Source = card,
|
||||
EventData = occurrence.Data,
|
||||
};
|
||||
|
||||
if (def.ActivationConditions is { Length: > 0 })
|
||||
if (def.ActivationConditions.Any(c => !EvaluateCondition(c, ctx, unit)))
|
||||
if (def.ActivationConditions.Any(c => !EvaluateCondition(c, ctx, card)))
|
||||
continue;
|
||||
|
||||
// ── Per-turn limit ────────────────────────────────────────
|
||||
if (def.TriggerLimitPerTurn is > 0)
|
||||
{
|
||||
var abilityKey = !string.IsNullOrWhiteSpace(def.Name) ? def.Name! : $"idx:{i}";
|
||||
var key = (unit.InstanceId, abilityKey, state.TurnNumber);
|
||||
var key = (card.InstanceId, abilityKey, state.TurnNumber);
|
||||
_triggerCountsPerTurn.TryGetValue(key, out var used);
|
||||
if (used >= def.TriggerLimitPerTurn.Value)
|
||||
continue;
|
||||
_triggerCountsPerTurn[key] = used + 1;
|
||||
}
|
||||
|
||||
// ── Per-game limit ────────────────────────────────────────
|
||||
if (def.TriggerLimitPerGame is > 0)
|
||||
{
|
||||
var abilityKey = !string.IsNullOrWhiteSpace(def.Name) ? def.Name! : $"idx:{i}";
|
||||
var gameKey = ($"{state.SessionId}:{card.InstanceId}", abilityKey);
|
||||
_triggerCountsPerGame.TryGetValue(gameKey, out var usedGame);
|
||||
if (usedGame >= def.TriggerLimitPerGame.Value)
|
||||
continue;
|
||||
_triggerCountsPerGame[gameKey] = usedGame + 1;
|
||||
}
|
||||
|
||||
// If any action needs a human pick, pause and request client input.
|
||||
if (def.Actions.Any(ActionNeedsClientTargets))
|
||||
{
|
||||
state.PendingTriggeredTarget = new PendingTriggeredTarget
|
||||
{
|
||||
ActorId = ownerId,
|
||||
SourceInstanceId = unit.InstanceId,
|
||||
SourceInstanceId = card.InstanceId,
|
||||
AbilityName = def.Name ?? "Triggered Ability",
|
||||
ActionsJson = JsonSerializer.Serialize(def.Actions, _jsonOpts),
|
||||
RangeJson = def.Range is not null
|
||||
@@ -370,81 +418,240 @@ public static class AbilitySystem
|
||||
|
||||
// ── Cost payment ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void PayCost(CostEntry[] costs, AbilityContext ctx)
|
||||
/// <summary>
|
||||
/// Pays all costs in <paramref name="costs"/> that can be auto-resolved.
|
||||
/// When an interactive pick-mode cost is encountered, stores <see cref="PendingCostPick"/>
|
||||
/// on <paramref name="ctx"/>.State and returns <c>true</c> (caller must stop and return state).
|
||||
/// Returns <c>false</c> when all costs are paid without pausing.
|
||||
/// </summary>
|
||||
private static bool PayCosts(
|
||||
CostEntry[] costs,
|
||||
AbilityContext ctx,
|
||||
int abilityIndex,
|
||||
Models.Action[] pendingActions,
|
||||
AbilityRange? range,
|
||||
DurationModel? forceDuration)
|
||||
{
|
||||
var player = ctx.State.Players[ctx.ActorId];
|
||||
|
||||
foreach (var cost in costs)
|
||||
for (int ci = 0; ci < costs.Length; ci++)
|
||||
{
|
||||
switch (cost.Type)
|
||||
var cost = costs[ci];
|
||||
|
||||
// Interactive costs: pause for player pick.
|
||||
if (cost.PickMode is CostPickMode.SelfPick or CostPickMode.EnemySeePick
|
||||
or CostPickMode.EnemyRandomPick or CostPickMode.EnemyPick)
|
||||
{
|
||||
case CostType.SpiritPoints:
|
||||
if (player.CurrentSp < cost.Amount) throw new GameException("INSUFFICIENT_SP");
|
||||
player.CurrentSp -= cost.Amount;
|
||||
break;
|
||||
|
||||
case CostType.SacrificeTokens:
|
||||
if (player.CurrentSt < cost.Amount) throw new GameException("INSUFFICIENT_ST");
|
||||
player.CurrentSt -= cost.Amount;
|
||||
break;
|
||||
|
||||
case CostType.DiscardFromHand:
|
||||
// Only DiscardFromHand / SendSpiritFromBattlefieldToDiscard / DealDamageToOwnSpirit
|
||||
// support interactive pick. Auto-resolve all others even if PickMode is set.
|
||||
if (cost.Type is CostType.DiscardFromHand
|
||||
or CostType.SendSpiritFromBattlefieldToDiscard
|
||||
or CostType.DealDamageToOwnSpirit)
|
||||
{
|
||||
var candidates = player.Hand
|
||||
.Where(c => cost.Filters is null || FiltersMatch(cost.Filters, c, ctx))
|
||||
.Take(cost.Amount).ToList();
|
||||
if (candidates.Count < cost.Amount)
|
||||
throw new GameException("INSUFFICIENT_CARDS_TO_DISCARD");
|
||||
foreach (var c in candidates) { player.Hand.Remove(c); player.Discard.Add(c); }
|
||||
break;
|
||||
}
|
||||
// Determine who picks.
|
||||
var pickerActorId = cost.PickMode is CostPickMode.SelfPick
|
||||
? ctx.ActorId
|
||||
: ctx.State.GetEnemyIds(ctx.ActorId).FirstOrDefault() ?? ctx.ActorId;
|
||||
|
||||
case CostType.MillTopOfDeck:
|
||||
for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++)
|
||||
// Remaining costs after this one.
|
||||
var remaining = costs.Skip(ci + 1).ToArray();
|
||||
|
||||
ctx.State.PendingCostPick = new PendingCostPick
|
||||
{
|
||||
var top = player.Deck[^1];
|
||||
player.Deck.RemoveAt(player.Deck.Count - 1);
|
||||
player.Discard.Add(top);
|
||||
}
|
||||
break;
|
||||
|
||||
case CostType.MillBottomOfDeck:
|
||||
for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++)
|
||||
{
|
||||
var bottom = player.Deck[0];
|
||||
player.Deck.RemoveAt(0);
|
||||
player.Discard.Add(bottom);
|
||||
}
|
||||
break;
|
||||
|
||||
case CostType.DealDamageToOwnArchSpirit:
|
||||
if (player.ArchSpirit is null) throw new GameException("NO_ARCHSPIRIT");
|
||||
ApplyDamageToUnit(player.ArchSpirit, cost.Amount, bypassDefense: false, ctx);
|
||||
break;
|
||||
|
||||
case CostType.DealDamageToOwnSpirit:
|
||||
{
|
||||
var spirit = player.Field.OfType<FieldCard>()
|
||||
.FirstOrDefault(f => !f.IsLeader
|
||||
&& (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx)));
|
||||
if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST");
|
||||
ApplyDamageToUnit(spirit, cost.Amount, bypassDefense: false, ctx);
|
||||
break;
|
||||
}
|
||||
|
||||
case CostType.SendSpiritFromBattlefieldToDiscard:
|
||||
{
|
||||
var spirit = player.Field.OfType<FieldCard>()
|
||||
.FirstOrDefault(f => !f.IsLeader
|
||||
&& (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx)));
|
||||
if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST");
|
||||
ctx.State.Board?.RemoveUnit(spirit.InstanceId);
|
||||
player.Field.Remove(spirit);
|
||||
player.Discard.Add(spirit);
|
||||
break;
|
||||
ActorId = ctx.ActorId,
|
||||
SourceInstanceId = ctx.Source?.InstanceId ?? string.Empty,
|
||||
AbilityIndex = abilityIndex,
|
||||
PickerActorId = pickerActorId,
|
||||
CostType = cost.Type.ToString(),
|
||||
Amount = cost.Amount,
|
||||
PickMode = cost.PickMode.ToString()!,
|
||||
FiltersJson = cost.Filters is not null
|
||||
? JsonSerializer.Serialize(cost.Filters, _jsonOpts) : null,
|
||||
RemainingCostsJson = JsonSerializer.Serialize(remaining, _jsonOpts),
|
||||
ActionsJson = JsonSerializer.Serialize(pendingActions, _jsonOpts),
|
||||
RangeJson = range is not null
|
||||
? JsonSerializer.Serialize(range, _jsonOpts) : null,
|
||||
ForceDurationJson = forceDuration is not null
|
||||
? JsonSerializer.Serialize(forceDuration, _jsonOpts) : null,
|
||||
};
|
||||
return true; // paused
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-resolve the cost.
|
||||
PaySingleCost(cost, player, ctx);
|
||||
}
|
||||
return false; // all paid
|
||||
}
|
||||
|
||||
private static void PaySingleCost(CostEntry cost, PlayerState player, AbilityContext ctx)
|
||||
{
|
||||
switch (cost.Type)
|
||||
{
|
||||
case CostType.SpiritPoints:
|
||||
if (player.CurrentSp < cost.Amount) throw new GameException("INSUFFICIENT_SP");
|
||||
player.CurrentSp -= cost.Amount;
|
||||
break;
|
||||
|
||||
case CostType.SacrificeTokens:
|
||||
if (player.CurrentSt < cost.Amount) throw new GameException("INSUFFICIENT_ST");
|
||||
player.CurrentSt -= cost.Amount;
|
||||
break;
|
||||
|
||||
case CostType.DiscardFromHand:
|
||||
{
|
||||
var pool = player.Hand
|
||||
.Where(c => cost.Filters is null || FiltersMatch(cost.Filters, c, ctx))
|
||||
.ToList();
|
||||
if (cost.PickMode == CostPickMode.Random)
|
||||
pool = pool.OrderBy(_ => Random.Shared.Next()).ToList();
|
||||
var candidates = pool.Take(cost.Amount).ToList();
|
||||
if (candidates.Count < cost.Amount)
|
||||
throw new GameException("INSUFFICIENT_CARDS_TO_DISCARD");
|
||||
foreach (var c in candidates) { player.Hand.Remove(c); player.Discard.Add(c); }
|
||||
break;
|
||||
}
|
||||
|
||||
case CostType.MillTopOfDeck:
|
||||
for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++)
|
||||
{
|
||||
var top = player.Deck[^1];
|
||||
player.Deck.RemoveAt(player.Deck.Count - 1);
|
||||
player.Discard.Add(top);
|
||||
}
|
||||
break;
|
||||
|
||||
case CostType.MillBottomOfDeck:
|
||||
for (int i = 0; i < cost.Amount && player.Deck.Count > 0; i++)
|
||||
{
|
||||
var bottom = player.Deck[0];
|
||||
player.Deck.RemoveAt(0);
|
||||
player.Discard.Add(bottom);
|
||||
}
|
||||
break;
|
||||
|
||||
case CostType.DealDamageToOwnArchSpirit:
|
||||
if (player.ArchSpirit is null) throw new GameException("NO_ARCHSPIRIT");
|
||||
ApplyDamageToUnit(player.ArchSpirit, cost.Amount, bypassDefense: false, ctx);
|
||||
break;
|
||||
|
||||
case CostType.DealDamageToOwnSpirit:
|
||||
{
|
||||
var spirit = player.Field.OfType<FieldCard>()
|
||||
.FirstOrDefault(f => !f.IsLeader
|
||||
&& (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx)));
|
||||
if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST");
|
||||
ApplyDamageToUnit(spirit, cost.Amount, bypassDefense: false, ctx);
|
||||
break;
|
||||
}
|
||||
|
||||
case CostType.SendSpiritFromBattlefieldToDiscard:
|
||||
{
|
||||
var spirit = player.Field.OfType<FieldCard>()
|
||||
.FirstOrDefault(f => !f.IsLeader
|
||||
&& (cost.Filters is null || FiltersMatch(cost.Filters, f, ctx)));
|
||||
if (spirit is null) throw new GameException("NO_VALID_SPIRIT_FOR_COST");
|
||||
ctx.State.Board?.RemoveUnit(spirit.InstanceId);
|
||||
player.Field.Remove(spirit);
|
||||
player.Discard.Add(spirit);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resumes an Active ability after the picker has submitted their cost-pick selections.
|
||||
/// Called by <c>GameCostPickHandler</c>.
|
||||
/// </summary>
|
||||
public static GameState ResumeCostPick(
|
||||
GameState state,
|
||||
string actorId,
|
||||
string requestId,
|
||||
IReadOnlyList<string> selectedInstanceIds)
|
||||
{
|
||||
var pending = state.PendingCostPick
|
||||
?? throw new GameException("NO_PENDING_COST_PICK");
|
||||
|
||||
if (pending.RequestId != requestId)
|
||||
throw new GameException("REQUEST_ID_MISMATCH");
|
||||
|
||||
// Allow both the actor and the designated picker to respond.
|
||||
if (actorId != pending.ActorId && actorId != pending.PickerActorId)
|
||||
throw new GameException("NOT_YOUR_COST_PICK");
|
||||
|
||||
state.PendingCostPick = null;
|
||||
|
||||
var player = state.Players[pending.ActorId];
|
||||
|
||||
// Validate and pay the interactive cost using the client-selected IDs.
|
||||
switch (pending.CostType)
|
||||
{
|
||||
case nameof(CostType.DiscardFromHand):
|
||||
{
|
||||
var toDiscard = selectedInstanceIds
|
||||
.Select(id => player.Hand.FirstOrDefault(c => c.InstanceId == id))
|
||||
.OfType<CardInstance>()
|
||||
.Take(pending.Amount)
|
||||
.ToList();
|
||||
if (toDiscard.Count < pending.Amount)
|
||||
throw new GameException("INVALID_COST_PICK_SELECTION");
|
||||
foreach (var c in toDiscard) { player.Hand.Remove(c); player.Discard.Add(c); }
|
||||
break;
|
||||
}
|
||||
case nameof(CostType.SendSpiritFromBattlefieldToDiscard):
|
||||
{
|
||||
var picked = selectedInstanceIds.FirstOrDefault()
|
||||
?? throw new GameException("INVALID_COST_PICK_SELECTION");
|
||||
var spirit = player.Field.OfType<FieldCard>()
|
||||
.FirstOrDefault(f => f.InstanceId == picked)
|
||||
?? throw new GameException("INVALID_COST_PICK_SELECTION");
|
||||
state.Board?.RemoveUnit(spirit.InstanceId);
|
||||
player.Field.Remove(spirit);
|
||||
player.Discard.Add(spirit);
|
||||
break;
|
||||
}
|
||||
case nameof(CostType.DealDamageToOwnSpirit):
|
||||
{
|
||||
var picked = selectedInstanceIds.FirstOrDefault()
|
||||
?? throw new GameException("INVALID_COST_PICK_SELECTION");
|
||||
var spirit = player.Field.OfType<FieldCard>()
|
||||
.FirstOrDefault(f => f.InstanceId == picked)
|
||||
?? throw new GameException("INVALID_COST_PICK_SELECTION");
|
||||
// Temporary context for damage application.
|
||||
var dmgCtx = new AbilityContext { State = state, ActorId = pending.ActorId };
|
||||
ApplyDamageToUnit(spirit, pending.Amount, bypassDefense: false, dmgCtx);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Find the source unit (may have left the field while waiting — skip if gone).
|
||||
var source = state.Players.Values
|
||||
.SelectMany(p => p.Field).OfType<FieldCard>()
|
||||
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
|
||||
if (source is null) return state;
|
||||
|
||||
var ctx = new AbilityContext { State = state, ActorId = pending.ActorId, Source = source };
|
||||
|
||||
// Pay any remaining non-interactive costs.
|
||||
var remainingCosts = JsonSerializer.Deserialize<CostEntry[]>(
|
||||
pending.RemainingCostsJson, _jsonOpts) ?? [];
|
||||
foreach (var c in remainingCosts)
|
||||
PaySingleCost(c, player, ctx);
|
||||
|
||||
// Execute the ability actions.
|
||||
var actions = JsonSerializer.Deserialize<Models.Action[]>(
|
||||
pending.ActionsJson, _jsonOpts) ?? [];
|
||||
DurationModel? forceDuration = pending.ForceDurationJson is not null
|
||||
? JsonSerializer.Deserialize<DurationModel>(pending.ForceDurationJson, _jsonOpts)
|
||||
: null;
|
||||
AbilityRange? range = pending.RangeJson is not null
|
||||
? JsonSerializer.Deserialize<AbilityRange>(pending.RangeJson, _jsonOpts)
|
||||
: null;
|
||||
|
||||
ExecuteActions(actions, ctx, clientTargets: null, requireClientTargets: false,
|
||||
activationRange: range, forceDuration: forceDuration);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
// ── Action execution ──────────────────────────────────────────────────────
|
||||
@@ -842,50 +1049,83 @@ public static class AbilitySystem
|
||||
// ── §5.1 Stat modification ─────────────────────────────────────────
|
||||
case ModifyHealthEffect mh when target is CardInstance ci:
|
||||
{
|
||||
int amt = ResolveValue(mh.Amount, ctx);
|
||||
int raw = ResolveValue(mh.Amount, ctx);
|
||||
if (mh.StatTarget == StatTarget.Current)
|
||||
{
|
||||
ci.CurrentHealth = (ci.CurrentHealth ?? 0) + amt;
|
||||
if (ci.MaxHealth.HasValue)
|
||||
ci.CurrentHealth = Math.Min(ci.CurrentHealth.Value, ci.MaxHealth.Value);
|
||||
int cur = ci.CurrentHealth ?? 0;
|
||||
int newVal = ApplyStatOperator(cur, raw, mh.Operator);
|
||||
if (ci.MaxHealth.HasValue) newVal = Math.Min(newVal, ci.MaxHealth.Value);
|
||||
int delta = newVal - cur;
|
||||
ci.CurrentHealth = newVal;
|
||||
if (ci.CurrentHealth <= 0) KillUnit(ci, ctx, ctx.Source?.InstanceId);
|
||||
TrackEffect(new ModifyHealthEffect { Amount = V(-delta), StatTarget = mh.StatTarget },
|
||||
ci.InstanceId, duration, ctx);
|
||||
}
|
||||
else
|
||||
{
|
||||
ci.MaxHealth = (ci.MaxHealth ?? 0) + amt;
|
||||
int cur = ci.MaxHealth ?? 0;
|
||||
int newVal = Math.Max(0, ApplyStatOperator(cur, raw, mh.Operator));
|
||||
int delta = newVal - cur;
|
||||
ci.MaxHealth = newVal;
|
||||
if (ci.CurrentHealth > ci.MaxHealth) ci.CurrentHealth = ci.MaxHealth;
|
||||
TrackEffect(new ModifyHealthEffect { Amount = V(-delta), StatTarget = mh.StatTarget },
|
||||
ci.InstanceId, duration, ctx);
|
||||
}
|
||||
TrackEffect(new ModifyHealthEffect { Amount = V(-amt), StatTarget = mh.StatTarget },
|
||||
ci.InstanceId, duration, ctx);
|
||||
break;
|
||||
}
|
||||
case ModifyDefenseEffect md when target is CardInstance ci:
|
||||
{
|
||||
int amt = ResolveValue(md.Amount, ctx);
|
||||
int raw = ResolveValue(md.Amount, ctx);
|
||||
if (md.StatTarget == StatTarget.Current)
|
||||
ci.CurrentDefense = Math.Max(0, (ci.CurrentDefense ?? 0) + amt);
|
||||
{
|
||||
int cur = ci.CurrentDefense ?? 0;
|
||||
int newVal = Math.Max(0, ApplyStatOperator(cur, raw, md.Operator));
|
||||
int delta = newVal - cur;
|
||||
ci.CurrentDefense = newVal;
|
||||
TrackEffect(new ModifyDefenseEffect { Amount = V(-delta), StatTarget = md.StatTarget },
|
||||
ci.InstanceId, duration, ctx);
|
||||
}
|
||||
else
|
||||
ci.MaxDefense = (ci.MaxDefense ?? 0) + amt;
|
||||
TrackEffect(new ModifyDefenseEffect { Amount = V(-amt), StatTarget = md.StatTarget },
|
||||
ci.InstanceId, duration, ctx);
|
||||
{
|
||||
int cur = ci.MaxDefense ?? 0;
|
||||
int newVal = Math.Max(0, ApplyStatOperator(cur, raw, md.Operator));
|
||||
int delta = newVal - cur;
|
||||
ci.MaxDefense = newVal;
|
||||
TrackEffect(new ModifyDefenseEffect { Amount = V(-delta), StatTarget = md.StatTarget },
|
||||
ci.InstanceId, duration, ctx);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ModifyDamageEffect mdam when target is CardInstance ci:
|
||||
{
|
||||
int amt = ResolveValue(mdam.Amount, ctx);
|
||||
ci.Damage = Math.Max(0, (ci.Damage ?? 0) + amt);
|
||||
TrackEffect(new ModifyDamageEffect { Amount = V(-amt) }, ci.InstanceId, duration, ctx);
|
||||
int cur = ci.Damage ?? 0;
|
||||
int newVal = Math.Max(0, ApplyStatOperator(cur, ResolveValue(mdam.Amount, ctx), mdam.Operator));
|
||||
int delta = newVal - cur;
|
||||
ci.Damage = newVal;
|
||||
TrackEffect(new ModifyDamageEffect { Amount = V(-delta) }, ci.InstanceId, duration, ctx);
|
||||
break;
|
||||
}
|
||||
case ModifyMPEffect mmp when target is CardInstance ci:
|
||||
{
|
||||
int amt = ResolveValue(mmp.Amount, ctx);
|
||||
int raw = ResolveValue(mmp.Amount, ctx);
|
||||
if (mmp.StatTarget == StatTarget.Current && ci is FieldCard fc)
|
||||
fc.CurrentMp = Math.Max(0, fc.CurrentMp + amt);
|
||||
{
|
||||
int cur = fc.CurrentMp;
|
||||
int newVal = Math.Max(0, ApplyStatOperator(cur, raw, mmp.Operator));
|
||||
int delta = newVal - cur;
|
||||
fc.CurrentMp = newVal;
|
||||
TrackEffect(new ModifyMPEffect { Amount = V(-delta), StatTarget = mmp.StatTarget },
|
||||
ci.InstanceId, duration, ctx);
|
||||
}
|
||||
else
|
||||
ci.MaxMp = Math.Max(0, (ci.MaxMp ?? 0) + amt);
|
||||
TrackEffect(new ModifyMPEffect { Amount = V(-amt), StatTarget = mmp.StatTarget },
|
||||
ci.InstanceId, duration, ctx);
|
||||
{
|
||||
int cur = ci.MaxMp ?? 0;
|
||||
int newVal = Math.Max(0, ApplyStatOperator(cur, raw, mmp.Operator));
|
||||
int delta = newVal - cur;
|
||||
ci.MaxMp = newVal;
|
||||
TrackEffect(new ModifyMPEffect { Amount = V(-delta), StatTarget = mmp.StatTarget },
|
||||
ci.InstanceId, duration, ctx);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SetMovementTypeEffect smt when target is CardInstance ci:
|
||||
@@ -908,19 +1148,21 @@ public static class AbilitySystem
|
||||
}
|
||||
case ModifyMinAttackRangeEffect mmar when target is CardInstance ci:
|
||||
{
|
||||
int orig = ci.MinAttackRange ?? 0;
|
||||
int newVal = Math.Max(0, orig + ResolveValue(mmar.Amount, ctx));
|
||||
int cur = ci.MinAttackRange ?? 0;
|
||||
int newVal = Math.Max(0, ApplyStatOperator(cur, ResolveValue(mmar.Amount, ctx), mmar.Operator));
|
||||
int delta = newVal - cur;
|
||||
ci.MinAttackRange = newVal;
|
||||
TrackEffect(new ModifyMinAttackRangeEffect { Amount = V(orig - newVal) },
|
||||
TrackEffect(new ModifyMinAttackRangeEffect { Amount = V(-delta) },
|
||||
ci.InstanceId, duration, ctx);
|
||||
break;
|
||||
}
|
||||
case ModifyMaxAttackRangeEffect mmax when target is CardInstance ci:
|
||||
{
|
||||
int orig = ci.MaxAttackRange ?? 1;
|
||||
int newVal = Math.Max(0, orig + ResolveValue(mmax.Amount, ctx));
|
||||
int cur = ci.MaxAttackRange ?? 1;
|
||||
int newVal = Math.Max(0, ApplyStatOperator(cur, ResolveValue(mmax.Amount, ctx), mmax.Operator));
|
||||
int delta = newVal - cur;
|
||||
ci.MaxAttackRange = newVal;
|
||||
TrackEffect(new ModifyMaxAttackRangeEffect { Amount = V(orig - newVal) },
|
||||
TrackEffect(new ModifyMaxAttackRangeEffect { Amount = V(-delta) },
|
||||
ci.InstanceId, duration, ctx);
|
||||
break;
|
||||
}
|
||||
@@ -2350,6 +2592,20 @@ public static class AbilitySystem
|
||||
|
||||
// ── Value / affinity resolution ───────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Applies a <see cref="StatModOperator"/> to a current stat value.
|
||||
/// Returns the new value (pre-clamping). The caller stores delta = newVal - oldVal
|
||||
/// so the reversal can be expressed as a simple Add(-delta).
|
||||
/// </summary>
|
||||
private static int ApplyStatOperator(int current, int amount, StatModOperator op) => op switch
|
||||
{
|
||||
StatModOperator.Subtract => current - amount,
|
||||
StatModOperator.Multiply => current * amount,
|
||||
StatModOperator.Divide => amount == 0 ? current : current / amount,
|
||||
StatModOperator.Percent => current + current * amount / 100,
|
||||
_ => current + amount, // Add (default)
|
||||
};
|
||||
|
||||
private static int ResolveValue(ValueExpr expr, AbilityContext ctx)
|
||||
{
|
||||
if (expr.Fixed.HasValue) return expr.Fixed.Value;
|
||||
|
||||
@@ -53,10 +53,24 @@ public sealed class AbilityDefinition
|
||||
|
||||
/// <summary>
|
||||
/// Maximum number of times this Triggered ability may resolve per turn.
|
||||
/// Null or <= 0 means unlimited.
|
||||
/// Null or <= 0 means unlimited.
|
||||
/// </summary>
|
||||
public int? TriggerLimitPerTurn { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maximum number of times this Triggered ability may resolve for the entire game.
|
||||
/// Null or <= 0 means unlimited.
|
||||
/// </summary>
|
||||
public int? TriggerLimitPerGame { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Restricts which zones the source card must be in for the trigger to be active.
|
||||
/// Valid values: "Battlefield", "Hand", "Discard", "Deck".
|
||||
/// Null or empty means the trigger fires regardless of the source card's zone.
|
||||
/// Default behaviour (null) retains the existing battlefield-only scan.
|
||||
/// </summary>
|
||||
public string[]? SourceZoneGate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional display name shown in the admin tool and client ability list.
|
||||
/// Not required for game logic.
|
||||
|
||||
@@ -113,16 +113,40 @@ public enum CostType
|
||||
DealDamageToOwnSpirit,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How the player(s) resolve the selection for an interactive cost (e.g. DiscardFromHand).
|
||||
/// Null / absent: server auto-resolves (picks first N valid candidates).
|
||||
/// </summary>
|
||||
public enum CostPickMode
|
||||
{
|
||||
/// <summary>Server picks randomly from valid candidates.</summary>
|
||||
Random,
|
||||
/// <summary>Controlling player sees and picks which cards to pay.</summary>
|
||||
SelfPick,
|
||||
/// <summary>Opponent picks on behalf of the controlling player (sees all options).</summary>
|
||||
EnemySeePick,
|
||||
/// <summary>Opponent picks randomly from the controlling player's valid candidates.</summary>
|
||||
EnemyRandomPick,
|
||||
/// <summary>Opponent has free choice of which cards the controlling player pays.</summary>
|
||||
EnemyPick,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A single cost element for an Active ability.
|
||||
/// Multiple CostEntry items must all be paid simultaneously before the ability resolves.
|
||||
/// </summary>
|
||||
public sealed class CostEntry
|
||||
{
|
||||
public CostType Type { get; set; }
|
||||
public int Amount { get; set; } = 1;
|
||||
public CostType Type { get; set; }
|
||||
public int Amount { get; set; } = 1;
|
||||
/// <summary>Optional filter for targeted costs (e.g. "Discard a Spirit card from hand").</summary>
|
||||
public Filter[]? Filters { get; set; }
|
||||
public Filter[]? Filters { get; set; }
|
||||
/// <summary>
|
||||
/// When set, the cost resolution is interactive: a player (controlling or opponent)
|
||||
/// is prompted to pick which specific cards/units satisfy the cost.
|
||||
/// Null = auto-resolve (engine picks first N matching candidates).
|
||||
/// </summary>
|
||||
public CostPickMode? PickMode { get; set; }
|
||||
}
|
||||
|
||||
// ── Ability range ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -104,15 +104,24 @@ public abstract class Effect { }
|
||||
|
||||
public enum StatTarget { Current, Max }
|
||||
|
||||
public sealed class ModifyHealthEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; }
|
||||
public sealed class ModifyDefenseEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; }
|
||||
public sealed class ModifyDamageEffect : Effect { public ValueExpr Amount { get; set; } = new(); }
|
||||
public sealed class ModifyMPEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; }
|
||||
/// <summary>
|
||||
/// How to apply the Amount to the current stat value.
|
||||
/// "Add" (default) and "Subtract" use the Amount directly (positive integer recommended;
|
||||
/// Subtract flips the sign before applying). "Multiply" and "Divide" treat Amount as
|
||||
/// the multiplier/divisor integer (e.g. Multiply 2 = ×2). "Percent" treats Amount as
|
||||
/// a percentage (e.g. Percent 50 adds 50% of the base value).
|
||||
/// </summary>
|
||||
public enum StatModOperator { Add, Subtract, Multiply, Divide, Percent }
|
||||
|
||||
public sealed class ModifyHealthEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; public StatModOperator Operator { get; set; } = StatModOperator.Add; }
|
||||
public sealed class ModifyDefenseEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; public StatModOperator Operator { get; set; } = StatModOperator.Add; }
|
||||
public sealed class ModifyDamageEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatModOperator Operator { get; set; } = StatModOperator.Add; }
|
||||
public sealed class ModifyMPEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatTarget StatTarget { get; set; } = StatTarget.Current; public StatModOperator Operator { get; set; } = StatModOperator.Add; }
|
||||
|
||||
public sealed class SetMovementTypeEffect : Effect { public MovementType MovementType { get; set; } }
|
||||
public sealed class SetAttackRangeEffect : Effect { public int Min { get; set; } public int Max { get; set; } }
|
||||
public sealed class ModifyMinAttackRangeEffect : Effect { public ValueExpr Amount { get; set; } = new(); }
|
||||
public sealed class ModifyMaxAttackRangeEffect : Effect { public ValueExpr Amount { get; set; } = new(); }
|
||||
public sealed class ModifyMinAttackRangeEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatModOperator Operator { get; set; } = StatModOperator.Add; }
|
||||
public sealed class ModifyMaxAttackRangeEffect : Effect { public ValueExpr Amount { get; set; } = new(); public StatModOperator Operator { get; set; } = StatModOperator.Add; }
|
||||
public sealed class ModifyCostEffect : Effect { public int? Sp { get; set; } public int? St { get; set; } }
|
||||
public sealed class SetAffinityEffect : Effect { public AffinityExpr Affinity { get; set; } = new(); }
|
||||
public sealed class GrantAdditionalAttackEffect : Effect { public int N { get; set; } = 1; }
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
namespace SOR.Game.Abilities.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Stored in GameState when an Active ability's cost requires interactive player selection
|
||||
/// (e.g. "Discard a card of your choice from hand").
|
||||
///
|
||||
/// The engine pauses cost payment, pushes a CostPickRequestPush to the picker player,
|
||||
/// then resumes via GameCostPickHandler once the player submits their selection.
|
||||
/// </summary>
|
||||
public sealed class PendingCostPick
|
||||
{
|
||||
/// <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 activated the ability.</summary>
|
||||
public string ActorId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>InstanceId of the unit whose ability cost is being resolved.</summary>
|
||||
public string SourceInstanceId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>0-based index of the ability in the source unit's AbilitiesJson array.</summary>
|
||||
public int AbilityIndex { get; set; }
|
||||
|
||||
/// <summary>AccountId of the player who must pick (may differ from ActorId for EnemyPick modes).</summary>
|
||||
public string PickerActorId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The cost type being interactively resolved.</summary>
|
||||
public string CostType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Number of cards/units the picker must select.</summary>
|
||||
public int Amount { get; set; } = 1;
|
||||
|
||||
/// <summary>The pick mode driving who selects and how.</summary>
|
||||
public string PickMode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>JSON-serialized Filter[]? — constraints on what the picker may select.</summary>
|
||||
public string? FiltersJson { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// JSON-serialized CostEntry[] of costs that still need paying after this pick resolves.
|
||||
/// Empty when this is the last interactive cost.
|
||||
/// </summary>
|
||||
public string RemainingCostsJson { get; set; } = "[]";
|
||||
|
||||
/// <summary>JSON-serialized Action[] — the full action list to execute after all costs are paid.</summary>
|
||||
public string ActionsJson { get; set; } = "[]";
|
||||
|
||||
/// <summary>JSON-serialized AbilityRange? — passed through to ExecuteActions on resume.</summary>
|
||||
public string? RangeJson { get; set; }
|
||||
|
||||
/// <summary>JSON-serialized DurationModel? — forceDuration passed to ExecuteActions on resume.</summary>
|
||||
public string? ForceDurationJson { get; set; }
|
||||
}
|
||||
@@ -831,3 +831,34 @@ public sealed record GameTriggeredTargetRequest(
|
||||
string RequestId,
|
||||
IReadOnlyList<AbilityTarget> Targets);
|
||||
|
||||
/// <summary>
|
||||
/// Pushed to the picker player when an Active ability cost requires interactive card/unit
|
||||
/// selection (e.g. "Discard a Spirit card of your choice").
|
||||
/// The client shows a zone picker and replies with <see cref="GameCostPickRequest"/>.
|
||||
/// </summary>
|
||||
public sealed record CostPickRequestPush(
|
||||
/// <summary>Correlation ID — must be echoed back in the response.</summary>
|
||||
string RequestId,
|
||||
/// <summary>InstanceId of the unit whose ability cost is being resolved.</summary>
|
||||
string SourceInstanceId,
|
||||
/// <summary>The cost type being resolved (e.g. "DiscardFromHand").</summary>
|
||||
string CostType,
|
||||
/// <summary>How many cards/units the picker must select.</summary>
|
||||
int Amount,
|
||||
/// <summary>Who is picking: "SelfPick", "EnemySeePick", "EnemyRandomPick", "EnemyPick".</summary>
|
||||
string PickMode,
|
||||
/// <summary>JSON-serialized Filter[]? constraining valid selections. Null = no constraint.</summary>
|
||||
string? FiltersJson);
|
||||
|
||||
/// <summary>
|
||||
/// Sent by the picker to submit their card/unit selections for a pending cost.
|
||||
/// </summary>
|
||||
public sealed record GameCostPickRequest(
|
||||
Guid SessionId,
|
||||
string RequestId,
|
||||
/// <summary>InstanceIds of the selected cards or units.</summary>
|
||||
IReadOnlyList<string> SelectedInstanceIds);
|
||||
|
||||
/// <summary>Acknowledged response for a cost pick submission.</summary>
|
||||
public sealed record GameCostPickResponse(bool Success);
|
||||
|
||||
|
||||
@@ -100,6 +100,13 @@ public sealed class GameState
|
||||
/// submits a <c>game.triggered_target</c> response.
|
||||
/// </summary>
|
||||
public Abilities.Models.PendingTriggeredTarget? PendingTriggeredTarget { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Non-null when an Active ability's cost requires interactive card/unit selection
|
||||
/// (CostPickMode.SelfPick / EnemyPick etc.). The game is effectively "paused" until
|
||||
/// the picker submits a <c>game.cost_pick</c> response.
|
||||
/// </summary>
|
||||
public Abilities.Models.PendingCostPick? PendingCostPick { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PlayerState
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Game.Abilities;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// game.cost_pick — player (or opponent) submits their card/unit selections for a
|
||||
/// paused Active ability cost (CostPickMode.SelfPick / EnemyPick etc.).
|
||||
///
|
||||
/// This handler resumes and completes cost payment, then executes the ability actions
|
||||
/// and broadcasts the updated game state to all players in the session.
|
||||
/// </summary>
|
||||
internal sealed class GameCostPickHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly IClientPush _clientPush;
|
||||
|
||||
public GameCostPickHandler(
|
||||
IMessageSerializer serializer,
|
||||
GameDbContext gameDb,
|
||||
IClientPush clientPush)
|
||||
{
|
||||
_serializer = serializer;
|
||||
_gameDb = gameDb;
|
||||
_clientPush = clientPush;
|
||||
}
|
||||
|
||||
public string MessageType => "game.cost_pick";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameCostPickRequest>(message.Payload);
|
||||
var actorId = connection.UserId;
|
||||
|
||||
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
|
||||
var prevStateJson = session.StateJson!;
|
||||
var state = GameEngine.Deserialize(prevStateJson);
|
||||
|
||||
var newState = AbilitySystem.ResumeCostPick(
|
||||
state, actorId, req.RequestId, req.SelectedInstanceIds);
|
||||
|
||||
await SaveStateAsync(_gameDb, session, newState, actorId, "game.cost_pick",
|
||||
JsonSerializer.Serialize(req), ct);
|
||||
|
||||
await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson);
|
||||
|
||||
return ServerMessage.Reply("game.cost_pick.ack", message.Seq,
|
||||
new GameCostPickResponse(true));
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,9 @@ public static class ServiceRegistration
|
||||
// Triggered ability target response (player submits picks for a paused trigger)
|
||||
services.AddTransient<IMessageHandler, GameTriggeredTargetHandler>();
|
||||
|
||||
// Interactive cost pick response (player submits card/unit selections for an interactive cost)
|
||||
services.AddTransient<IMessageHandler, GameCostPickHandler>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user