Server engine (SOR.Game): - Zone-scope card targets (Hand/Deck/Discard/AnyZone) pause with a server- enumerated candidates list (PendingTargetPick.CandidatesJson) instead of failing when the client submits player accountIds for hidden zones - Missing mandatory target picks now prompt (PendingTargetPick) rather than throwing INSUFFICIENT_TARGETS; all post-pick resume flows run with requireClientTargets so actions never silently auto-hit the first candidate - ChannelCardFromZone: Filters + InOwn/InTargetChannelRange enforced via shared IsWithinChannelConstraints (incl. player-picked tile validation) - TakeControl duration reversal via internal __ReturnControl effect; board occupant-owner kept in sync both ways - TrackedDuration gains SourceOwnerAccountId (UntilStartOfSourceOwnerTurn now anchors correctly) and IsAura (aura reapply no longer strips unrelated buffs) - RevealCards honours N for player targets; IsAllyTurn means teammate's turn; content-keyed ParseAbilities cache; AbilityValidator for save-time linting; duplicate PolyType attributes removed (converter reads base registry only) Admin builder (AbilityBuilder/CardEditor): - Full multi-filter editor (28 filter types with parameter fields) replacing the single param-less dropdown; raw-JSON ChooseOne editor per action - Cost PickMode, TriggerLimitPerGame, SourceZoneGate inputs - Save-time ability validation with error list (blocks invalid saves) Client (Godot): - Card-list picker for zone-scope target picks; OR/XOR-root abilities skip speculative upfront targeting; ally units included in team-aware highlight pools (Game.get_ally_units); state re-sync on rejected pick responses Tests: new SOR.Game.Tests project (21 passing) covering the regression suite from SOR.Abilities-Review-and-solutions.md §8 plus validator rules. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
891 lines
34 KiB
GDScript
891 lines
34 KiB
GDScript
extends Node
|
|
## Game autoload — manages all ranked-game state and server communication.
|
|
##
|
|
## Receives matchmaking and game server pushes, stores game state,
|
|
## and provides helpers for the GameScreen and MatchmakingScreen.
|
|
##
|
|
## Usage:
|
|
## Game.session_id ← current session GUID string
|
|
## Game.state ← latest GameStateDto dict
|
|
## Game.get_my_player() ← own PlayerStateDto dict
|
|
## Game.is_my_turn() ← bool
|
|
|
|
# ── Signals ───────────────────────────────────────────────────────────────────
|
|
|
|
## Emitted when matchmaking finds a game. Navigate to GameScreen.
|
|
signal match_found(session_id: String, opponent_name: String, opponent_rank: int)
|
|
|
|
## Emitted whenever the authoritative game state changes.
|
|
signal state_updated(state: Dictionary)
|
|
|
|
## Emitted when the game ends.
|
|
signal game_over(winner_account_id: String, win_condition: String,
|
|
winner_rank_delta: int, loser_rank_delta: int,
|
|
player_outcomes: Array)
|
|
|
|
## Emitted when the server abandons an Initializing session (e.g. server restart).
|
|
signal session_abandoned(reason: String)
|
|
|
|
## Emitted when the active player has been inactive for 5 minutes.
|
|
## The local player (waiting for opponent) can call send_force_concede() to claim a win.
|
|
signal opponent_inactive(session_id: String)
|
|
|
|
## Emitted when the local player has been flagged as inactive.
|
|
## Show a warning — the opponent may accept a forfeit.
|
|
signal inactive_warning(session_id: String)
|
|
|
|
## Emitted when both players have been idle for 10 minutes (mutual idle).
|
|
## Both players must wait — no concede or force-concede is allowed.
|
|
signal both_idle_warning(session_id: String)
|
|
|
|
## Emitted when a player is knocked out mid-game (game continues for others).
|
|
signal player_eliminated(session_id: String, eliminated_account_id: String, seat_index: int, team_index: int)
|
|
|
|
## Emitted when a game session starts or ends (from game.activity pushes).
|
|
## Used by game_screen.gd to drive the live-star skybox.
|
|
## 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)
|
|
|
|
## Emitted when an interactive cost requires the player to select cards/units.
|
|
## Payload keys: requestId, sourceInstanceId, costType, amount, pickMode, filtersJson
|
|
signal cost_pick_request(request_data: Dictionary)
|
|
|
|
## Emitted when a CostGroup OR/XOR requires the chooser to pick an option.
|
|
## Payload keys: requestId, sourceInstanceId, costGroupJson
|
|
signal cost_group_pick_request(request_data: Dictionary)
|
|
|
|
## Emitted when an ActionGroup OR/XOR requires the chooser to pick a branch.
|
|
## Payload keys: requestId, sourceInstanceId, actionGroupJson
|
|
signal action_group_pick_request(request_data: Dictionary)
|
|
|
|
## Emitted when a ChooseOne (Opponent/Ally chooser) requires a branch selection.
|
|
## Payload keys: requestId, sourceInstanceId, branchCount, branchesJson
|
|
signal branch_pick_request(request_data: Dictionary)
|
|
|
|
## Emitted when an action needs the Opponent/Ally to pick targets.
|
|
## Payload keys: requestId, sourceInstanceId, actionJson, rangeJson
|
|
signal target_pick_request(request_data: Dictionary)
|
|
|
|
## Emitted when an effect requires a tile selection.
|
|
## Payload keys: requestId, sourceInstanceId, effectType, requireEmpty, requireOccupied,
|
|
## occupantOwnership, maxRange, targetInstanceId
|
|
signal tile_pick_request(request_data: Dictionary)
|
|
|
|
## Emitted when an effect requires a player selection.
|
|
## Payload keys: requestId, sourceInstanceId, effectType, ownership, validPlayerIds, targetInstanceId
|
|
signal player_pick_request(request_data: Dictionary)
|
|
|
|
## Emitted when cards are revealed and must be ordered by the chooser.
|
|
## Payload keys: requestId, sourceInstanceId, effectType, revealedCardsJson, count
|
|
signal reveal_choice_pick_request(request_data: Dictionary)
|
|
|
|
## Emitted when a Repentance card resolves with no custom animation asset.
|
|
## Server only emits this when no active ability on the card has a usable AssetUrl.
|
|
## Payload keys: eventId, sessionId, actorAccountId, sourceArchSpiritInstanceId,
|
|
## cardInstanceId, cardDefinitionId, cardName, affinity, targets
|
|
signal repentance_placeholder_visual(payload: Dictionary)
|
|
|
|
## Emitted when an Active ability fires with no custom animation asset.
|
|
## Payload keys: eventId, sessionId, actorAccountId, sourceInstanceId,
|
|
## abilityName, sourceAffinity, targets, targetMode
|
|
signal ability_placeholder_visual(payload: Dictionary)
|
|
|
|
# ── State ─────────────────────────────────────────────────────────────────────
|
|
|
|
var session_id : String = ""
|
|
var state : Dictionary = {}
|
|
var opponent_name : String = ""
|
|
var is_spectating : bool = false
|
|
var debug_output : bool = false
|
|
var _state_version : int = -1
|
|
var _syncing : bool = false # true while a game.get_state request is in-flight
|
|
|
|
# ── Lifecycle ─────────────────────────────────────────────────────────────────
|
|
|
|
func _ready() -> void:
|
|
Network.message_received.connect(_on_server_push)
|
|
Auth.session_expired.connect(_clear_state)
|
|
Auth.auth_success.connect(_on_auth_reconnect)
|
|
|
|
|
|
func _clear_state() -> void:
|
|
session_id = ""
|
|
state = {}
|
|
opponent_name = ""
|
|
is_spectating = false
|
|
_state_version = -1
|
|
_syncing = false
|
|
|
|
|
|
## Called on every auth_success (initial login AND reconnects).
|
|
## If we have both an active session_id AND live game state, resend game.ready
|
|
## so the server re-registers this connection and we get state updates again.
|
|
## The state check prevents sending stale session IDs from games that already ended.
|
|
func _on_auth_reconnect(_uid: String, _dn: String) -> void:
|
|
if session_id.is_empty():
|
|
return
|
|
if is_spectating:
|
|
_request_spectator_state()
|
|
elif not state.is_empty():
|
|
send_ready()
|
|
|
|
|
|
## Start spectating a game session. State is applied from the server ack.
|
|
func start_spectating(sid: String) -> void:
|
|
is_spectating = true
|
|
state = {}
|
|
session_id = sid
|
|
_request_spectator_state()
|
|
|
|
|
|
func _request_spectator_state() -> void:
|
|
if session_id.is_empty():
|
|
return
|
|
Network.request("game.spectate",
|
|
{ "sessionId": session_id },
|
|
func(_t: String, p: Variant) -> void:
|
|
if debug_output:
|
|
print("[Game] <<< game.spectate.ack")
|
|
_apply_state_from_payload(p),
|
|
func(code: String, msg: String) -> void:
|
|
if debug_output:
|
|
print("[Game] ERR spectate ", code, " ", msg)
|
|
is_spectating = false)
|
|
|
|
|
|
## Stop spectating the current session.
|
|
func stop_spectating() -> void:
|
|
if not is_spectating: return
|
|
Network.send("game.spectate.stop", { "sessionId": session_id })
|
|
is_spectating = false
|
|
_clear_state()
|
|
|
|
# ── Public helpers ────────────────────────────────────────────────────────────
|
|
|
|
## Returns the PlayerStateDto dict for the local player, or {}.
|
|
func get_my_player() -> Dictionary:
|
|
return _player_by_id(Auth.user_id)
|
|
|
|
|
|
## Returns all opponent PlayerStateDto dicts (non-local, non-eliminated players).
|
|
func get_opponents() -> Array:
|
|
var result: Array = []
|
|
for p: Dictionary in state.get("players", []):
|
|
if str(p.get("accountId", "")) != Auth.user_id:
|
|
result.append(p)
|
|
return result
|
|
|
|
|
|
## Returns the PlayerStateDto dict for the (first) opponent — backward-compat alias.
|
|
func get_opponent() -> Dictionary:
|
|
var opps := get_opponents()
|
|
return opps[0] if not opps.is_empty() else {}
|
|
|
|
|
|
## Returns the display name for an account ID, using the name embedded in the game state.
|
|
## Falls back to the first 8 characters of the ID if no name is available.
|
|
func get_display_name(account_id: String) -> String:
|
|
if account_id.is_empty(): return "?"
|
|
for p: Dictionary in state.get("players", []):
|
|
if str(p.get("accountId", "")) == account_id:
|
|
var dn : String = str(p.get("displayName", ""))
|
|
if not dn.is_empty(): return dn
|
|
break
|
|
return account_id.substr(0, min(8, account_id.length()))
|
|
|
|
|
|
## Returns true when it is the local player's turn.
|
|
func is_my_turn() -> bool:
|
|
return str(state.get("activePlayerAccountId", "")) == Auth.user_id
|
|
|
|
|
|
## Returns the current phase string (Placement | Draw | Main | End | GameOver).
|
|
func get_phase() -> String:
|
|
return state.get("phase", "")
|
|
|
|
|
|
## Returns the BoardDto dict, or {}.
|
|
func get_board() -> Dictionary:
|
|
return state.get("board", {})
|
|
|
|
|
|
func _as_array(v: Variant) -> Array:
|
|
return v as Array if v is Array else []
|
|
|
|
|
|
## Returns Array of TileDto dicts.
|
|
func get_tiles() -> Array:
|
|
return _as_array(get_board().get("tiles", []))
|
|
|
|
|
|
## Returns the local player's hand (Array of CardInstanceDto dicts).
|
|
func get_hand() -> Array:
|
|
return _as_array(get_my_player().get("hand", []))
|
|
|
|
|
|
## Returns the local player's field (Array of CardInstanceDto dicts).
|
|
func get_field() -> Array:
|
|
return _as_array(get_my_player().get("field", []))
|
|
|
|
|
|
## Returns the opponent's field (Array of CardInstanceDto dicts).
|
|
func get_opponent_field() -> Array:
|
|
return _as_array(get_opponent().get("field", []))
|
|
|
|
|
|
## Returns all enemy PlayerStateDto dicts (players not on the same team as the local player).
|
|
func get_enemy_players() -> Array:
|
|
var my_team : int = int(get_my_player().get("teamIndex", -1))
|
|
var result : Array = []
|
|
for p: Dictionary in state.get("players", []):
|
|
var pid : String = str(p.get("accountId", ""))
|
|
if pid == Auth.user_id: continue
|
|
if int(p.get("teamIndex", -2)) != my_team:
|
|
result.append(p)
|
|
return result
|
|
|
|
|
|
## Returns all units (field + archSpirit) belonging to enemy players, as a flat Array.
|
|
func get_all_enemy_units() -> Array:
|
|
var units : Array = []
|
|
for p: Dictionary in get_enemy_players():
|
|
units.append_array(_as_array(p.get("field", [])))
|
|
var arch = p.get("archSpirit")
|
|
if arch is Dictionary and not (arch as Dictionary).is_empty():
|
|
units.append(arch)
|
|
return units
|
|
|
|
|
|
## Returns all units (field + archSpirit) belonging to allied players
|
|
## (same team, not the local player). Empty in FFA games.
|
|
func get_ally_units() -> Array:
|
|
var my_team : int = int(get_my_player().get("teamIndex", -1))
|
|
var units : Array = []
|
|
if my_team < 0:
|
|
return units
|
|
for p: Dictionary in state.get("players", []):
|
|
var pid : String = str(p.get("accountId", ""))
|
|
if pid == Auth.user_id: continue
|
|
if int(p.get("teamIndex", -2)) != my_team: continue
|
|
units.append_array(_as_array(p.get("field", [])))
|
|
var arch = p.get("archSpirit")
|
|
if arch is Dictionary and not (arch as Dictionary).is_empty():
|
|
units.append(arch)
|
|
return units
|
|
|
|
|
|
## Returns a TileDto dict by coord, or {}.
|
|
func get_tile(x: int, y: int) -> Dictionary:
|
|
for t: Dictionary in get_tiles():
|
|
var c: Dictionary = t.get("coord", {})
|
|
if c.get("x", -1) == x and c.get("y", -1) == y:
|
|
return t
|
|
return {}
|
|
|
|
|
|
## Returns a CardInstanceDto from any player's field by instanceId, or {}.
|
|
func get_unit_by_id(instance_id: String) -> Dictionary:
|
|
for p: Dictionary in state.get("players", []):
|
|
for u: Dictionary in p.get("field", []):
|
|
if u.get("instanceId", "") == instance_id:
|
|
return u
|
|
var arch_val: Variant = p.get("archSpirit")
|
|
if arch_val is Dictionary and not (arch_val as Dictionary).is_empty():
|
|
if (arch_val as Dictionary).get("instanceId", "") == instance_id:
|
|
return arch_val
|
|
return {}
|
|
|
|
|
|
## Returns the board width (default 8).
|
|
func board_width() -> int:
|
|
return get_board().get("width", 8)
|
|
|
|
|
|
## Returns the board height (default 8).
|
|
func board_height() -> int:
|
|
return get_board().get("height", 8)
|
|
|
|
# ── Server actions ────────────────────────────────────────────────────────────
|
|
|
|
func send_ready() -> void:
|
|
if debug_output:
|
|
print("[Game] >>> game.ready sessionId=", session_id)
|
|
Network.request("game.ready",
|
|
{ "sessionId": session_id },
|
|
func(_t: String, p: Variant) -> void:
|
|
if debug_output:
|
|
print("[Game] <<< game.ready.ack ", JSON.stringify(p))
|
|
var d := p as Dictionary
|
|
if d.get("status", "") == "AlreadyStarted":
|
|
# Restore opponent name on rejoin — the server includes it in the ack.
|
|
var oname: String = str(d.get("opponentDisplayName", ""))
|
|
if not oname.is_empty():
|
|
opponent_name = oname
|
|
_fetch_state(),
|
|
func(code: String, msg: String) -> void:
|
|
if debug_output:
|
|
print("[Game] ERR game.ready code=", code, " msg=", msg))
|
|
|
|
|
|
func _fetch_state() -> void:
|
|
if _syncing:
|
|
return
|
|
_syncing = true
|
|
Network.request("game.get_state",
|
|
{ "sessionId": session_id },
|
|
func(_t: String, p: Variant) -> void:
|
|
_syncing = false
|
|
_apply_state_from_payload(p),
|
|
func(_c: String, _m: String) -> void:
|
|
_syncing = false)
|
|
|
|
|
|
func send_draw() -> void:
|
|
_game_request("game.draw", {})
|
|
|
|
|
|
func send_place_arch_spirit(x: int, y: int) -> void:
|
|
_game_request("game.place_arch_spirit",
|
|
{ "position": { "x": x, "y": y } })
|
|
|
|
|
|
func send_play_card(card_instance_id: String, target_x: int, target_y: int) -> void:
|
|
_game_request("game.play_card", {
|
|
"cardInstanceId": card_instance_id,
|
|
"targetTile": { "x": target_x, "y": target_y }
|
|
})
|
|
|
|
|
|
func send_play_card_multi(card_instance_id: String, targets: Array) -> void:
|
|
_game_request("game.play_card", {
|
|
"cardInstanceId": card_instance_id,
|
|
"targetTiles": targets
|
|
})
|
|
|
|
|
|
func send_play_card_with_targets(card_instance_id: String, targets: Array) -> void:
|
|
var payload := { "cardInstanceId": card_instance_id }
|
|
if not targets.is_empty():
|
|
payload["targets"] = targets
|
|
_game_request("game.play_card", payload)
|
|
|
|
|
|
func send_move_unit(unit_instance_id: String, target_x: int, target_y: int) -> void:
|
|
_game_request("game.move_unit", {
|
|
"unitInstanceId": unit_instance_id,
|
|
"targetPosition": { "x": target_x, "y": target_y }
|
|
})
|
|
|
|
|
|
func send_attack(attacker_id: String, target_id: String) -> void:
|
|
_game_request("game.attack", {
|
|
"attackerInstanceId": attacker_id,
|
|
"targetInstanceId": target_id
|
|
})
|
|
|
|
|
|
func send_sacrifice(unit_id: String) -> void:
|
|
_game_request("game.sacrifice", { "unitInstanceId": unit_id })
|
|
|
|
|
|
func send_end_turn() -> void:
|
|
_game_request("game.end_turn", {})
|
|
|
|
|
|
func send_concede() -> void:
|
|
_game_request("game.concede", {})
|
|
|
|
|
|
func send_force_concede() -> void:
|
|
_game_request("game.force_concede", {})
|
|
|
|
|
|
func send_ascend(incoming_card_instance_id: String) -> void:
|
|
_game_request("game.ascend",
|
|
{ "incomingCardInstanceId": incoming_card_instance_id })
|
|
|
|
|
|
func send_transition(incoming_card_instance_id: String) -> void:
|
|
_game_request("game.transition",
|
|
{ "incomingCardInstanceId": incoming_card_instance_id })
|
|
|
|
|
|
func send_activate_ability(source_id: String, ability_index: int,
|
|
targets: Array = []) -> void:
|
|
var payload := {
|
|
"sourceInstanceId": source_id,
|
|
"abilityIndex": ability_index
|
|
}
|
|
if not targets.is_empty():
|
|
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)
|
|
|
|
|
|
func send_cost_pick_response(request_id: String, selected_instance_ids: Array) -> void:
|
|
_game_request("game.cost_pick", {
|
|
"requestId": request_id,
|
|
"selectedInstanceIds": selected_instance_ids
|
|
})
|
|
|
|
|
|
func send_cost_group_pick_response(request_id: String, choice_index: int) -> void:
|
|
_game_request("game.cost_group_pick", {
|
|
"requestId": request_id,
|
|
"choiceIndex": choice_index
|
|
})
|
|
|
|
|
|
func send_action_group_pick_response(request_id: String, choice_index: int) -> void:
|
|
_game_request("game.action_group_pick", {
|
|
"requestId": request_id,
|
|
"choiceIndex": choice_index
|
|
})
|
|
|
|
|
|
func send_branch_pick_response(request_id: String, branch_index: int) -> void:
|
|
_game_request("game.branch_pick", {
|
|
"requestId": request_id,
|
|
"branchIndex": branch_index
|
|
})
|
|
|
|
|
|
func send_target_pick_response(request_id: String, targets: Array) -> void:
|
|
var payload : Dictionary = { "requestId": request_id }
|
|
if not targets.is_empty():
|
|
payload["targets"] = targets
|
|
_game_request("game.target_pick", payload)
|
|
|
|
|
|
func send_tile_pick_response(request_id: String, x: int, y: int) -> void:
|
|
_game_request("game.tile_pick", { "requestId": request_id, "x": x, "y": y })
|
|
|
|
|
|
func send_player_pick_response(request_id: String, picked_player_id: String) -> void:
|
|
_game_request("game.player_pick", {
|
|
"requestId": request_id,
|
|
"pickedPlayerId": picked_player_id
|
|
})
|
|
|
|
|
|
func send_reveal_choice_pick_response(request_id: String, ordered_indices: Array) -> void:
|
|
_game_request("game.reveal_choice_pick", {
|
|
"requestId": request_id,
|
|
"orderedIndices": ordered_indices
|
|
})
|
|
|
|
# ── Private ───────────────────────────────────────────────────────────────────
|
|
|
|
## Pick/response messages where the client optimistically tears down its prompt UI
|
|
## before the server confirms. If the server rejects the pick, the pending prompt
|
|
## still exists server-side — re-fetching state makes GameGetStateHandler re-push
|
|
## it so the player is never stuck without a prompt.
|
|
const _PROMPT_RESPONSE_TYPES: Array[String] = [
|
|
"game.triggered_target", "game.cost_pick", "game.cost_group_pick",
|
|
"game.action_group_pick", "game.branch_pick", "game.target_pick",
|
|
"game.tile_pick", "game.player_pick", "game.reveal_choice_pick",
|
|
]
|
|
|
|
func _game_request(msg_type: String, extra: Dictionary) -> void:
|
|
var payload := { "sessionId": session_id }
|
|
payload.merge(extra)
|
|
if debug_output:
|
|
print("[Game] >>> ", msg_type, " ", JSON.stringify(extra))
|
|
Network.request(msg_type, payload,
|
|
func(_t: String, p: Variant) -> void:
|
|
if debug_output:
|
|
print("[Game] <<< ", msg_type, ".ack payload=", JSON.stringify(p))
|
|
_apply_state_from_payload(p),
|
|
func(code: String, msg: String) -> void:
|
|
if debug_output:
|
|
print("[Game] ERR ", msg_type, " code=", code, " msg=", msg)
|
|
if msg_type in _PROMPT_RESPONSE_TYPES:
|
|
_fetch_state())
|
|
|
|
|
|
func _apply_state_from_payload(p: Variant) -> void:
|
|
var d := p as Dictionary
|
|
var s := d.get("state", {}) as Dictionary
|
|
if s.is_empty():
|
|
if debug_output:
|
|
print("[Game] _apply_state_from_payload: no 'state' key in payload ", JSON.stringify(p))
|
|
return
|
|
# Discard stale responses that belong to a session we have already left.
|
|
var response_sid: String = str(s.get("sessionId", ""))
|
|
if not session_id.is_empty() and not response_sid.is_empty() \
|
|
and response_sid != session_id:
|
|
if debug_output:
|
|
print("[Game] _apply_state_from_payload: ignored stale response for session ", response_sid)
|
|
return
|
|
_state_version = int(s.get("stateVersion", -1))
|
|
if debug_output:
|
|
print("[Game] state applied phase=", s.get("phase","?"),
|
|
" turn=", s.get("turnNumber","?"),
|
|
" ver=", _state_version,
|
|
" activePlayer=", str(s.get("activePlayerAccountId","?")).substr(0,8))
|
|
state = s
|
|
state_updated.emit(state)
|
|
|
|
|
|
## Request a full state resync from the server (e.g. from in-game settings, or auto on missed delta).
|
|
func request_sync() -> void:
|
|
if session_id.is_empty(): return
|
|
if debug_output:
|
|
print("[Game] requesting full state sync")
|
|
if is_spectating:
|
|
_request_spectator_state()
|
|
else:
|
|
_fetch_state()
|
|
|
|
|
|
func _player_by_id(account_id: String) -> Dictionary:
|
|
for p: Dictionary in state.get("players", []):
|
|
if str(p.get("accountId", "")).to_lower() == account_id.to_lower():
|
|
return p
|
|
return {}
|
|
|
|
|
|
func _apply_delta(delta: Dictionary) -> void:
|
|
# Helper: dict.get(key, default) returns null (not default) when the key exists with value null.
|
|
# Use 'is Array' / 'is Dictionary' guards so typed assignment never receives null.
|
|
if debug_output:
|
|
print("DELTA: ", delta)
|
|
# 1. Changed tiles
|
|
var changed_tiles = delta.get("changedTiles")
|
|
if changed_tiles is Array:
|
|
var tiles: Array = state.get("board", {}).get("tiles", [])
|
|
for td: Dictionary in changed_tiles:
|
|
var tx := int(td.get("x", -1))
|
|
var ty := int(td.get("y", -1))
|
|
for tile: Dictionary in tiles:
|
|
var c: Dictionary = tile.get("coord", {})
|
|
if c.get("x", -1) == tx and c.get("y", -1) == ty:
|
|
if td.has("base1") and td["base1"] != null: tile["base1"] = td["base1"]
|
|
if td.has("base2") and td["base2"] != null: tile["base2"] = td["base2"]
|
|
if td.has("resolvedAffinity") and td["resolvedAffinity"] != null: tile["resolvedAffinity"] = td["resolvedAffinity"]
|
|
if td.has("occupantCleared") and bool(td["occupantCleared"]): tile["occupantId"] = null; tile["occupantOwner"] = null
|
|
elif td.has("occupantId") and td["occupantId"] != null: tile["occupantId"] = td["occupantId"]
|
|
if td.has("occupantOwner") and td["occupantOwner"] != null: tile["occupantOwner"] = td["occupantOwner"]
|
|
if td.has("ruinCleared") and bool(td["ruinCleared"]): tile["ruinId"] = null; tile["ruinOwner"] = null
|
|
elif td.has("ruinId") and td["ruinId"] != null: tile["ruinId"] = td["ruinId"]
|
|
if td.has("ruinOwner") and td["ruinOwner"] != null: tile["ruinOwner"] = td["ruinOwner"]
|
|
break
|
|
|
|
# 2. Added units (new units entering the field)
|
|
var added_units = delta.get("unitsAdded")
|
|
if added_units is Array:
|
|
for add_entry: Dictionary in added_units:
|
|
var owner_id := str(add_entry.get("ownerAccountId", ""))
|
|
var unit := add_entry.get("unit", {}) as Dictionary
|
|
if unit.is_empty():
|
|
continue
|
|
var target := _player_by_id(owner_id)
|
|
if target.is_empty():
|
|
continue
|
|
var field: Array = target.get("field", [])
|
|
var exists := false
|
|
for u: Dictionary in field:
|
|
if str(u.get("instanceId", "")) == str(unit.get("instanceId", "")):
|
|
exists = true
|
|
break
|
|
if not exists:
|
|
field.append(unit)
|
|
|
|
# 3. Removed unit IDs
|
|
var removed_ids = delta.get("unitsRemoved")
|
|
if removed_ids is Array:
|
|
for iid: String in removed_ids:
|
|
for p: Dictionary in state.get("players", []):
|
|
var field: Array = p.get("field", [])
|
|
for i in range(field.size() - 1, -1, -1):
|
|
if field[i].get("instanceId", "") == iid:
|
|
field.remove_at(i)
|
|
break
|
|
|
|
# 4. Changed units (merge non-null UnitDelta fields)
|
|
var changed_units = delta.get("unitsChanged")
|
|
if changed_units is Array:
|
|
for ud: Dictionary in changed_units:
|
|
var iid := str(ud.get("instanceId", ""))
|
|
var unit := get_unit_by_id(iid)
|
|
if not unit.is_empty():
|
|
_merge_unit_delta(unit, ud)
|
|
|
|
# 5. Viewer-private zones (own hand/discard only)
|
|
var private_delta = delta.get("privateByViewer")
|
|
if private_delta is Dictionary and not private_delta.is_empty():
|
|
var hand_added = private_delta.get("handAdded")
|
|
if hand_added is Array and not hand_added.is_empty():
|
|
var my_hand: Array = get_my_player().get("hand", [])
|
|
for card: Dictionary in hand_added:
|
|
my_hand.append(card)
|
|
|
|
var hand_removed = private_delta.get("handRemovedIds")
|
|
if hand_removed is Array:
|
|
var my_hand: Array = get_my_player().get("hand", [])
|
|
for iid: String in hand_removed:
|
|
for i in range(my_hand.size() - 1, -1, -1):
|
|
if my_hand[i].get("instanceId", "") == iid:
|
|
my_hand.remove_at(i)
|
|
break
|
|
|
|
var discard_added = private_delta.get("discardAdded")
|
|
if discard_added is Array and not discard_added.is_empty():
|
|
var my_discard: Array = get_my_player().get("discard", [])
|
|
for card: Dictionary in discard_added:
|
|
my_discard.append(card)
|
|
|
|
# 6. Public counts by account
|
|
var public_counts = delta.get("publicCountsByAccount")
|
|
if public_counts is Dictionary:
|
|
for aid_v: Variant in public_counts.keys():
|
|
var aid := str(aid_v)
|
|
var counts := public_counts.get(aid, {}) as Dictionary
|
|
var player := _player_by_id(aid)
|
|
if player.is_empty() or counts.is_empty():
|
|
continue
|
|
if counts.has("handCount") and counts["handCount"] != null: player["handCount"] = int(counts["handCount"])
|
|
if counts.has("deckCount") and counts["deckCount"] != null: player["deckCount"] = int(counts["deckCount"])
|
|
if counts.has("discardCount") and counts["discardCount"] != null: player["discardCount"] = int(counts["discardCount"])
|
|
|
|
# 7. ArchSpirit updates by account
|
|
var arch_by_account = delta.get("archSpiritByAccount")
|
|
if arch_by_account is Dictionary:
|
|
for aid_v: Variant in arch_by_account.keys():
|
|
var aid := str(aid_v)
|
|
var arch_update := arch_by_account.get(aid, {}) as Dictionary
|
|
if arch_update.is_empty():
|
|
continue
|
|
var player := _player_by_id(aid)
|
|
if player.is_empty():
|
|
continue
|
|
var full_arch : Variant = arch_update.get("full")
|
|
if full_arch is Dictionary and not (full_arch as Dictionary).is_empty():
|
|
player["archSpirit"] = full_arch
|
|
continue
|
|
var arch_delta := arch_update.get("delta") as Dictionary
|
|
if arch_delta.is_empty():
|
|
continue
|
|
var arch_val: Variant = player.get("archSpirit")
|
|
if arch_val == null or not (arch_val is Dictionary):
|
|
request_sync()
|
|
continue
|
|
var arch := arch_val as Dictionary
|
|
if arch.is_empty():
|
|
# Missing baseline (likely first sight of this arch). Ask for full sync.
|
|
request_sync()
|
|
continue
|
|
_merge_unit_delta(arch, arch_delta)
|
|
|
|
# 8. Player stats by account
|
|
var stats_by_account = delta.get("playerStatsByAccount")
|
|
if stats_by_account is Dictionary:
|
|
for aid_v: Variant in stats_by_account.keys():
|
|
var aid := str(aid_v)
|
|
var stats := stats_by_account.get(aid, {}) as Dictionary
|
|
if stats.is_empty():
|
|
continue
|
|
var player := _player_by_id(aid)
|
|
if player.is_empty():
|
|
continue
|
|
if stats.has("currentSp") and stats["currentSp"] != null: player["currentSp"] = int(stats["currentSp"])
|
|
if stats.has("currentSt") and stats["currentSt"] != null: player["currentSt"] = int(stats["currentSt"])
|
|
if stats.has("deckCount") and stats["deckCount"] != null: player["deckCount"] = int(stats["deckCount"])
|
|
if stats.has("handCount") and stats["handCount"] != null: player["handCount"] = int(stats["handCount"])
|
|
if stats.has("discardCount") and stats["discardCount"] != null: player["discardCount"] = int(stats["discardCount"])
|
|
|
|
# 9. Meta
|
|
var meta = delta.get("metaDelta")
|
|
if meta is Dictionary and not meta.is_empty():
|
|
if meta.has("phase") and meta["phase"] != null: state["phase"] = meta["phase"]
|
|
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"])
|
|
|
|
# 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))
|
|
if debug_output:
|
|
print("[Game] delta applied ver=", _state_version,
|
|
" phase=", state.get("phase","?"),
|
|
" turn=", state.get("turnNumber","?"))
|
|
state_updated.emit(state)
|
|
|
|
|
|
func _merge_unit_delta(unit: Dictionary, ud: Dictionary) -> void:
|
|
if ud.has("currentHealth") and ud["currentHealth"] != null: unit["currentHealth"] = int(ud["currentHealth"])
|
|
if ud.has("maxHealth") and ud["maxHealth"] != null: unit["maxHealth"] = int(ud["maxHealth"])
|
|
if ud.has("currentDefense") and ud["currentDefense"] != null: unit["currentDefense"] = int(ud["currentDefense"])
|
|
if ud.has("maxDefense") and ud["maxDefense"] != null: unit["maxDefense"] = int(ud["maxDefense"])
|
|
if ud.has("damage") and ud["damage"] != null: unit["damage"] = int(ud["damage"])
|
|
if ud.has("isExhausted") and ud["isExhausted"] != null: unit["isExhausted"] = bool(ud["isExhausted"])
|
|
if ud.has("canMove") and ud["canMove"] != null: unit["canMove"] = bool(ud["canMove"])
|
|
if ud.has("canAttack") and ud["canAttack"] != null: unit["canAttack"] = bool(ud["canAttack"])
|
|
if ud.has("canBeAttacked") and ud["canBeAttacked"] != null: unit["canBeAttacked"] = bool(ud["canBeAttacked"])
|
|
if ud.has("canUseAbility") and ud["canUseAbility"] != null: unit["canUseAbility"] = bool(ud["canUseAbility"])
|
|
if ud.has("currentMp") and ud["currentMp"] != null: unit["currentMp"] = int(ud["currentMp"])
|
|
if ud.has("maxMp") and ud["maxMp"] != null: unit["maxMp"] = int(ud["maxMp"])
|
|
if ud.has("extraAttacksRemaining") and ud["extraAttacksRemaining"] != null: unit["extraAttacksRemaining"] = int(ud["extraAttacksRemaining"])
|
|
if ud.has("position") and ud["position"] != null: unit["position"] = ud["position"]
|
|
if ud.has("effectsJson") and ud["effectsJson"] != null: unit["effectsJson"] = ud["effectsJson"]
|
|
if ud.has("abilitiesJson") and ud["abilitiesJson"] != null: unit["abilitiesJson"] = ud["abilitiesJson"]
|
|
if ud.has("abilityUsesJson") and ud["abilityUsesJson"] != null: unit["abilityUsesJson"] = ud["abilityUsesJson"]
|
|
# art2dUrl and modelUrl are not merged from deltas — they are fixed per card definition
|
|
# and are set once when the unit is added via unitsAdded (UnitSnapshot).
|
|
|
|
|
|
func _on_server_push(type: String, payload: Variant) -> void:
|
|
if type.begins_with("game.") or type.begins_with("matchmaking."):
|
|
if debug_output:
|
|
print("[Game] PUSH ", type, " ", JSON.stringify(payload).substr(0, 800))
|
|
match type:
|
|
"matchmaking.match_found":
|
|
var d := payload as Dictionary
|
|
var sid : String = str(d.get("gameSessionId", ""))
|
|
var oname : String = str(d.get("opponentDisplayName", "Opponent"))
|
|
var orank : int = int(d.get("opponentRankScore", 0))
|
|
state = {} # Clear any stale previous-game state before new session starts
|
|
session_id = sid
|
|
opponent_name = oname
|
|
match_found.emit(sid, oname, orank)
|
|
|
|
"game.state_update":
|
|
var d := payload as Dictionary
|
|
var s := d.get("state", {}) as Dictionary
|
|
if not s.is_empty():
|
|
# Drop stale spectator pushes that belong to a session we already left.
|
|
var update_sid : String = str(s.get("sessionId", ""))
|
|
if not session_id.is_empty() and update_sid != session_id:
|
|
if debug_output:
|
|
print("[Game] PUSH state_update IGNORED (wrong session): ", update_sid)
|
|
return
|
|
_state_version = int(s.get("stateVersion", -1))
|
|
if debug_output:
|
|
print("[Game] PUSH state_update phase=", s.get("phase","?"),
|
|
" turn=", s.get("turnNumber","?"),
|
|
" ver=", _state_version,
|
|
" activePlayer=", str(s.get("activePlayerAccountId","?")).substr(0,8))
|
|
state = s
|
|
state_updated.emit(state)
|
|
else:
|
|
if debug_output:
|
|
print("[Game] PUSH state_update: no 'state' key")
|
|
|
|
"game.state_delta":
|
|
var d := payload as Dictionary
|
|
var delta := d.get("delta", {}) as Dictionary
|
|
if delta.is_empty(): return
|
|
var v := int(delta.get("stateVersion", -1))
|
|
if _state_version >= 0 and v <= _state_version:
|
|
# Already up to date — acting player received full state in ACK
|
|
return
|
|
if _state_version >= 0 and v > _state_version + 1:
|
|
if debug_output:
|
|
print("[Game] WARN: missed delta (have %d, got %d) — requesting full sync" \
|
|
% [_state_version, v])
|
|
_fetch_state()
|
|
return
|
|
if debug_output:
|
|
print("[Delta] ", delta)
|
|
_apply_delta(delta)
|
|
|
|
"game.over":
|
|
var d := payload as Dictionary
|
|
var winner : String = str(d.get("winnerAccountId", ""))
|
|
var wc : String = str(d.get("winCondition", ""))
|
|
var wd : int = int(d.get("winnerRankDelta", 0))
|
|
var ld : int = int(d.get("loserRankDelta", 0))
|
|
var _raw_outcomes = d.get("playerOutcomes")
|
|
var outcomes : Array = _raw_outcomes as Array if _raw_outcomes is Array else []
|
|
session_id = "" # Clear so _on_auth_reconnect doesn't resend game.ready for an ended game
|
|
state = {} # Clear stale state so a new GameScreen calls send_ready() on the next match
|
|
game_over.emit(winner, wc, wd, ld, outcomes)
|
|
|
|
"game.session_abandoned":
|
|
var d := payload as Dictionary
|
|
var reason : String = str(d.get("reason", "unknown"))
|
|
if debug_output:
|
|
print("[Game] session abandoned: ", reason)
|
|
_clear_state()
|
|
session_abandoned.emit(reason)
|
|
|
|
"game.opponent_inactive":
|
|
var d := payload as Dictionary
|
|
var sid : String = str(d.get("sessionId", ""))
|
|
if debug_output:
|
|
print("[Game] PUSH opponent_inactive session=", sid)
|
|
opponent_inactive.emit(sid)
|
|
|
|
"game.inactive_warning":
|
|
var d := payload as Dictionary
|
|
var sid : String = str(d.get("sessionId", ""))
|
|
if debug_output:
|
|
print("[Game] PUSH inactive_warning session=", sid)
|
|
inactive_warning.emit(sid)
|
|
|
|
"game.both_idle_warning":
|
|
var d := payload as Dictionary
|
|
var sid : String = str(d.get("sessionId", ""))
|
|
if debug_output:
|
|
print("[Game] PUSH both_idle_warning session=", sid)
|
|
both_idle_warning.emit(sid)
|
|
|
|
"game.player_eliminated":
|
|
var d := payload as Dictionary
|
|
player_eliminated.emit(
|
|
str(d.get("sessionId", "")),
|
|
str(d.get("eliminatedAccountId", "")),
|
|
int(d.get("seatIndex", -1)),
|
|
int(d.get("teamIndex", -1)))
|
|
|
|
"game.activity":
|
|
var d := payload as Dictionary
|
|
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)
|
|
|
|
"game.ability.cost_pick_request":
|
|
cost_pick_request.emit(payload as Dictionary)
|
|
|
|
"game.ability.cost_group_pick_request":
|
|
cost_group_pick_request.emit(payload as Dictionary)
|
|
|
|
"game.ability.action_group_pick_request":
|
|
action_group_pick_request.emit(payload as Dictionary)
|
|
|
|
"game.ability.branch_pick_request":
|
|
branch_pick_request.emit(payload as Dictionary)
|
|
|
|
"game.ability.target_pick_request":
|
|
target_pick_request.emit(payload as Dictionary)
|
|
|
|
"game.ability.tile_pick_request":
|
|
tile_pick_request.emit(payload as Dictionary)
|
|
|
|
"game.ability.player_pick_request":
|
|
player_pick_request.emit(payload as Dictionary)
|
|
|
|
"game.ability.reveal_choice_pick_request":
|
|
reveal_choice_pick_request.emit(payload as Dictionary)
|
|
|
|
"game.visual.repentance_placeholder":
|
|
repentance_placeholder_visual.emit(payload as Dictionary)
|
|
|
|
"game.visual.ability_placeholder":
|
|
ability_placeholder_visual.emit(payload as Dictionary)
|