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) # ── State ───────────────────────────────────────────────────────────────────── var session_id : String = "" var state : Dictionary = {} var opponent_name : String = "" var is_spectating : bool = false var _state_version : int = -1 # ── 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 ## Called on every auth_success (initial login AND reconnects). ## If we have an active session, resend game.ready so the server ## re-registers this connection and we get state updates again. func _on_auth_reconnect(_uid: String, _dn: String) -> void: if not session_id.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 Network.request("game.spectate", { "sessionId": sid }, func(_t: String, p: Variant) -> void: print("[Game] <<< game.spectate.ack") _apply_state_from_payload(p), func(code: String, msg: String) -> void: 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 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", {}) ## Returns Array of TileDto dicts. func get_tiles() -> Array: return get_board().get("tiles", []) ## Returns the local player's hand (Array of CardInstanceDto dicts). func get_hand() -> Array: return get_my_player().get("hand", []) ## Returns the local player's field (Array of CardInstanceDto dicts). func get_field() -> Array: return get_my_player().get("field", []) ## Returns the opponent's field (Array of CardInstanceDto dicts). func get_opponent_field() -> Array: return 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(p.get("field", [])) var arch : Dictionary = p.get("archSpirit", {}) if not arch.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: Dictionary = p.get("archSpirit", {}) if arch.get("instanceId", "") == instance_id: return arch 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: print("[Game] >>> game.ready sessionId=", session_id) Network.request("game.ready", { "sessionId": session_id }, func(_t: String, p: Variant) -> void: 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: print("[Game] ERR game.ready code=", code, " msg=", msg)) func _fetch_state() -> void: Network.request("game.get_state", { "sessionId": session_id }, func(_t: String, p: Variant) -> void: _apply_state_from_payload(p), func(_c: String, _m: String) -> void: pass) 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) # ── Private ─────────────────────────────────────────────────────────────────── func _game_request(msg_type: String, extra: Dictionary) -> void: var payload := { "sessionId": session_id } payload.merge(extra) print("[Game] >>> ", msg_type, " ", JSON.stringify(extra)) Network.request(msg_type, payload, func(_t: String, p: Variant) -> void: print("[Game] <<< ", msg_type, ".ack payload=", JSON.stringify(p)) _apply_state_from_payload(p), func(code: String, msg: String) -> void: print("[Game] ERR ", msg_type, " code=", code, " msg=", msg)) func _apply_state_from_payload(p: Variant) -> void: var d := p as Dictionary var s := d.get("state", {}) as Dictionary if s.is_empty(): print("[Game] _apply_state_from_payload: no 'state' key in payload ", JSON.stringify(p)) return _state_version = int(s.get("stateVersion", -1)) 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 print("[Game] requesting full state sync") _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. 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("addedUnits") if added_units is Array: for unit: Dictionary in added_units: var owner_id := str(unit.get("ownerId", "")) # not on CardInstanceDto, use position to find by ownerId? # CardInstanceDto doesn't carry ownerId; find the right player by checking which player # doesn't already have this unit. We append to the player who owns the tile. # Fallback: use the unit's position coord to find the tile's occupant owner. var placed := false for p: Dictionary in state.get("players", []): var field: Array = p.get("field", []) # Check if this player already has the unit (shouldn't happen) var found := false for u: Dictionary in field: if u.get("instanceId", "") == unit.get("instanceId", ""): found = true break if not found and not placed: # Determine ownership from the tile's occupantOwner matching this player's accountId var pos: Dictionary = unit.get("position", {}) if not pos.is_empty(): var tile := get_tile(int(pos.get("x", -1)), int(pos.get("y", -1))) if str(tile.get("occupantOwner", "")).to_lower() == str(p.get("accountId", "")).to_lower(): field.append(unit) placed = true # Fallback if we couldn't place via tile: append to active player's field if not placed: var my_p := get_my_player() if not my_p.is_empty(): my_p.get("field", []).append(unit) # 3. Removed unit IDs var removed_ids = delta.get("removedUnitIds") 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("changedUnits") 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. Hand added / removed (own player only) var hand_added = 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 = 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 # 6. Discard added var discard_added = 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) # 7. Opponent hand / deck counts var opp_hand_count = delta.get("opponentHandCount") var opp_deck_count = delta.get("opponentDeckCount") var opp := get_opponent() if not opp.is_empty(): if opp_hand_count != null: opp["handCount"] = int(opp_hand_count) if opp_deck_count != null: opp["deckCount"] = int(opp_deck_count) # 8. ArchSpirits var own_arch_delta = delta.get("ownArchSpiritDelta") if own_arch_delta is Dictionary and not own_arch_delta.is_empty(): var my_arch: Dictionary = get_my_player().get("archSpirit", {}) if not my_arch.is_empty(): _merge_unit_delta(my_arch, own_arch_delta) var opp_arch_delta = delta.get("opponentArchSpiritDelta") if opp_arch_delta is Dictionary and not opp_arch_delta.is_empty(): var opp_arch: Dictionary = get_opponent().get("archSpirit", {}) if not opp_arch.is_empty(): _merge_unit_delta(opp_arch, opp_arch_delta) # 9. Player stats var own_stats = delta.get("ownStatsDelta") if own_stats is Dictionary and not own_stats.is_empty(): var my_p := get_my_player() if not my_p.is_empty(): if own_stats.has("currentSp") and own_stats["currentSp"] != null: my_p["currentSp"] = int(own_stats["currentSp"]) if own_stats.has("currentSt") and own_stats["currentSt"] != null: my_p["currentSt"] = int(own_stats["currentSt"]) if own_stats.has("deckCount") and own_stats["deckCount"] != null: my_p["deckCount"] = int(own_stats["deckCount"]) if own_stats.has("handCount") and own_stats["handCount"] != null: my_p["handCount"] = int(own_stats["handCount"]) if own_stats.has("discardCount") and own_stats["discardCount"] != null: my_p["discardCount"] = int(own_stats["discardCount"]) var opp_stats = delta.get("opponentStatsDelta") if opp_stats is Dictionary and not opp_stats.is_empty(): var opp_p := get_opponent() if not opp_p.is_empty(): if opp_stats.has("currentSp") and opp_stats["currentSp"] != null: opp_p["currentSp"] = int(opp_stats["currentSp"]) if opp_stats.has("currentSt") and opp_stats["currentSt"] != null: opp_p["currentSt"] = int(opp_stats["currentSt"]) if opp_stats.has("deckCount") and opp_stats["deckCount"] != null: opp_p["deckCount"] = int(opp_stats["deckCount"]) if opp_stats.has("handCount") and opp_stats["handCount"] != null: opp_p["handCount"] = int(opp_stats["handCount"]) if opp_stats.has("discardCount") and opp_stats["discardCount"] != null: opp_p["discardCount"] = int(opp_stats["discardCount"]) # 10. 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"]) _state_version = int(delta.get("stateVersion", _state_version)) 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"] func _on_server_push(type: String, payload: Variant) -> void: if type.begins_with("game.") or type.begins_with("matchmaking."): 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(): _state_version = int(s.get("stateVersion", -1)) 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: 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: print("[Game] WARN: missed delta (have %d, got %d) — requesting full sync" \ % [_state_version, v]) _fetch_state() return 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 outcomes : Array = d.get("playerOutcomes", []) as Array 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")) 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", "")) 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", "")) 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", "")) 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)