- Remove max_players == 2 gate; use per-seat Add AI buttons in the
additional players panel instead of the guest-slot button
- Fix seat-indexed panel rendering: unified loop over all additional
seats detects AI slots, human players, and empty seats correctly
- Add _ai_adding guard to prevent concurrent add-AI requests that
caused the server race (second request overwrote first AI slot)
- Fix push handler reading wrong key ("slots" → "currentAiSlots")
which wiped ai_slots on every push, leaving only the newest AI
- Fix ACK handler reading wrong keys ("aiId"/"displayName" →
"aiAccountId"/"aiDisplayName")
- Server: fix all-ready check that required GuestAccountId.HasValue,
blocking start for no-guest lobbies filled via AdditionalPlayersJson
- Server: fix StartGameAsync null-deref on GuestAccountId and add
no-guest branch (host=P1, first additional=P2, rest=seats 2+)
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>
465 lines
18 KiB
GDScript
465 lines
18 KiB
GDScript
extends Node
|
|
## CustomLobby autoload — manages free-play lobby state and server communication.
|
|
##
|
|
## Maintains local state for the lobby the player is currently in (as host or guest),
|
|
## handles incoming server pushes from the lobby room, and exposes clean methods for
|
|
## all lobby actions (create, join, leave, ready, unready, change deck, update rules,
|
|
## preset management).
|
|
##
|
|
## Usage:
|
|
## CustomLobby.lobby_id ← current lobby GUID string
|
|
## CustomLobby.lobby ← latest lobby details dict
|
|
## CustomLobby.is_host ← bool
|
|
## CustomLobby.i_am_ready ← bool
|
|
## CustomLobby.partner_ready ← bool
|
|
|
|
# ── Signals ───────────────────────────────────────────────────────────────────
|
|
|
|
## Pushed when a guest joins the host's open lobby.
|
|
signal guest_joined(guest_account_id: String, guest_display_name: String)
|
|
|
|
## Pushed when the host updates lobby rules (or a preset vote is approved).
|
|
signal lobby_rules_updated(new_rules: Dictionary)
|
|
|
|
## Pushed when a participant changes their selected deck.
|
|
signal lobby_deck_changed(account_id: String, deck_id: String)
|
|
|
|
## Pushed when any participant's ready status changes.
|
|
signal ready_status_changed(host_ready: bool, guest_ready: bool)
|
|
|
|
## Pushed when both players are ready and the game session has been created.
|
|
## Navigate to GameScreen.tscn after receiving this.
|
|
signal game_starting(session_id: String, opponent_account_id: String, opponent_display_name: String)
|
|
|
|
## Pushed when the host proposes loading a preset; guests should show a vote banner.
|
|
signal preset_vote_requested(payload: Dictionary)
|
|
|
|
## Pushed when a preset vote is rejected.
|
|
signal preset_vote_rejected(lobby_id: String, preset_id: String)
|
|
|
|
## Emitted locally when the player has left or cancelled the lobby.
|
|
signal lobby_left
|
|
|
|
## Pushed by the server when the other participant leaves a Full lobby.
|
|
## reason is "host_cancelled" or "guest_left".
|
|
signal partner_left(reason: String)
|
|
|
|
## Pushed to the host when the guest submits a rule suggestion.
|
|
## rules is the raw CustomRulesOverride dict (camelCase nullable fields).
|
|
signal rule_suggestion_received(rules: Dictionary)
|
|
|
|
## Pushed to the guest when the host rejects their rule suggestion.
|
|
signal rule_suggestion_rejected
|
|
|
|
## Emitted when a lobby action is rejected gracefully (non-fatal), for lightweight UX toasts.
|
|
signal lobby_notice(message: String)
|
|
|
|
## Pushed (or acked) when the host changes a seat's team assignment.
|
|
signal team_assignment_changed(seat_teams: Dictionary)
|
|
|
|
## Emitted when the AI slot list for the current lobby changes (add / server push).
|
|
signal ai_slots_changed(ai_slots: Array)
|
|
|
|
# ── State ─────────────────────────────────────────────────────────────────────
|
|
|
|
var lobby_id : String = ""
|
|
var lobby : Dictionary = {}
|
|
var my_deck_id : String = ""
|
|
var is_host : bool = false
|
|
var is_additional : bool = false # true for 3rd+ players (not host, not first guest)
|
|
var i_am_ready : bool = false
|
|
var partner_ready : bool = false
|
|
var first_turn_pref : String = "random"
|
|
var max_players : int = 2
|
|
var game_mode : String = "FFA"
|
|
var team_count : int = 1
|
|
## Seat index → team index overrides. Empty = use default (seat % team_count).
|
|
var seat_teams : Dictionary = {}
|
|
## Current AI slots in this lobby (array of dicts: accountId, displayName, difficulty, strategy, seatIndex).
|
|
var ai_slots : Array = []
|
|
|
|
# ── Lifecycle ─────────────────────────────────────────────────────────────────
|
|
|
|
func _ready() -> void:
|
|
Network.message_received.connect(_on_server_push)
|
|
Auth.session_expired.connect(clear_state)
|
|
|
|
|
|
func clear_state() -> void:
|
|
lobby_id = ""
|
|
lobby = {}
|
|
my_deck_id = ""
|
|
is_host = false
|
|
is_additional = false
|
|
i_am_ready = false
|
|
partner_ready = false
|
|
first_turn_pref = "random"
|
|
max_players = 2
|
|
game_mode = "FFA"
|
|
team_count = 1
|
|
seat_teams = {}
|
|
ai_slots = []
|
|
|
|
# ── Public actions ────────────────────────────────────────────────────────────
|
|
|
|
## Create a new lobby. On success, lobby_id and is_host are set; navigate to LobbyRoomScreen.
|
|
func create(lobby_name: String, deck_id: String, password: String,
|
|
rules_override: Dictionary,
|
|
p_max_players: int = 2, p_game_mode: String = "FFA", p_team_count: int = 1,
|
|
on_success: Callable = Callable(),
|
|
on_error: Callable = Callable()) -> void:
|
|
clear_state()
|
|
my_deck_id = deck_id
|
|
max_players = p_max_players
|
|
game_mode = p_game_mode
|
|
team_count = p_team_count
|
|
var payload := {
|
|
"lobbyName": lobby_name,
|
|
"deckId": deck_id,
|
|
"maxPlayers": p_max_players,
|
|
"gameMode": p_game_mode,
|
|
"teamCount": p_team_count,
|
|
}
|
|
if password != "":
|
|
payload["password"] = password
|
|
if not rules_override.is_empty():
|
|
payload["rules"] = rules_override
|
|
Network.request("game.custom.create", payload,
|
|
func(_t: String, p: Variant) -> void:
|
|
var d := p as Dictionary
|
|
lobby_id = str(d.get("lobbyId", ""))
|
|
lobby = d
|
|
is_host = true
|
|
# Extract server-confirmed values (server may adjust/clamp).
|
|
max_players = int(d.get("maxPlayers", p_max_players))
|
|
game_mode = str(d.get("gameMode", p_game_mode))
|
|
team_count = int(d.get("teamCount", p_team_count))
|
|
if on_success.is_valid(): on_success.call(d),
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR create ", code, " ", msg)
|
|
if on_error.is_valid(): on_error.call(code, msg))
|
|
|
|
|
|
## Join an existing open lobby. On success, lobby_id and is_host=false are set.
|
|
func join(lid: String, deck_id: String, password: String,
|
|
on_success: Callable = Callable(),
|
|
on_error: Callable = Callable()) -> void:
|
|
clear_state()
|
|
my_deck_id = deck_id
|
|
var payload := { "lobbyId": lid, "deckId": deck_id }
|
|
if password != "":
|
|
payload["password"] = password
|
|
Network.request("game.custom.join", payload,
|
|
func(_t: String, p: Variant) -> void:
|
|
var d := p as Dictionary
|
|
lobby_id = str(d.get("lobbyId", ""))
|
|
lobby = d
|
|
is_host = false
|
|
is_additional = bool(d.get("isAdditionalPlayer", false))
|
|
max_players = int(d.get("maxPlayers", 2))
|
|
game_mode = str(d.get("gameMode", "FFA"))
|
|
team_count = int(d.get("teamCount", 1))
|
|
# Ensure the lobby dict has the fields _refresh_display needs.
|
|
lobby["guestAccountId"] = str(d.get("guestAccountId", ""))
|
|
lobby["guestDisplayName"] = str(d.get("guestDisplayName", ""))
|
|
lobby["hasGuest"] = true
|
|
lobby["additionalPlayers"] = d.get("additionalPlayers", [])
|
|
# Apply team assignments from join response if present.
|
|
var raw_st : Variant = d.get("seatTeams", null)
|
|
if raw_st != null:
|
|
seat_teams.clear()
|
|
for k in (raw_st as Dictionary):
|
|
seat_teams[int(k)] = int(raw_st[k])
|
|
lobby["seatTeams"] = seat_teams
|
|
if on_success.is_valid(): on_success.call(d),
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR join ", code, " ", msg)
|
|
if on_error.is_valid(): on_error.call(code, msg))
|
|
|
|
|
|
## Leave or cancel the current lobby.
|
|
func leave(on_done: Callable = Callable()) -> void:
|
|
if lobby_id.is_empty(): return
|
|
Network.request("game.custom.leave",
|
|
{ "lobbyId": lobby_id },
|
|
func(_t: String, _p: Variant) -> void:
|
|
clear_state()
|
|
lobby_left.emit()
|
|
if on_done.is_valid(): on_done.call(),
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR leave ", code, " ", msg)
|
|
if code == "LOBBY_NOT_FOUND":
|
|
# Treat as stale local lobby state and recover UX.
|
|
clear_state()
|
|
lobby_left.emit()
|
|
if on_done.is_valid(): on_done.call())
|
|
|
|
|
|
## Mark the caller as ready with their final deck and first-turn preference.
|
|
func set_ready(deck_id: String, pref: String) -> void:
|
|
my_deck_id = deck_id
|
|
first_turn_pref = pref
|
|
Network.request("game.custom.lobby.ready",
|
|
{ "lobbyId": lobby_id, "deckId": deck_id, "firstTurnPref": pref },
|
|
func(_t: String, p: Variant) -> void:
|
|
var d := p as Dictionary
|
|
var accepted := bool(d.get("isReady", true))
|
|
i_am_ready = accepted
|
|
if not accepted:
|
|
lobby_notice.emit("Lobby is waiting for more players before ready-up."),
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR set_ready ", code, " ", msg))
|
|
|
|
|
|
## Withdraw the caller's ready status.
|
|
func unready() -> void:
|
|
Network.request("game.custom.lobby.unready",
|
|
{ "lobbyId": lobby_id },
|
|
func(_t: String, _p: Variant) -> void:
|
|
i_am_ready = false,
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR unready ", code, " ", msg))
|
|
|
|
|
|
## Change the caller's deck selection (only when not yet ready).
|
|
func change_deck(deck_id: String) -> void:
|
|
my_deck_id = deck_id
|
|
Network.request("game.custom.lobby.change_deck",
|
|
{ "lobbyId": lobby_id, "deckId": deck_id },
|
|
func(_t: String, _p: Variant) -> void: pass,
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR change_deck ", code, " ", msg))
|
|
|
|
|
|
## Host-only: update lobby rule overrides (open or full lobby, neither player ready).
|
|
func update_rules(rules_override: Dictionary) -> void:
|
|
Network.request("game.custom.update_rules",
|
|
{ "lobbyId": lobby_id, "rules": rules_override },
|
|
func(_t: String, p: Variant) -> void:
|
|
# Apply new rules immediately from the ACK (don't wait for the push).
|
|
var d := p as Dictionary
|
|
var rules := d.get("rules", {}) as Dictionary
|
|
if not rules.is_empty():
|
|
lobby["rules"] = rules # keep lobby dict current for _refresh_display
|
|
lobby_rules_updated.emit(rules),
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR update_rules ", code, " ", msg))
|
|
|
|
|
|
## Save the current lobby's rules as a named preset.
|
|
func save_preset(preset_name: String) -> void:
|
|
Network.request("game.custom.preset.save",
|
|
{ "lobbyId": lobby_id, "presetName": preset_name },
|
|
func(_t: String, _p: Variant) -> void: pass,
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR save_preset ", code, " ", msg))
|
|
|
|
|
|
## List all presets owned by the local player.
|
|
func list_presets(callback: Callable) -> void:
|
|
Network.request("game.custom.preset.list", {},
|
|
func(_t: String, p: Variant) -> void:
|
|
var d := p as Dictionary
|
|
callback.call(d.get("presets", [])),
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR list_presets ", code, " ", msg))
|
|
|
|
|
|
## Host proposes loading a preset; triggers a yes/no vote for the guest.
|
|
func propose_preset(preset_id: String) -> void:
|
|
Network.request("game.custom.preset.propose",
|
|
{ "lobbyId": lobby_id, "presetId": preset_id },
|
|
func(_t: String, _p: Variant) -> void: pass,
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR propose_preset ", code, " ", msg))
|
|
|
|
|
|
## Cast a yes/no vote on the active preset proposal.
|
|
func vote_preset(accept: bool) -> void:
|
|
Network.request("game.custom.preset.vote",
|
|
{ "lobbyId": lobby_id, "accept": accept },
|
|
func(_t: String, _p: Variant) -> void: pass,
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR vote_preset ", code, " ", msg))
|
|
|
|
|
|
## Guest-only: propose rule overrides to the host. rules_override is a camelCase dict
|
|
## of nullable fields (omit or null = keep server default).
|
|
func suggest_rules(rules_override: Dictionary) -> void:
|
|
Network.request("game.custom.suggest_rules",
|
|
{ "lobbyId": lobby_id, "rules": rules_override },
|
|
func(_t: String, _p: Variant) -> void: pass,
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR suggest_rules ", code, " ", msg))
|
|
|
|
|
|
## Host-only: accept the guest's pending rule suggestion and apply it.
|
|
func accept_rule_suggestion() -> void:
|
|
Network.request("game.custom.suggest_rules.accept",
|
|
{ "lobbyId": lobby_id },
|
|
func(_t: String, _p: Variant) -> void: pass,
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR accept_rule_suggestion ", code, " ", msg))
|
|
|
|
|
|
## Host-only: reject the guest's pending rule suggestion.
|
|
func reject_rule_suggestion() -> void:
|
|
Network.request("game.custom.suggest_rules.reject",
|
|
{ "lobbyId": lobby_id },
|
|
func(_t: String, _p: Variant) -> void: pass,
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR reject_rule_suggestion ", code, " ", msg))
|
|
|
|
|
|
## Host-only: reassign a player seat to a different team.
|
|
func reassign_team(seat_index: int, team_index: int) -> void:
|
|
Network.request("game.custom.reassign_team",
|
|
{ "lobbyId": lobby_id, "seatIndex": seat_index, "teamIndex": team_index },
|
|
func(_t: String, p: Variant) -> void:
|
|
var d := p as Dictionary
|
|
var raw := d.get("seatTeams", {}) as Dictionary
|
|
seat_teams.clear()
|
|
for k in raw:
|
|
seat_teams[int(k)] = int(raw[k])
|
|
lobby["seatTeams"] = seat_teams
|
|
team_assignment_changed.emit(seat_teams),
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR reassign_team ", code, " ", msg))
|
|
|
|
|
|
## Host-only: add an AI player to the current open lobby.
|
|
## difficulty is 1-10, strategy is one of: Aggressive, Control, Balanced, Ramp, Swarm.
|
|
func add_ai(difficulty: int, strategy: String,
|
|
on_success: Callable = Callable(),
|
|
on_error: Callable = Callable()) -> void:
|
|
Network.request("game.ai.add",
|
|
{ "lobbyId": lobby_id, "difficulty": difficulty, "strategy": strategy },
|
|
func(_t: String, p: Variant) -> void:
|
|
var d := p as Dictionary
|
|
# Update ai_slots immediately from the ACK so the display
|
|
# reflects the new AI before the push arrives.
|
|
var seat := int(d.get("seatIndex", 1))
|
|
ai_slots = ai_slots.filter(func(s: Dictionary) -> bool:
|
|
return int(s.get("seatIndex", -1)) != seat)
|
|
ai_slots.append({
|
|
"accountId": str(d.get("aiAccountId", "")),
|
|
"displayName": str(d.get("aiDisplayName", "AI")),
|
|
"difficulty": difficulty,
|
|
"strategy": strategy,
|
|
"seatIndex": seat,
|
|
})
|
|
ai_slots_changed.emit(ai_slots)
|
|
if on_success.is_valid(): on_success.call(d),
|
|
func(code: String, msg: String) -> void:
|
|
print("[CustomLobby] ERR add_ai ", code, " ", msg)
|
|
if on_error.is_valid(): on_error.call(code, msg))
|
|
|
|
|
|
# ── Private ───────────────────────────────────────────────────────────────────
|
|
|
|
func _on_server_push(type: String, payload: Variant) -> void:
|
|
if type.begins_with("game.custom.lobby"):
|
|
print("[CustomLobby] PUSH ", type, " ", JSON.stringify(payload).substr(0, 200))
|
|
match type:
|
|
"game.custom.lobby.guest_joined":
|
|
var d := payload as Dictionary
|
|
var gid : String = str(d.get("guestAccountId", ""))
|
|
var gname: String = str(d.get("guestDisplayName", gid.substr(0, 8)))
|
|
# Keep local lobby snapshot current so LobbyRoomScreen can render seat updates.
|
|
if d.has("additionalPlayers"):
|
|
lobby["additionalPlayers"] = d.get("additionalPlayers", [])
|
|
if str(lobby.get("guestAccountId", "")).is_empty():
|
|
lobby["guestAccountId"] = gid
|
|
lobby["guestDisplayName"] = gname
|
|
lobby["hasGuest"] = true
|
|
guest_joined.emit(gid, gname)
|
|
|
|
"game.custom.lobby_updated":
|
|
var d := payload as Dictionary
|
|
var rules := d.get("newRules", {}) as Dictionary
|
|
if not rules.is_empty():
|
|
lobby["rules"] = rules # keep lobby dict current for _refresh_display
|
|
lobby_rules_updated.emit(rules)
|
|
|
|
"game.custom.lobby.deck_changed":
|
|
var d := payload as Dictionary
|
|
var aid := str(d.get("accountId", ""))
|
|
var did := str(d.get("deckId", ""))
|
|
lobby_deck_changed.emit(aid, did)
|
|
|
|
"game.custom.lobby.ready_status":
|
|
var d := payload as Dictionary
|
|
var hr : bool = d.get("hostReady", false)
|
|
var gr : bool = d.get("guestReady", false)
|
|
if d.has("additionalPlayers"):
|
|
lobby["additionalPlayers"] = d.get("additionalPlayers", [])
|
|
if is_host:
|
|
i_am_ready = hr
|
|
partner_ready = gr
|
|
elif is_additional:
|
|
# Additional players (3rd+) resolve self-ready and overall partner readiness
|
|
# from the full participant snapshot when present.
|
|
var others_ready := hr and gr
|
|
if d.has("additionalPlayers"):
|
|
for ap: Dictionary in (d.get("additionalPlayers", []) as Array):
|
|
var aid := str(ap.get("accountId", ""))
|
|
var ardy := bool(ap.get("isReady", false))
|
|
if aid == Auth.user_id:
|
|
i_am_ready = ardy
|
|
else:
|
|
others_ready = others_ready and ardy
|
|
partner_ready = others_ready
|
|
else:
|
|
# First guest
|
|
i_am_ready = gr
|
|
partner_ready = hr
|
|
ready_status_changed.emit(hr, gr)
|
|
|
|
"game.custom.started":
|
|
var d := payload as Dictionary
|
|
var sid : String = str(d.get("sessionId", ""))
|
|
var opp : String = str(d.get("opponentAccountId", ""))
|
|
var oname : String = str(d.get("opponentDisplayName", opp.substr(0, 8)))
|
|
Game.session_id = sid
|
|
Game.opponent_name = oname
|
|
Game.state = {}
|
|
clear_state()
|
|
game_starting.emit(sid, opp, oname)
|
|
|
|
"game.custom.preset.vote_requested":
|
|
preset_vote_requested.emit(payload as Dictionary)
|
|
|
|
"game.custom.preset.vote_rejected":
|
|
var d := payload as Dictionary
|
|
var lid := str(d.get("lobbyId", ""))
|
|
var pid := str(d.get("presetId", ""))
|
|
preset_vote_rejected.emit(lid, pid)
|
|
|
|
"game.custom.lobby.partner_left":
|
|
var d := payload as Dictionary
|
|
var reason : String = str(d.get("reason", ""))
|
|
clear_state()
|
|
partner_left.emit(reason)
|
|
|
|
"game.custom.lobby.rule_suggestion":
|
|
var d := payload as Dictionary
|
|
var rules := d.get("suggestedRules", {}) as Dictionary
|
|
rule_suggestion_received.emit(rules)
|
|
|
|
"game.custom.lobby.rule_suggestion.rejected":
|
|
rule_suggestion_rejected.emit()
|
|
|
|
"game.ai.slots_changed":
|
|
var d := payload as Dictionary
|
|
ai_slots = d.get("currentAiSlots", []) as Array
|
|
ai_slots_changed.emit(ai_slots)
|
|
|
|
"game.custom.lobby.team_reassigned":
|
|
var d := payload as Dictionary
|
|
var raw := d.get("seatTeams", {}) as Dictionary
|
|
seat_teams.clear()
|
|
for k in raw:
|
|
seat_teams[int(k)] = int(raw[k])
|
|
lobby["seatTeams"] = seat_teams
|
|
team_assignment_changed.emit(seat_teams)
|