Fix AI opponents in FreePlay 3+ player lobbies

- 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>
This commit is contained in:
dingo
2026-05-26 16:51:01 -04:00
co-authored by Claude Happy
parent 32693d303b
commit dfccd091fd
5 changed files with 137 additions and 75 deletions
@@ -51,6 +51,7 @@ const RULES_DIALOG = preload("res://scenes/free_play/components/RulesEditorDialo
var _first_turn_pref : String = "random"
var _current_rules : Dictionary = {}
var _team_panel : VBoxContainer = null # dynamically added team-controls section
var _ai_adding : bool = false # guard against concurrent add-AI requests
# ── Lifecycle ─────────────────────────────────────────────────────────────────
@@ -172,10 +173,11 @@ func _refresh_display() -> void:
host_name_label.text = "Host: %s%s" % [str(lobby.get("hostDisplayName", Auth.display_name)), team_suffix_0]
host_deck_label.text = "Deck: (selected)"
# Guest slot — may be a human, an AI, or empty
# Guest slot — may be a human, an AI (2-player only), or empty.
# For 3+ player games the seat-1 AI is an additional player shown in the panel below.
var team_suffix_1 : String = _team_label(game_mode, 1, team_count)
var has_guest : bool = lobby.get("hasGuest", false) or lobby.get("guestAccountId", "") != ""
var ai_in_guest_slot : Dictionary = _ai_slot_for_seat(1)
var ai_in_guest_slot : Dictionary = _ai_slot_for_seat(1) if max_players == 2 else {}
if not ai_in_guest_slot.is_empty():
guest_name_label.text = "AI: %s%s" % [str(ai_in_guest_slot.get("displayName", "AI")), team_suffix_1]
guest_deck_label.text = "Difficulty %d" % int(ai_in_guest_slot.get("difficulty", 1))
@@ -188,10 +190,11 @@ func _refresh_display() -> void:
guest_name_label.text = "Waiting for guest…"
guest_deck_label.text = ""
# Show Add AI button only for host when guest slot is truly empty (max 2 players)
# and neither player is ready
# Show Add AI Opponent button only for 2-player lobbies (guest slot).
# 3+ player lobbies use per-seat Add AI buttons in the additional players panel.
var slot_open : bool = (not has_guest and ai_in_guest_slot.is_empty() and max_players == 2)
add_ai_btn.visible = CustomLobby.is_host and slot_open and not CustomLobby.i_am_ready
add_ai_btn.disabled = _ai_adding
# Additional players (3+) from lobby dict.
_rebuild_additional_players_panel(lobby, max_players)
@@ -212,7 +215,9 @@ func _refresh_display() -> void:
_update_rules_label()
## Rebuild the additional players panel (seats 3+) from the lobby dict.
## Rebuild the additional players panel (seats 2+) from the lobby dict.
## For 3+ player lobbies this covers ALL non-host seats (seats 1–N when no guest is present,
## seats 2–N when a human guest occupies seat 1).
func _rebuild_additional_players_panel(lobby: Dictionary, max_players: int) -> void:
for c in additional_players_container.get_children():
c.queue_free()
@@ -221,32 +226,40 @@ func _rebuild_additional_players_panel(lobby: Dictionary, max_players: int) -> v
additional_players_container.visible = false
return
var gm : String = str(lobby.get("gameMode", "FFA"))
var tc : int = int(lobby.get("teamCount", 1))
var gm : String = str(lobby.get("gameMode", "FFA"))
var tc : int = int(lobby.get("teamCount", 1))
# The lobby dict may contain additionalPlayers array (from server push or join response).
var addl : Array = lobby.get("additionalPlayers", []) as Array
if addl.is_empty():
# Show empty slots for players who haven't joined yet.
# Host always occupies slot 1; guest slot 2 if guestAccountId is present.
var has_host : bool = true # host is always present
var has_guest : bool = lobby.get("hasGuest", false) or str(lobby.get("guestAccountId", "")) != ""
var taken_slots : int = (1 if has_host else 0) + (1 if has_guest else 0)
for i in range(max_players - taken_slots):
var seat_n : int = taken_slots + i
var tsuf : String = _team_label(gm, seat_n, tc)
var row := _make_player_slot_row("Seat %d: Waiting…%s" % [seat_n + 1, tsuf], false)
# Build a seat-index → addl-player dict for O(1) lookup.
var addl_by_seat : Dictionary = {}
for ap: Dictionary in (lobby.get("additionalPlayers", []) as Array):
var si : int = int(ap.get("seatIndex", -1))
if si >= 0:
addl_by_seat[si] = ap
# First additional seat depends on whether a human occupies the guest slot (seat 1).
var has_guest2 : bool = lobby.get("hasGuest", false) or str(lobby.get("guestAccountId", "")) != ""
var first_addl : int = 2 if has_guest2 else 1
for seat_n in range(first_addl, max_players):
var tsuf : String = _team_label(gm, seat_n, tc)
var ai_slot : Dictionary = _ai_slot_for_seat(seat_n)
if not ai_slot.is_empty():
# AI occupies this seat.
var row := _make_player_slot_row(
"AI: %s%s" % [str(ai_slot.get("displayName", "AI")), tsuf], true)
additional_players_container.add_child(row)
else:
for i2: int in addl.size():
var entry : Dictionary = addl[i2] as Dictionary
elif addl_by_seat.has(seat_n):
# Human player occupies this seat.
var entry : Dictionary = addl_by_seat[seat_n] as Dictionary
var aid : String = str(entry.get("accountId", ""))
var aname : String = str(entry.get("displayName", str(entry.get("accountId", "Player")).substr(0, 8)))
var ready : bool = bool(entry.get("isReady", false))
var seat_n2 : int = i2 + 2
var tsuf2 : String = _team_label(gm, seat_n2, tc)
var who := "You" if aid == Auth.user_id else aname
var row := _make_player_slot_row("Player: %s%s" % [who, tsuf2], ready)
var who : String = "You" if aid == Auth.user_id else aname
var row := _make_player_slot_row("Player: %s%s" % [who, tsuf], ready)
additional_players_container.add_child(row)
else:
# Seat is empty — show waiting row with Add AI button for the host.
var row := _make_additional_seat_row("Seat %d: Waiting…%s" % [seat_n + 1, tsuf])
additional_players_container.add_child(row)
additional_players_container.visible = true
@@ -279,6 +292,24 @@ func _make_player_slot_row(label_text: String, is_ready: bool) -> HBoxContainer:
return hbox
func _make_additional_seat_row(label_text: String) -> HBoxContainer:
var hbox := HBoxContainer.new()
hbox.add_theme_constant_override("separation", 8)
var name_lbl := Label.new()
name_lbl.text = label_text
name_lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL
name_lbl.add_theme_font_size_override("font_size", 13)
hbox.add_child(name_lbl)
if CustomLobby.is_host and not CustomLobby.i_am_ready:
var ai_btn := Button.new()
ai_btn.text = "Add AI"
ai_btn.custom_minimum_size = Vector2(70, 0)
ai_btn.disabled = _ai_adding
ai_btn.pressed.connect(_on_add_ai_pressed)
hbox.add_child(ai_btn)
return hbox
## Rebuild the host-only team assignment panel (shown only in team game modes).
## Each row: "[Seat N: <name>] [<] T0 [>]"
func _rebuild_team_controls(lobby: Dictionary, max_players: int,
@@ -543,6 +574,8 @@ func _on_ai_slots_changed(_slots: Array) -> void:
func _on_add_ai_pressed() -> void:
if _ai_adding:
return
var dlg := AcceptDialog.new()
dlg.title = "Add AI Opponent"
dlg.ok_button_text = "Add"
@@ -580,14 +613,16 @@ func _on_add_ai_pressed() -> void:
dlg.confirmed.connect(func():
var difficulty := diff_opts.selected + 1 # 1-indexed
var strategy :Variant = strategies[strat_opts.selected]
add_ai_btn.disabled = true
var strategy : Variant = strategies[strat_opts.selected]
_ai_adding = true
_refresh_display()
CustomLobby.add_ai(difficulty, strategy,
func(_d: Dictionary) -> void:
add_ai_btn.disabled = false
_ai_adding = false
_refresh_display(),
func(_code: String, _msg: String) -> void:
add_ai_btn.disabled = false
_ai_adding = false
_refresh_display()
_show_toast("Failed to add AI: " + _msg))
dlg.queue_free())
dlg.canceled.connect(func(): dlg.queue_free())
@@ -29,14 +29,14 @@ func valid_play_tiles(card: Dictionary, tile_bodies: Dictionary) -> Array:
return results
var ax: int = arch_pos.get("x", 0)
var ay: int = arch_pos.get("y", 0)
# Channel range is a property of the ArchSpirit.
# Channel range is validated by the server from the Spirit card being played.
# dict.get(key, default) only uses the default when the key is ABSENT.
# The server sends nullable ints (e.g. "minChannelRange": null), so the
# key EXISTS but its value is null — GDScript returns null, which silently
# coerces to 0 on a typed int variable, collapsing the range to nothing.
# Read as Variant first, then substitute the default explicitly.
var raw_min: Variant = arch.get("minChannelRange")
var raw_max: Variant = arch.get("maxChannelRange")
var raw_min: Variant = card.get("minChannelRange")
var raw_max: Variant = card.get("maxChannelRange")
var min_r: int = 1 if raw_min == null else int(raw_min)
var max_r: int = 1 if raw_max == null else int(raw_max)
var card_affinity: String = card.get("affinity", "")
@@ -50,7 +50,7 @@ func valid_play_tiles(card: Dictionary, tile_bodies: Dictionary) -> Array:
var tile: Dictionary = Game.get_tile(tx, ty)
print("tile", tile)
print("[GettingAff]", card_affinity)
if not unit_registry.tile_has_blocking_occupant(tile):
if unit_registry.tile_has_blocking_occupant(tile):
continue
if card_affinity != "" and not tile_matches_channel_affinity(tile, card_affinity):
continue
@@ -77,7 +77,7 @@ func is_ruin_instance(iid: String) -> bool:
## Returns true when the tile has an occupant that blocks movement (i.e. not a Ruin).
func tile_has_blocking_occupant(tile: Dictionary) -> bool:
var occupant_id: String = str(tile.get("occupantId", ""))
if occupant_id.is_empty() or occupant_id == "null":
if occupant_id.is_empty() or occupant_id == "<null>" or occupant_id == "null":
print("[TileBlock] failing out")
return false
print("[TileBlock] returning this: ", not is_ruin_instance(occupant_id))