Files
sor/Client/origin-client/autoloads/Game.gd
T
d61ebe66b8 Phase 8: Free Play ready-up system + client scenes
Server (Phase A):
- CustomLobby: +HostReady/GuestReady/HostFirstTurnPref/GuestFirstTurnPref/MaxPlayers
- Migration: AddReadyUpSystem — applied to prod DB
- GameJoinCustomLobbyHandler: no longer auto-creates session; sets Full status,
  resets readiness, pushes CustomLobbyGuestJoinedPush to host
- GameLobbyReadyHandler (NEW): game.custom.lobby.ready — marks caller ready,
  resolves first-turn, creates session + pushes game.custom.started when all ready
- GameUnreadyHandler (NEW): game.custom.lobby.unready
- GameChangeLobbyDeckHandler (NEW): game.custom.lobby.change_deck
- GameUpdateLobbyRulesHandler (NEW): game.custom.update_rules (host only)
- GameListActiveLobbiesHandler (NEW): game.custom.list_active (Status==Started)
- GameListCustomLobbiesHandler: now batch-loads host/guest display names
- GameMessages: +LobbyReadyRequest/Response, UnreadyInLobbyRequest/Response,
  ChangeLobbyDeckRequest/Response, UpdateLobbyRulesRequest/Response,
  ListActiveLobbiesRequest/Response, LobbyReadyStatusPush, LobbyDeckChangedPush,
  ActiveLobbyDto; CustomLobbyDto +HostDisplayName/GuestDisplayName
- ServiceRegistration: register 5 new handlers

Client (Phase B):
- CustomLobby.gd: new autoload for Free Play lobby state + all server calls
- project.godot: register CustomLobby autoload
- MainScreen: +Free Play button → FreePlayScreen.tscn
- FreePlayScreen (NEW): Open Lobbies tab + Active Games tab + Create dialog
- LobbyRoomScreen (NEW): ready-up UI, first-turn selector, preset voting
- Game.gd: +is_spectating, +start_spectating(), +stop_spectating()
- game_screen.gd: spectator mode — SPECTATING label, hidden action buttons,
  neutral HUD labels, stop_spectating() on exit

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>
2026-03-19 09:10:55 -04:00

348 lines
12 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)
## 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)
# ── State ─────────────────────────────────────────────────────────────────────
var session_id : String = ""
var state : Dictionary = {}
var opponent_name : String = ""
var is_spectating : bool = false
# ── Lifecycle ─────────────────────────────────────────────────────────────────
func _ready() -> void:
Network.message_received.connect(_on_server_push)
Auth.session_expired.connect(_clear_state)
func _clear_state() -> void:
session_id = ""
state = {}
opponent_name = ""
is_spectating = false
## 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 the PlayerStateDto dict for the opponent, or {}.
func get_opponent() -> Dictionary:
for p: Dictionary in state.get("players", []):
if str(p.get("accountId", "")) != Auth.user_id:
return p
return {}
## 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 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":
_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
print("[Game] state applied phase=", s.get("phase","?"),
" turn=", s.get("turnNumber","?"),
" activePlayer=", str(s.get("activePlayerAccountId","?")).substr(0,8))
state = s
state_updated.emit(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 _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, 200))
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():
print("[Game] PUSH state_update phase=", s.get("phase","?"),
" turn=", s.get("turnNumber","?"),
" activePlayer=", str(s.get("activePlayerAccountId","?")).substr(0,8))
state = s
state_updated.emit(state)
else:
print("[Game] PUSH state_update: no 'state' key")
"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))
state = {} # Clear stale state so a new GameScreen calls send_ready() on the next match
game_over.emit(winner, wc, wd, ld)
"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)