From d61ebe66b84057aa8908a5b78bef8fbdd0beff03 Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 19 Mar 2026 09:10:55 -0400 Subject: [PATCH] Phase 8: Free Play ready-up system + client scenes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Co-Authored-By: Happy --- Client/origin-client/autoloads/CustomLobby.gd | 255 +++++++++++ Client/origin-client/autoloads/Game.gd | 25 ++ Client/origin-client/project.godot | 1 + .../scenes/free_play/FreePlayScreen.tscn | 237 ++++++++++ .../scenes/free_play/LobbyRoomScreen.tscn | 307 +++++++++++++ .../scenes/free_play/free_play_screen.gd | 299 +++++++++++++ .../scenes/free_play/lobby_room_screen.gd | 324 ++++++++++++++ .../origin-client/scenes/game/game_screen.gd | 48 +- .../origin-client/scenes/main/MainScreen.tscn | 7 + .../origin-client/scenes/main/main_screen.gd | 4 + .../SOR.Database/Entities/Game/CustomLobby.cs | 17 + ...0260319125847_AddReadyUpSystem.Designer.cs | 417 ++++++++++++++++++ .../Game/20260319125847_AddReadyUpSystem.cs | 81 ++++ .../Game/GameDbContextModelSnapshot.cs | 15 + Server/src/SOR.Game/GameMessages.cs | 57 ++- .../Handlers/GameChangeLobbyDeckHandler.cs | 75 ++++ .../Handlers/GameJoinCustomLobbyHandler.cs | 102 +---- .../Handlers/GameListActiveLobbiesHandler.cs | 105 +++++ .../Handlers/GameListCustomLobbiesHandler.cs | 42 +- .../Handlers/GameLobbyReadyHandler.cs | 186 ++++++++ .../SOR.Game/Handlers/GameUnreadyHandler.cs | 66 +++ .../Handlers/GameUpdateLobbyRulesHandler.cs | 107 +++++ Server/src/SOR.Game/ServiceRegistration.cs | 7 + 23 files changed, 2685 insertions(+), 99 deletions(-) create mode 100644 Client/origin-client/autoloads/CustomLobby.gd create mode 100644 Client/origin-client/scenes/free_play/FreePlayScreen.tscn create mode 100644 Client/origin-client/scenes/free_play/LobbyRoomScreen.tscn create mode 100644 Client/origin-client/scenes/free_play/free_play_screen.gd create mode 100644 Client/origin-client/scenes/free_play/lobby_room_screen.gd create mode 100644 Server/src/SOR.Database/Migrations/Game/20260319125847_AddReadyUpSystem.Designer.cs create mode 100644 Server/src/SOR.Database/Migrations/Game/20260319125847_AddReadyUpSystem.cs create mode 100644 Server/src/SOR.Game/Handlers/GameChangeLobbyDeckHandler.cs create mode 100644 Server/src/SOR.Game/Handlers/GameListActiveLobbiesHandler.cs create mode 100644 Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs create mode 100644 Server/src/SOR.Game/Handlers/GameUnreadyHandler.cs create mode 100644 Server/src/SOR.Game/Handlers/GameUpdateLobbyRulesHandler.cs diff --git a/Client/origin-client/autoloads/CustomLobby.gd b/Client/origin-client/autoloads/CustomLobby.gd new file mode 100644 index 0000000..4c801ef --- /dev/null +++ b/Client/origin-client/autoloads/CustomLobby.gd @@ -0,0 +1,255 @@ +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) + +## 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) + +## 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 + +# ── State ───────────────────────────────────────────────────────────────────── + +var lobby_id : String = "" +var lobby : Dictionary = {} +var my_deck_id : String = "" +var is_host : bool = false +var i_am_ready : bool = false +var partner_ready : bool = false +var first_turn_pref: String = "random" + +# ── 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 + i_am_ready = false + partner_ready = false + first_turn_pref = "random" + +# ── 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, on_success: Callable = Callable(), + on_error: Callable = Callable()) -> void: + my_deck_id = deck_id + var payload := { + "lobbyName": lobby_name, + "deckId": deck_id, + } + 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 + 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: + 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 + 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)) + + +## 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: + i_am_ready = true, + 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 (only when neither player is 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: pass, + 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)) + +# ── 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", "")) + guest_joined.emit(gid) + + "game.custom.lobby_updated": + var d := payload as Dictionary + var rules := d.get("newRules", {}) as Dictionary + 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 is_host: + i_am_ready = hr + partner_ready = gr + else: + 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", "")) + Game.session_id = sid + Game.state = {} + game_starting.emit(sid, opp) + + "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) diff --git a/Client/origin-client/autoloads/Game.gd b/Client/origin-client/autoloads/Game.gd index 87d3294..a0dde20 100644 --- a/Client/origin-client/autoloads/Game.gd +++ b/Client/origin-client/autoloads/Game.gd @@ -38,6 +38,7 @@ signal inactive_warning(session_id: String) var session_id : String = "" var state : Dictionary = {} var opponent_name : String = "" +var is_spectating : bool = false # ── Lifecycle ───────────────────────────────────────────────────────────────── @@ -50,6 +51,30 @@ 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 ──────────────────────────────────────────────────────────── diff --git a/Client/origin-client/project.godot b/Client/origin-client/project.godot index 0e952aa..622ea2c 100644 --- a/Client/origin-client/project.godot +++ b/Client/origin-client/project.godot @@ -24,6 +24,7 @@ CollectionCache="*res://autoloads/CollectionCache.gd" Chat="*res://autoloads/Chat.gd" Settings="*res://autoloads/Settings.gd" Game="*res://autoloads/Game.gd" +CustomLobby="*res://autoloads/CustomLobby.gd" ModelCache="*res://autoloads/ModelCache.gd" Music="*res://autoloads/Music.gd" SFX="*res://autoloads/SFX.gd" diff --git a/Client/origin-client/scenes/free_play/FreePlayScreen.tscn b/Client/origin-client/scenes/free_play/FreePlayScreen.tscn new file mode 100644 index 0000000..474a719 --- /dev/null +++ b/Client/origin-client/scenes/free_play/FreePlayScreen.tscn @@ -0,0 +1,237 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://scenes/free_play/free_play_screen.gd" id="1_fps"] + +[node name="FreePlayScreen" type="Control"] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +script = ExtResource("1_fps") + +[node name="Background" type="ColorRect" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +color = Color(0.094, 0.094, 0.137, 1.0) + +[node name="Layout" type="VBoxContainer" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +theme_override_constants/separation = 0 + +[node name="Header" type="HBoxContainer" parent="Layout"] +layout_mode = 2 +custom_minimum_size = Vector2(0, 56) +theme_override_constants/separation = 12 + +[node name="HeaderMargin" type="MarginContainer" parent="Layout/Header"] +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/margin_left = 16 +theme_override_constants/margin_right = 16 + +[node name="HeaderInner" type="HBoxContainer" parent="Layout/Header/HeaderMargin"] +layout_mode = 2 +size_flags_horizontal = 3 + +[node name="BackBtn" type="Button" parent="Layout/Header/HeaderMargin/HeaderInner"] +layout_mode = 2 +text = "← Back" +theme_override_font_sizes/font_size = 14 + +[node name="TitleLabel" type="Label" parent="Layout/Header/HeaderMargin/HeaderInner"] +layout_mode = 2 +size_flags_horizontal = 3 +text = "FREE PLAY" +horizontal_alignment = 1 +theme_override_font_sizes/font_size = 20 + +[node name="HeaderSpacer" type="Control" parent="Layout/Header/HeaderMargin/HeaderInner"] +layout_mode = 2 +custom_minimum_size = Vector2(70, 0) + +[node name="Separator" type="HSeparator" parent="Layout"] +layout_mode = 2 + +[node name="TabBar" type="HBoxContainer" parent="Layout"] +layout_mode = 2 +custom_minimum_size = Vector2(0, 44) +theme_override_constants/separation = 0 + +[node name="TabMargin" type="MarginContainer" parent="Layout/TabBar"] +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/margin_left = 12 +theme_override_constants/margin_right = 12 + +[node name="TabInner" type="HBoxContainer" parent="Layout/TabBar/TabMargin"] +layout_mode = 2 +size_flags_horizontal = 3 + +[node name="OpenTabBtn" type="Button" parent="Layout/TabBar/TabMargin/TabInner"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +text = "Open Lobbies" +theme_override_font_sizes/font_size = 14 + +[node name="ActiveTabBtn" type="Button" parent="Layout/TabBar/TabMargin/TabInner"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +text = "Active Games" +theme_override_font_sizes/font_size = 14 + +[node name="TabRightSpacer" type="Control" parent="Layout/TabBar/TabMargin/TabInner"] +layout_mode = 2 +size_flags_horizontal = 3 + +[node name="CreateBtn" type="Button" parent="Layout/TabBar/TabMargin/TabInner"] +unique_name_in_owner = true +layout_mode = 2 +custom_minimum_size = Vector2(100, 0) +text = "+ Create" +theme_override_font_sizes/font_size = 14 + +[node name="FilterBar" type="HBoxContainer" parent="Layout"] +layout_mode = 2 +custom_minimum_size = Vector2(0, 40) +theme_override_constants/separation = 8 + +[node name="FilterMargin" type="MarginContainer" parent="Layout/FilterBar"] +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/margin_left = 12 +theme_override_constants/margin_right = 12 + +[node name="FilterInner" type="HBoxContainer" parent="Layout/FilterBar/FilterMargin"] +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/separation = 8 + +[node name="SearchField" type="LineEdit" parent="Layout/FilterBar/FilterMargin/FilterInner"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +placeholder_text = "Search by name…" + +[node name="PasswordToggle" type="CheckBox" parent="Layout/FilterBar/FilterMargin/FilterInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "Show password-protected" +button_pressed = true + +[node name="RefreshBtn" type="Button" parent="Layout/FilterBar/FilterMargin/FilterInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "Refresh" + +[node name="Scroll" type="ScrollContainer" parent="Layout"] +layout_mode = 2 +size_flags_vertical = 3 + +[node name="ScrollContent" type="VBoxContainer" parent="Layout/Scroll"] +layout_mode = 2 +size_flags_horizontal = 3 + +[node name="ScrollMargin" type="MarginContainer" parent="Layout/Scroll/ScrollContent"] +layout_mode = 2 +theme_override_constants/margin_left = 12 +theme_override_constants/margin_right = 12 +theme_override_constants/margin_top = 8 +theme_override_constants/margin_bottom = 8 + +[node name="LobbyListContainer" type="VBoxContainer" parent="Layout/Scroll/ScrollContent/ScrollMargin"] +unique_name_in_owner = true +layout_mode = 2 +theme_override_constants/separation = 4 + +[node name="ActiveListContainer" type="VBoxContainer" parent="Layout/Scroll/ScrollContent/ScrollMargin"] +unique_name_in_owner = true +layout_mode = 2 +theme_override_constants/separation = 4 +visible = false + +[node name="CreateDialog" type="AcceptDialog" parent="."] +unique_name_in_owner = true +visible = false +title = "Create Lobby" +initial_position = 4 +min_size = Vector2(400, 340) + +[node name="CreateContent" type="VBoxContainer" parent="CreateDialog"] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +theme_override_constants/separation = 10 + +[node name="NameLabel" type="Label" parent="CreateDialog/CreateContent"] +layout_mode = 2 +text = "Lobby Name:" + +[node name="LobbyNameField" type="LineEdit" parent="CreateDialog/CreateContent"] +unique_name_in_owner = true +layout_mode = 2 +placeholder_text = "My Awesome Lobby" + +[node name="PwLabel" type="Label" parent="CreateDialog/CreateContent"] +layout_mode = 2 +text = "Password (optional):" + +[node name="LobbyPasswordField" type="LineEdit" parent="CreateDialog/CreateContent"] +unique_name_in_owner = true +layout_mode = 2 +placeholder_text = "Leave blank for public" +secret = true + +[node name="DeckLabel" type="Label" parent="CreateDialog/CreateContent"] +layout_mode = 2 +text = "Select Deck:" + +[node name="DeckScroll" type="ScrollContainer" parent="CreateDialog/CreateContent"] +layout_mode = 2 +custom_minimum_size = Vector2(0, 100) + +[node name="DeckSelectContainer" type="VBoxContainer" parent="CreateDialog/CreateContent/DeckScroll"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/separation = 4 + +[node name="JoinPasswordDialog" type="AcceptDialog" parent="."] +unique_name_in_owner = true +visible = false +title = "Password Required" +initial_position = 4 +min_size = Vector2(300, 120) + +[node name="JoinPwContent" type="VBoxContainer" parent="JoinPasswordDialog"] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +theme_override_constants/separation = 8 + +[node name="JoinPwLabel" type="Label" parent="JoinPasswordDialog/JoinPwContent"] +layout_mode = 2 +text = "Enter lobby password:" + +[node name="JoinPasswordField" type="LineEdit" parent="JoinPasswordDialog/JoinPwContent"] +unique_name_in_owner = true +layout_mode = 2 +secret = true diff --git a/Client/origin-client/scenes/free_play/LobbyRoomScreen.tscn b/Client/origin-client/scenes/free_play/LobbyRoomScreen.tscn new file mode 100644 index 0000000..e2b30c9 --- /dev/null +++ b/Client/origin-client/scenes/free_play/LobbyRoomScreen.tscn @@ -0,0 +1,307 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://scenes/free_play/lobby_room_screen.gd" id="1_lrs"] + +[node name="LobbyRoomScreen" type="Control"] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +script = ExtResource("1_lrs") + +[node name="Background" type="ColorRect" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +color = Color(0.094, 0.094, 0.137, 1.0) + +[node name="Layout" type="VBoxContainer" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +theme_override_constants/separation = 0 + +[node name="Header" type="HBoxContainer" parent="Layout"] +layout_mode = 2 +custom_minimum_size = Vector2(0, 56) + +[node name="HeaderMargin" type="MarginContainer" parent="Layout/Header"] +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/margin_left = 16 +theme_override_constants/margin_right = 16 + +[node name="HeaderInner" type="HBoxContainer" parent="Layout/Header/HeaderMargin"] +layout_mode = 2 +size_flags_horizontal = 3 + +[node name="LobbyTitleLabel" type="Label" parent="Layout/Header/HeaderMargin/HeaderInner"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +text = "LOBBY" +theme_override_font_sizes/font_size = 20 + +[node name="LeaveBtn" type="Button" parent="Layout/Header/HeaderMargin/HeaderInner"] +layout_mode = 2 +text = "Leave" +theme_override_font_sizes/font_size = 14 + +[node name="Separator" type="HSeparator" parent="Layout"] +layout_mode = 2 + +[node name="VoteBanner" type="PanelContainer" parent="Layout"] +unique_name_in_owner = true +layout_mode = 2 +visible = false + +[node name="VoteInner" type="HBoxContainer" parent="Layout/VoteBanner"] +layout_mode = 2 +theme_override_constants/separation = 12 + +[node name="VoteLabel" type="Label" parent="Layout/VoteBanner/VoteInner"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +text = "Accept preset?" + +[node name="VoteYesBtn" type="Button" parent="Layout/VoteBanner/VoteInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "Yes" + +[node name="VoteNoBtn" type="Button" parent="Layout/VoteBanner/VoteInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "No" + +[node name="MainSplit" type="HSplitContainer" parent="Layout"] +layout_mode = 2 +size_flags_vertical = 3 +split_offset = 400 + +[node name="LeftPanel" type="ScrollContainer" parent="Layout/MainSplit"] +layout_mode = 2 + +[node name="LeftContent" type="VBoxContainer" parent="Layout/MainSplit/LeftPanel"] +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/separation = 12 + +[node name="LeftMargin" type="MarginContainer" parent="Layout/MainSplit/LeftPanel/LeftContent"] +layout_mode = 2 +theme_override_constants/margin_left = 16 +theme_override_constants/margin_right = 16 +theme_override_constants/margin_top = 16 +theme_override_constants/margin_bottom = 16 + +[node name="LeftInner" type="VBoxContainer" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin"] +layout_mode = 2 +theme_override_constants/separation = 14 + +[node name="HostSection" type="Label" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +layout_mode = 2 +text = "HOST" +modulate = Color(0.6, 0.6, 0.65, 1.0) +theme_override_font_sizes/font_size = 11 + +[node name="HostNameLabel" type="Label" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "Host: …" +theme_override_font_sizes/font_size = 15 + +[node name="HostDeckLabel" type="Label" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "Deck: (none)" +modulate = Color(0.75, 0.75, 0.75, 1.0) + +[node name="HostReadyIndicator" type="Label" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "Not ready" +modulate = Color(0.6, 0.6, 0.6, 1.0) + +[node name="GuestSep" type="HSeparator" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +layout_mode = 2 + +[node name="GuestSection" type="Label" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +layout_mode = 2 +text = "GUEST" +modulate = Color(0.6, 0.6, 0.65, 1.0) +theme_override_font_sizes/font_size = 11 + +[node name="GuestNameLabel" type="Label" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "Waiting for guest…" +theme_override_font_sizes/font_size = 15 + +[node name="GuestDeckLabel" type="Label" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "" +modulate = Color(0.75, 0.75, 0.75, 1.0) + +[node name="GuestReadyIndicator" type="Label" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "Not ready" +modulate = Color(0.6, 0.6, 0.6, 1.0) + +[node name="ActionSep" type="HSeparator" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +layout_mode = 2 + +[node name="ChangeDeckBtn" type="Button" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "Change Deck" + +[node name="FirstTurnSection" type="Label" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +layout_mode = 2 +text = "WHO GOES FIRST?" +modulate = Color(0.6, 0.6, 0.65, 1.0) +theme_override_font_sizes/font_size = 11 + +[node name="FirstTurnBtns" type="HBoxContainer" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +layout_mode = 2 +theme_override_constants/separation = 8 + +[node name="FirstMeBtn" type="Button" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner/FirstTurnBtns"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +text = "Me" +toggle_mode = true + +[node name="FirstOppBtn" type="Button" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner/FirstTurnBtns"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +text = "Opponent" +toggle_mode = true + +[node name="FirstRandomBtn" type="Button" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner/FirstTurnBtns"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +text = "Random" +toggle_mode = true +button_pressed = true + +[node name="ReadyBtn" type="Button" parent="Layout/MainSplit/LeftPanel/LeftContent/LeftMargin/LeftInner"] +unique_name_in_owner = true +layout_mode = 2 +custom_minimum_size = Vector2(0, 52) +text = "✓ Ready" +theme_override_font_sizes/font_size = 16 + +[node name="RightPanel" type="ScrollContainer" parent="Layout/MainSplit"] +layout_mode = 2 + +[node name="RightContent" type="VBoxContainer" parent="Layout/MainSplit/RightPanel"] +layout_mode = 2 +size_flags_horizontal = 3 + +[node name="RightMargin" type="MarginContainer" parent="Layout/MainSplit/RightPanel/RightContent"] +layout_mode = 2 +theme_override_constants/margin_left = 16 +theme_override_constants/margin_right = 16 +theme_override_constants/margin_top = 16 +theme_override_constants/margin_bottom = 16 + +[node name="RightInner" type="VBoxContainer" parent="Layout/MainSplit/RightPanel/RightContent/RightMargin"] +layout_mode = 2 +theme_override_constants/separation = 12 + +[node name="RulesTitle" type="Label" parent="Layout/MainSplit/RightPanel/RightContent/RightMargin/RightInner"] +layout_mode = 2 +text = "RULES" +modulate = Color(0.6, 0.6, 0.65, 1.0) +theme_override_font_sizes/font_size = 11 + +[node name="RulesLabel" type="Label" parent="Layout/MainSplit/RightPanel/RightContent/RightMargin/RightInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "(default rules)" +modulate = Color(0.85, 0.85, 0.85, 1.0) +autowrap_mode = 3 + +[node name="EditRulesBtn" type="Button" parent="Layout/MainSplit/RightPanel/RightContent/RightMargin/RightInner"] +unique_name_in_owner = true +layout_mode = 2 +text = "Edit Rules" + +[node name="PresetSep" type="HSeparator" parent="Layout/MainSplit/RightPanel/RightContent/RightMargin/RightInner"] +layout_mode = 2 + +[node name="PresetsTitle" type="Label" parent="Layout/MainSplit/RightPanel/RightContent/RightMargin/RightInner"] +layout_mode = 2 +text = "PRESETS" +modulate = Color(0.6, 0.6, 0.65, 1.0) +theme_override_font_sizes/font_size = 11 + +[node name="PresetBtns" type="HBoxContainer" parent="Layout/MainSplit/RightPanel/RightContent/RightMargin/RightInner"] +layout_mode = 2 +theme_override_constants/separation = 8 + +[node name="SavePresetBtn" type="Button" parent="Layout/MainSplit/RightPanel/RightContent/RightMargin/RightInner/PresetBtns"] +unique_name_in_owner = true +layout_mode = 2 +text = "Save Preset" + +[node name="LoadPresetBtn" type="Button" parent="Layout/MainSplit/RightPanel/RightContent/RightMargin/RightInner/PresetBtns"] +unique_name_in_owner = true +layout_mode = 2 +text = "Load Preset" + +[node name="DeckPickerDialog" type="AcceptDialog" parent="."] +unique_name_in_owner = true +visible = false +title = "Choose Deck" +initial_position = 4 +min_size = Vector2(300, 280) + +[node name="DeckPickerScroll" type="ScrollContainer" parent="DeckPickerDialog"] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 + +[node name="DeckPickerContainer" type="VBoxContainer" parent="DeckPickerDialog/DeckPickerScroll"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/separation = 6 + +[node name="PresetListDialog" type="AcceptDialog" parent="."] +unique_name_in_owner = true +visible = false +title = "Load Preset" +initial_position = 4 +min_size = Vector2(300, 280) + +[node name="PresetListScroll" type="ScrollContainer" parent="PresetListDialog"] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 + +[node name="PresetListContainer" type="VBoxContainer" parent="PresetListDialog/PresetListScroll"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/separation = 6 diff --git a/Client/origin-client/scenes/free_play/free_play_screen.gd b/Client/origin-client/scenes/free_play/free_play_screen.gd new file mode 100644 index 0000000..f34221f --- /dev/null +++ b/Client/origin-client/scenes/free_play/free_play_screen.gd @@ -0,0 +1,299 @@ +extends Control +## FreePlayScreen — browse open lobbies, active games, and create new lobbies. +## +## Layout (programmatic): +## VBox +## ├─ Header: "FREE PLAY" + Back button +## ├─ Tab bar: [Open Lobbies] [Active Games] + [+ Create] (right) +## └─ Content area (lobby list / active games list) + +# ── Node refs ───────────────────────────────────────────────────────────────── + +@onready var back_btn : Button = $Layout/Header/HeaderMargin/HeaderInner/BackBtn +@onready var lobby_list_container : VBoxContainer = %LobbyListContainer +@onready var active_list_container : VBoxContainer = %ActiveListContainer +@onready var open_tab_btn : Button = %OpenTabBtn +@onready var active_tab_btn : Button = %ActiveTabBtn +@onready var search_field : LineEdit = %SearchField +@onready var password_toggle : CheckBox = %PasswordToggle +@onready var refresh_btn : Button = %RefreshBtn +@onready var create_btn : Button = %CreateBtn +@onready var create_dialog : AcceptDialog = %CreateDialog +@onready var lobby_name_field : LineEdit = %LobbyNameField +@onready var lobby_password_field : LineEdit = %LobbyPasswordField +@onready var deck_select_container : VBoxContainer = %DeckSelectContainer +@onready var join_password_dialog : AcceptDialog = %JoinPasswordDialog +@onready var join_password_field : LineEdit = %JoinPasswordField + +# ── State ───────────────────────────────────────────────────────────────────── + +var _current_tab : String = "open" # "open" | "active" +var _open_lobbies : Array = [] +var _active_games : Array = [] +var _selected_deck : String = "" +var _pending_join_lobby : Dictionary = {} + +# ── Lifecycle ───────────────────────────────────────────────────────────────── + +func _ready() -> void: + Chat.set_bubble_visible(true) + _setup_ui() + _refresh_lobbies() + + +func _exit_tree() -> void: + Chat.set_bubble_visible(false) + +# ── UI setup ────────────────────────────────────────────────────────────────── + +func _setup_ui() -> void: + back_btn.pressed.connect(func(): + get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn")) + open_tab_btn.pressed.connect(func(): _switch_tab("open")) + active_tab_btn.pressed.connect(func(): _switch_tab("active")) + refresh_btn.pressed.connect(_refresh_lobbies) + search_field.text_changed.connect(func(_t): _refresh_lobbies()) + create_btn.pressed.connect(_show_create_dialog) + + create_dialog.confirmed.connect(_on_create_confirmed) + join_password_dialog.confirmed.connect(_on_join_password_confirmed) + + _switch_tab("open") + _load_decks_for_create() + + +func _switch_tab(tab: String) -> void: + _current_tab = tab + var open_active = tab == "open" + lobby_list_container.visible = open_active + active_list_container.visible = not open_active + open_tab_btn.modulate = Color.WHITE if open_active else Color(0.6, 0.6, 0.6) + active_tab_btn.modulate = Color(0.6, 0.6, 0.6) if open_active else Color.WHITE + _refresh_lobbies() + +# ── Data loading ────────────────────────────────────────────────────────────── + +func _refresh_lobbies() -> void: + if _current_tab == "open": + _load_open_lobbies() + else: + _load_active_games() + + +func _load_open_lobbies() -> void: + var payload := { + "page": 1, + "pageSize": 50, + "nameSearch": search_field.text.strip_edges(), + "showPasswordProtected": password_toggle.button_pressed, + } + Network.request("game.custom.list", payload, + func(_t: String, p: Variant) -> void: + var d := p as Dictionary + _open_lobbies = d.get("lobbies", []) + _populate_open_lobbies(), + func(code: String, msg: String) -> void: + print("[FreePlay] ERR list ", code, " ", msg)) + + +func _load_active_games() -> void: + Network.request("game.custom.list_active", { "page": 1, "pageSize": 50 }, + func(_t: String, p: Variant) -> void: + var d := p as Dictionary + _active_games = d.get("games", []) + _populate_active_games(), + func(code: String, msg: String) -> void: + print("[FreePlay] ERR list_active ", code, " ", msg)) + + +func _load_decks_for_create() -> void: + Network.request("collection.get_decks", {}, + func(_t: String, p: Variant) -> void: + var d := p as Dictionary + var decks : Array = d.get("decks", []) + _populate_deck_buttons(decks), + func(_c: String, _m: String) -> void: pass) + +# ── List population ─────────────────────────────────────────────────────────── + +func _populate_open_lobbies() -> void: + for child in lobby_list_container.get_children(): + child.queue_free() + + if _open_lobbies.is_empty(): + var lbl := Label.new() + lbl.text = "No open lobbies found." + lbl.modulate = Color(0.6, 0.6, 0.6) + lobby_list_container.add_child(lbl) + return + + for lobby in _open_lobbies: + lobby_list_container.add_child(_make_lobby_row(lobby)) + + +func _populate_active_games() -> void: + for child in active_list_container.get_children(): + child.queue_free() + + if _active_games.is_empty(): + var lbl := Label.new() + lbl.text = "No active games right now." + lbl.modulate = Color(0.6, 0.6, 0.6) + active_list_container.add_child(lbl) + return + + for game in _active_games: + active_list_container.add_child(_make_active_game_row(game)) + + +func _make_lobby_row(lobby: Dictionary) -> Control: + var row := HBoxContainer.new() + row.custom_minimum_size = Vector2(0, 48) + + var name_lbl := Label.new() + var has_pw : bool = lobby.get("rules", {}).get("hasPassword", false) + var has_guest : bool = lobby.get("hasGuest", false) + var host_name : String = lobby.get("hostDisplayName", "?") + name_lbl.text = "%s%s — Host: %s [%s]" % [ + "🔒 " if has_pw else "", + lobby.get("lobbyName", "?"), + host_name, + "2/2" if has_guest else "1/2" + ] + name_lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL + name_lbl.clip_text = true + row.add_child(name_lbl) + + var join_btn := Button.new() + join_btn.text = "Join" + join_btn.custom_minimum_size = Vector2(70, 0) + join_btn.pressed.connect(func(): _on_join_pressed(lobby)) + row.add_child(join_btn) + + var sep := HSeparator.new() + var wrapper := VBoxContainer.new() + wrapper.add_child(row) + wrapper.add_child(sep) + return wrapper + + +func _make_active_game_row(game: Dictionary) -> Control: + var row := HBoxContainer.new() + row.custom_minimum_size = Vector2(0, 48) + + var name_lbl := Label.new() + var host_name : String = game.get("hostDisplayName", "?") + var guest_name : String = game.get("guestDisplayName", "?") + var has_pw : bool = game.get("hasPassword", false) + name_lbl.text = "%s%s — %s vs %s" % [ + "🔒 " if has_pw else "", + game.get("lobbyName", "?"), + host_name, guest_name + ] + name_lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL + name_lbl.clip_text = true + row.add_child(name_lbl) + + var spectate_btn := Button.new() + spectate_btn.text = "Spectate" + spectate_btn.custom_minimum_size = Vector2(80, 0) + var session_id : String = str(game.get("gameSessionId", "")) + spectate_btn.pressed.connect(func(): _on_spectate_pressed(session_id)) + row.add_child(spectate_btn) + + var sep := HSeparator.new() + var wrapper := VBoxContainer.new() + wrapper.add_child(row) + wrapper.add_child(sep) + return wrapper + + +func _populate_deck_buttons(decks: Array) -> void: + for child in deck_select_container.get_children(): + child.queue_free() + if decks.is_empty(): + var lbl := Label.new() + lbl.text = "No decks found. Build one in My Collection first." + lbl.modulate = Color(0.7, 0.7, 0.7) + deck_select_container.add_child(lbl) + return + for deck in decks: + var btn := Button.new() + var did : String = str(deck.get("id", "")) + var name : String = str(deck.get("name", "Unnamed Deck")) + btn.text = name + btn.toggle_mode = true + btn.button_group = _get_or_create_deck_group() + btn.pressed.connect(func(): _selected_deck = did) + deck_select_container.add_child(btn) + +# ── Deck button group helper ────────────────────────────────────────────────── + +var _deck_btn_group : ButtonGroup = null + +func _get_or_create_deck_group() -> ButtonGroup: + if _deck_btn_group == null: + _deck_btn_group = ButtonGroup.new() + return _deck_btn_group + +# ── Action handlers ─────────────────────────────────────────────────────────── + +func _on_join_pressed(lobby: Dictionary) -> void: + var has_pw : bool = lobby.get("rules", {}).get("hasPassword", false) + _pending_join_lobby = lobby + if has_pw: + join_password_field.text = "" + join_password_dialog.popup_centered() + else: + _do_join(lobby, "") + + +func _on_join_password_confirmed() -> void: + _do_join(_pending_join_lobby, join_password_field.text.strip_edges()) + + +func _do_join(lobby: Dictionary, password: String) -> void: + var lid : String = str(lobby.get("lobbyId", "")) + if _selected_deck.is_empty(): + _selected_deck = _get_first_deck_id() + CustomLobby.join(lid, _selected_deck, password, + func(_p: Variant) -> void: + get_tree().change_scene_to_file("res://scenes/free_play/LobbyRoomScreen.tscn"), + func(code: String, msg: String) -> void: + OS.alert("Could not join lobby: %s — %s" % [code, msg], "Join Failed")) + + +func _on_spectate_pressed(session_id: String) -> void: + Game.start_spectating(session_id) + get_tree().change_scene_to_file("res://scenes/game/GameScreen.tscn") + + +func _show_create_dialog() -> void: + lobby_name_field.text = "" + lobby_password_field.text = "" + if _selected_deck.is_empty(): + _selected_deck = _get_first_deck_id() + create_dialog.popup_centered() + + +func _on_create_confirmed() -> void: + var name_text := lobby_name_field.text.strip_edges() + if name_text.is_empty(): + OS.alert("Please enter a lobby name.", "Missing Name") + return + if _selected_deck.is_empty(): + OS.alert("Please select a deck.", "No Deck Selected") + return + var pw := lobby_password_field.text.strip_edges() + CustomLobby.create(name_text, _selected_deck, pw, {}, + func(_p: Variant) -> void: + get_tree().change_scene_to_file("res://scenes/free_play/LobbyRoomScreen.tscn"), + func(code: String, msg: String) -> void: + OS.alert("Could not create lobby: %s — %s" % [code, msg], "Create Failed")) + + +func _get_first_deck_id() -> String: + for child in deck_select_container.get_children(): + if child is Button and child.has_method("get_meta"): + return "" + return "" diff --git a/Client/origin-client/scenes/free_play/lobby_room_screen.gd b/Client/origin-client/scenes/free_play/lobby_room_screen.gd new file mode 100644 index 0000000..ca4c695 --- /dev/null +++ b/Client/origin-client/scenes/free_play/lobby_room_screen.gd @@ -0,0 +1,324 @@ +extends Control +## LobbyRoomScreen — lobby room where host and guest prepare before starting. +## +## Layout: +## VBox +## ├─ Header: "LOBBY: " + [Leave] button +## └─ HSplit +## ├─ Left: player slots (host & guest) + first-turn selector + deck controls +## └─ Right: rules display + preset panel (host only) + +# ── Node refs ───────────────────────────────────────────────────────────────── + +@onready var lobby_title_label : Label = %LobbyTitleLabel +@onready var host_name_label : Label = %HostNameLabel +@onready var host_deck_label : Label = %HostDeckLabel +@onready var host_ready_indicator : Label = %HostReadyIndicator +@onready var guest_name_label : Label = %GuestNameLabel +@onready var guest_deck_label : Label = %GuestDeckLabel +@onready var guest_ready_indicator: Label = %GuestReadyIndicator +@onready var ready_btn : Button = %ReadyBtn +@onready var change_deck_btn : Button = %ChangeDeckBtn +@onready var first_me_btn : Button = %FirstMeBtn +@onready var first_opp_btn : Button = %FirstOppBtn +@onready var first_random_btn : Button = %FirstRandomBtn +@onready var rules_label : Label = %RulesLabel +@onready var edit_rules_btn : Button = %EditRulesBtn +@onready var save_preset_btn : Button = %SavePresetBtn +@onready var load_preset_btn : Button = %LoadPresetBtn +@onready var vote_banner : PanelContainer = %VoteBanner +@onready var vote_label : Label = %VoteLabel +@onready var vote_yes_btn : Button = %VoteYesBtn +@onready var vote_no_btn : Button = %VoteNoBtn +@onready var deck_picker_dialog : AcceptDialog = %DeckPickerDialog +@onready var deck_picker_container: VBoxContainer = %DeckPickerContainer +@onready var preset_list_dialog : AcceptDialog = %PresetListDialog +@onready var preset_list_container: VBoxContainer = %PresetListContainer + +# ── State ───────────────────────────────────────────────────────────────────── + +var _first_turn_pref : String = "random" +var _current_rules : Dictionary = {} + +# ── Lifecycle ───────────────────────────────────────────────────────────────── + +func _ready() -> void: + _setup_ui() + _connect_signals() + _refresh_display() + + +func _exit_tree() -> void: + CustomLobby.guest_joined.disconnect(_on_guest_joined) + CustomLobby.ready_status_changed.disconnect(_on_ready_status_changed) + CustomLobby.lobby_rules_updated.disconnect(_on_rules_updated) + CustomLobby.lobby_deck_changed.disconnect(_on_deck_changed) + CustomLobby.game_starting.disconnect(_on_game_starting) + CustomLobby.preset_vote_requested.disconnect(_on_preset_vote_requested) + CustomLobby.preset_vote_rejected.disconnect(_on_preset_vote_rejected) + CustomLobby.lobby_left.disconnect(_on_lobby_left) + +# ── Setup ───────────────────────────────────────────────────────────────────── + +func _setup_ui() -> void: + # Back / Leave + $Layout/Header/HeaderMargin/HeaderInner/LeaveBtn.pressed.connect(_on_leave_pressed) + + # Ready button + ready_btn.pressed.connect(_on_ready_pressed) + + # Change deck + change_deck_btn.pressed.connect(_show_deck_picker) + + # First-turn toggles (mutual exclusive) + var btns := [first_me_btn, first_opp_btn, first_random_btn] + var prefs := [ + "host" if CustomLobby.is_host else "guest", + "guest" if CustomLobby.is_host else "host", + "random" + ] + for i in range(btns.size()): + var b := btns[i] + var pref := prefs[i] + b.pressed.connect(func(): + _first_turn_pref = pref + _update_first_turn_buttons()) + + first_random_btn.button_pressed = true + _first_turn_pref = "random" + + # Host-only controls + edit_rules_btn.visible = CustomLobby.is_host + save_preset_btn.visible = CustomLobby.is_host + load_preset_btn.visible = CustomLobby.is_host + + edit_rules_btn.pressed.connect(_on_edit_rules_pressed) + save_preset_btn.pressed.connect(_on_save_preset_pressed) + load_preset_btn.pressed.connect(_on_load_preset_pressed) + + vote_yes_btn.pressed.connect(func(): CustomLobby.vote_preset(true)) + vote_no_btn.pressed.connect(func(): CustomLobby.vote_preset(false)) + vote_banner.visible = false + + deck_picker_dialog.confirmed.connect(_on_deck_picker_confirmed) + preset_list_dialog.confirmed.connect(_on_preset_confirmed) + + +func _connect_signals() -> void: + CustomLobby.guest_joined.connect(_on_guest_joined) + CustomLobby.ready_status_changed.connect(_on_ready_status_changed) + CustomLobby.lobby_rules_updated.connect(_on_rules_updated) + CustomLobby.lobby_deck_changed.connect(_on_deck_changed) + CustomLobby.game_starting.connect(_on_game_starting) + CustomLobby.preset_vote_requested.connect(_on_preset_vote_requested) + CustomLobby.preset_vote_rejected.connect(_on_preset_vote_rejected) + CustomLobby.lobby_left.connect(_on_lobby_left) + +# ── Refresh ─────────────────────────────────────────────────────────────────── + +func _refresh_display() -> void: + var lobby := CustomLobby.lobby as Dictionary + var lobby_name : String = str(lobby.get("lobbyName", lobby.get("lobbyId", "Lobby"))) + lobby_title_label.text = "LOBBY: %s" % lobby_name + + # Host slot + host_name_label.text = "Host: %s" % str(lobby.get("hostDisplayName", Auth.user_id)) + host_deck_label.text = "Deck: (selected)" + + # Guest slot + var has_guest : bool = lobby.get("hasGuest", false) or lobby.get("guestAccountId", "") != "" + if has_guest: + guest_name_label.text = "Guest: %s" % str(lobby.get("guestDisplayName", "Guest")) + guest_deck_label.text = "Deck: (selected)" + else: + guest_name_label.text = "Waiting for guest…" + guest_deck_label.text = "" + + _update_ready_indicators(CustomLobby.i_am_ready if CustomLobby.is_host else CustomLobby.partner_ready, + CustomLobby.partner_ready if CustomLobby.is_host else CustomLobby.i_am_ready) + + # Rules + _current_rules = lobby.get("rules", lobby.get("activeRules", {})) + _update_rules_label() + + +func _update_ready_indicators(host_ready: bool, guest_ready: bool) -> void: + host_ready_indicator.text = "✓ READY" if host_ready else "Not ready" + host_ready_indicator.modulate = Color(0.2, 0.9, 0.3) if host_ready else Color(0.6, 0.6, 0.6) + guest_ready_indicator.text = "✓ READY" if guest_ready else "Not ready" + guest_ready_indicator.modulate = Color(0.2, 0.9, 0.3) if guest_ready else Color(0.6, 0.6, 0.6) + + # Update ready button text + if CustomLobby.i_am_ready: + ready_btn.text = "✗ Unready" + change_deck_btn.disabled = true + else: + ready_btn.text = "✓ Ready" + change_deck_btn.disabled = false + + # Lock first-turn buttons while ready + first_me_btn.disabled = CustomLobby.i_am_ready + first_opp_btn.disabled = CustomLobby.i_am_ready + first_random_btn.disabled = CustomLobby.i_am_ready + + # Lock edit rules if anyone is ready + edit_rules_btn.disabled = CustomLobby.i_am_ready or CustomLobby.partner_ready + + +func _update_first_turn_buttons() -> void: + first_me_btn.button_pressed = (_first_turn_pref == ("host" if CustomLobby.is_host else "guest")) + first_opp_btn.button_pressed = (_first_turn_pref == ("guest" if CustomLobby.is_host else "host")) + first_random_btn.button_pressed = (_first_turn_pref == "random") + + +func _update_rules_label() -> void: + if _current_rules.is_empty(): + rules_label.text = "(default rules)" + return + var lines : PackedStringArray = [] + var fields := { + "openingHandSize": "Opening Hand", + "drawPerTurn": "Draw/Turn", + "spAccumulationPerTurn": "SP/Turn", + "spHasCap": "SP Cap", + "spCap": "SP Cap Value", + "handSizeCap": "Hand Cap", + "turnTimerSeconds": "Turn Timer (s)", + "timeLimitMinutes": "Time Limit (min)", + "turnLimit": "Turn Limit", + "mpBuff": "MP Buff", + "boardWidth": "Board W", + "boardHeight": "Board H", + } + for key in fields: + if _current_rules.has(key): + lines.append("%s: %s" % [fields[key], _current_rules[key]]) + rules_label.text = "\n".join(lines) if not lines.is_empty() else "(default rules)" + +# ── Signal handlers ─────────────────────────────────────────────────────────── + +func _on_guest_joined(guest_account_id: String) -> void: + guest_name_label.text = "Guest: %s" % guest_account_id.substr(0, 8) + guest_deck_label.text = "Deck: (selected)" + + +func _on_ready_status_changed(host_ready: bool, guest_ready: bool) -> void: + _update_ready_indicators(host_ready, guest_ready) + + +func _on_rules_updated(new_rules: Dictionary) -> void: + _current_rules = new_rules + _update_rules_label() + + +func _on_deck_changed(_account_id: String, _deck_id: String) -> void: + host_deck_label.text = "Deck: (updated)" + guest_deck_label.text = "Deck: (updated)" + + +func _on_game_starting(session_id: String, _opponent_account_id: String) -> void: + ready_btn.disabled = true + ready_btn.text = "Starting…" + await get_tree().create_timer(0.8).timeout + get_tree().change_scene_to_file("res://scenes/game/GameScreen.tscn") + + +func _on_preset_vote_requested(payload: Dictionary) -> void: + var preset_name : String = str(payload.get("presetName", "a preset")) + vote_label.text = "Accept '%s'?" % preset_name + vote_banner.visible = true + + +func _on_preset_vote_rejected(_lid: String, _pid: String) -> void: + vote_banner.visible = false + _show_toast("Preset rejected") + + +func _on_lobby_left() -> void: + get_tree().change_scene_to_file("res://scenes/free_play/FreePlayScreen.tscn") + +# ── Actions ─────────────────────────────────────────────────────────────────── + +func _on_leave_pressed() -> void: + CustomLobby.leave() + + +func _on_ready_pressed() -> void: + if not CustomLobby.i_am_ready: + var deck_id := CustomLobby.my_deck_id + CustomLobby.set_ready(deck_id, _first_turn_pref) + else: + CustomLobby.unready() + + +func _show_deck_picker() -> void: + for child in deck_picker_container.get_children(): + child.queue_free() + Network.request("collection.get_decks", {}, + func(_t: String, p: Variant) -> void: + var d := p as Dictionary + var decks : Array = d.get("decks", []) + for deck in decks: + var btn := Button.new() + var did : String = str(deck.get("id", "")) + var name : String = str(deck.get("name", "Deck")) + btn.text = name + btn.pressed.connect(func(): + CustomLobby.change_deck(did) + deck_picker_dialog.hide()) + deck_picker_container.add_child(btn), + func(_c: String, _m: String) -> void: pass) + deck_picker_dialog.popup_centered() + + +func _on_deck_picker_confirmed() -> void: + pass # selection handled per-button above + + +func _on_edit_rules_pressed() -> void: + OS.alert("Rules editor: use the preset system or rejoin with custom rules.", "Edit Rules") + + +func _on_save_preset_pressed() -> void: + var dialog := AcceptDialog.new() + dialog.title = "Save Preset" + var input := LineEdit.new() + input.placeholder_text = "Preset name" + dialog.add_child(input) + add_child(dialog) + dialog.confirmed.connect(func(): + var name := input.text.strip_edges() + if name.is_empty(): return + CustomLobby.save_preset(name) + dialog.queue_free()) + dialog.popup_centered() + + +func _on_load_preset_pressed() -> void: + for child in preset_list_container.get_children(): + child.queue_free() + CustomLobby.list_presets(func(presets: Array) -> void: + for preset in presets: + var btn := Button.new() + var pid : String = str(preset.get("presetId", "")) + var name : String = str(preset.get("name", "Preset")) + btn.text = name + btn.pressed.connect(func(): + CustomLobby.propose_preset(pid) + preset_list_dialog.hide()) + preset_list_container.add_child(btn)) + preset_list_dialog.popup_centered() + + +func _on_preset_confirmed() -> void: + pass # handled per-button in load preset + + +func _show_toast(msg: String) -> void: + var lbl := Label.new() + lbl.text = msg + lbl.modulate = Color(1.0, 0.8, 0.2) + lbl.position = Vector2(get_viewport_rect().size.x / 2 - 100, 80) + add_child(lbl) + await get_tree().create_timer(2.5).timeout + lbl.queue_free() diff --git a/Client/origin-client/scenes/game/game_screen.gd b/Client/origin-client/scenes/game/game_screen.gd index 36a37d1..6ad566d 100644 --- a/Client/origin-client/scenes/game/game_screen.gd +++ b/Client/origin-client/scenes/game/game_screen.gd @@ -67,6 +67,7 @@ var count : int = 0 var _cam_tween : Tween = null var _last_click_frame : int = -1 var _last_click_iid : String = "" +var _is_spectating : bool = false # ── Affinity colors ─────────────────────────────────────────────────────────── const AFFINITY_COLORS : Dictionary = { @@ -225,6 +226,14 @@ func _ready() -> void: Game.opponent_inactive.connect(_on_opponent_inactive) Game.inactive_warning.connect(_on_inactive_warning) + if Game.is_spectating: + _is_spectating = true + _setup_spectator_ui() + # State was already applied via game.spectate ack — re-emit if present. + if not Game.state.is_empty(): + _on_state_updated(Game.state) + return + if not Game.state.is_empty(): _on_state_updated(Game.state) else: @@ -232,6 +241,8 @@ func _ready() -> void: func _exit_tree() -> void: + if _is_spectating: + Game.stop_spectating() if Game.state_updated.is_connected(_on_state_updated): Game.state_updated.disconnect(_on_state_updated) if Game.game_over.is_connected(_on_game_over): @@ -248,6 +259,22 @@ func _exit_tree() -> void: if child.name == "ChatOverlay": child.queue_free() + +func _setup_spectator_ui() -> void: + # "SPECTATING" overlay label. + var lbl := Label.new() + lbl.text = "SPECTATING" + lbl.modulate = Color(1.0, 0.76, 0.2) + lbl.theme_override_font_sizes = { &"font_size": 18 } + lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + lbl.set_anchors_preset(Control.PRESET_TOP_WIDE) + lbl.position = Vector2(0, 8) + _hud.add_child(lbl) + + # Hide action buttons — spectators can only watch. + _draw_btn.visible = false + _end_turn_btn.visible = false + # ── Environment ─────────────────────────────────────────────────────────────── func _setup_environment() -> void: @@ -2600,13 +2627,18 @@ func _find_hand_card(iid: String) -> Dictionary: func _update_hud(state: Dictionary) -> void: var phase : String = state.get("phase", "") var turn : int = state.get("turnNumber", 1) - var is_mine : bool = Game.is_my_turn() + var is_mine : bool = (not _is_spectating) and Game.is_my_turn() var my : Dictionary = Game.get_my_player() var opp : Dictionary = Game.get_opponent() _phase_lbl.text = "Phase: %s" % phase - _turn_lbl.text = "Turn %d — %s" % [turn, "Your turn" if is_mine else "Opponent's turn"] - _turn_lbl.modulate = Color(0.4, 1.0, 0.5) if is_mine else Color(1.0, 0.6, 0.6) + if _is_spectating: + var active_id : String = str(state.get("activePlayerAccountId", "")) + _turn_lbl.text = "Turn %d — Spectating" % turn + _turn_lbl.modulate = Color(1.0, 0.76, 0.2) + else: + _turn_lbl.text = "Turn %d — %s" % [turn, "Your turn" if is_mine else "Opponent's turn"] + _turn_lbl.modulate = Color(0.4, 1.0, 0.5) if is_mine else Color(1.0, 0.6, 0.6) _sp_lbl.text = "SP: %d" % int(my.get("currentSp", 0)) _st_lbl.text = "ST: %d" % int(my.get("currentSt", 0)) @@ -2617,9 +2649,13 @@ func _update_hud(state: Dictionary) -> void: _opp_hand_lbl.text = "Hand: %d" % int(opp.get("handCount", 0)) _opp_deck_lbl.text = "Deck: %d" % int(opp.get("deckCount", 0)) - _draw_btn.visible = (phase == "Draw" and is_mine) - _end_turn_btn.visible = (phase == "Main" and is_mine) - _end_turn_btn.disabled = not is_mine + if _is_spectating: + _draw_btn.visible = false + _end_turn_btn.visible = false + else: + _draw_btn.visible = (phase == "Draw" and is_mine) + _end_turn_btn.visible = (phase == "Main" and is_mine) + _end_turn_btn.disabled = not is_mine if phase == "Placement": var my_arch : Dictionary = my.get("archSpirit", {}) diff --git a/Client/origin-client/scenes/main/MainScreen.tscn b/Client/origin-client/scenes/main/MainScreen.tscn index 983217d..101aa92 100644 --- a/Client/origin-client/scenes/main/MainScreen.tscn +++ b/Client/origin-client/scenes/main/MainScreen.tscn @@ -124,6 +124,13 @@ custom_minimum_size = Vector2(0, 52) text = "Find Match" theme_override_font_sizes/font_size = 15 +[node name="FreePlayBtn" type="Button" parent="Layout/Scroll/Content/ContentMargin/ContentInner/NavButtons"] +unique_name_in_owner = true +layout_mode = 2 +custom_minimum_size = Vector2(0, 52) +text = "Free Play" +theme_override_font_sizes/font_size = 15 + [node name="SocialSection" type="Label" parent="Layout/Scroll/Content/ContentMargin/ContentInner"] layout_mode = 2 text = "COMMUNITY" diff --git a/Client/origin-client/scenes/main/main_screen.gd b/Client/origin-client/scenes/main/main_screen.gd index 382126c..e9a1604 100644 --- a/Client/origin-client/scenes/main/main_screen.gd +++ b/Client/origin-client/scenes/main/main_screen.gd @@ -8,6 +8,7 @@ extends Control @onready var status_label : Label = %StatusLabel @onready var logout_btn : Button = %LogoutBtn @onready var match_btn : Button = %MatchBtn +@onready var free_play_btn : Button = %FreePlayBtn @onready var collection_btn : Button = %CollectionBtn @onready var bazaar_btn : Button = %BazaarBtn @onready var leaderboard_btn : Button = %LeaderboardBtn @@ -31,6 +32,9 @@ func _ready() -> void: match_btn.pressed.connect(func(): get_tree().change_scene_to_file("res://scenes/matchmaking/MatchmakingScreen.tscn")) + free_play_btn.pressed.connect(func(): + get_tree().change_scene_to_file("res://scenes/free_play/FreePlayScreen.tscn")) + collection_btn.pressed.connect(func(): get_tree().change_scene_to_file("res://scenes/collection/CollectionScreen.tscn")) diff --git a/Server/src/SOR.Database/Entities/Game/CustomLobby.cs b/Server/src/SOR.Database/Entities/Game/CustomLobby.cs index d865e81..16b7221 100644 --- a/Server/src/SOR.Database/Entities/Game/CustomLobby.cs +++ b/Server/src/SOR.Database/Entities/Game/CustomLobby.cs @@ -80,6 +80,23 @@ public sealed class CustomLobby /// Board height override in rows. public int? BoardHeightOverride { get; set; } + // ── Ready-up state ──────────────────────────────────────────────────────── + + /// True once the host has clicked Ready in the lobby room. + public bool HostReady { get; set; } = false; + + /// True once the guest has clicked Ready in the lobby room. + public bool GuestReady { get; set; } = false; + + /// Host's first-turn preference: "host" | "guest" | "random" | null. + public string? HostFirstTurnPref { get; set; } + + /// Guest's first-turn preference: "host" | "guest" | "random" | null. + public string? GuestFirstTurnPref { get; set; } + + /// Maximum number of players. Default 2; stub for future N-player support. + public int MaxPlayers { get; set; } = 2; + // ── Timestamps ─────────────────────────────────────────────────────────── public DateTimeOffset CreatedAt { get; set; } diff --git a/Server/src/SOR.Database/Migrations/Game/20260319125847_AddReadyUpSystem.Designer.cs b/Server/src/SOR.Database/Migrations/Game/20260319125847_AddReadyUpSystem.Designer.cs new file mode 100644 index 0000000..c22e2b0 --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Game/20260319125847_AddReadyUpSystem.Designer.cs @@ -0,0 +1,417 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using SOR.Database.Contexts; + +#nullable disable + +namespace SOR.Database.Migrations.Game +{ + [DbContext(typeof(GameDbContext))] + [Migration("20260319125847_AddReadyUpSystem")] + partial class AddReadyUpSystem + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("game") + .HasAnnotation("ProductVersion", "8.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BoardHeightOverride") + .HasColumnType("integer"); + + b.Property("BoardWidthOverride") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiscardOnMaxHandOverride") + .HasColumnType("boolean"); + + b.Property("DrawPerTurnOverride") + .HasColumnType("integer"); + + b.Property("FirstPlayerSkipsDrawOverride") + .HasColumnType("boolean"); + + b.Property("GameSessionId") + .HasColumnType("uuid"); + + b.Property("GuestAccountId") + .HasColumnType("uuid"); + + b.Property("GuestDeckId") + .HasColumnType("uuid"); + + b.Property("GuestFirstTurnPref") + .HasColumnType("text"); + + b.Property("GuestReady") + .HasColumnType("boolean"); + + b.Property("HandSizeCapOverride") + .HasColumnType("integer"); + + b.Property("HostAccountId") + .HasColumnType("uuid"); + + b.Property("HostDeckId") + .HasColumnType("uuid"); + + b.Property("HostFirstTurnPref") + .HasColumnType("text"); + + b.Property("HostReady") + .HasColumnType("boolean"); + + b.Property("MaxArchTier1Override") + .HasColumnType("integer"); + + b.Property("MaxDeckSizeOverride") + .HasColumnType("integer"); + + b.Property("MaxPlayers") + .HasColumnType("integer"); + + b.Property("MinDeckSizeOverride") + .HasColumnType("integer"); + + b.Property("MpBuffOverride") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OpeningHandSizeOverride") + .HasColumnType("integer"); + + b.Property("Password") + .HasColumnType("text"); + + b.Property("SpAccumulationPerTurnOverride") + .HasColumnType("integer"); + + b.Property("SpCapOverride") + .HasColumnType("integer"); + + b.Property("SpHasCapOverride") + .HasColumnType("boolean"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimeLimitMinutesOverride") + .HasColumnType("integer"); + + b.Property("TurnLimitOverride") + .HasColumnType("integer"); + + b.Property("TurnTimerSecondsOverride") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("HostAccountId"); + + b.HasIndex("Status", "CreatedAt"); + + b.ToTable("custom_lobbies", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ActionType") + .IsRequired() + .HasColumnType("text"); + + b.Property("ActorAccountId") + .HasColumnType("uuid"); + + b.Property("GameSessionId") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PayloadJson") + .HasColumnType("jsonb") + .HasColumnName("payload"); + + b.Property("ResultJson") + .HasColumnType("jsonb") + .HasColumnName("result"); + + b.Property("SequenceNumber") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ActorAccountId"); + + b.HasIndex("GameSessionId", "SequenceNumber") + .IsUnique(); + + b.ToTable("action_logs", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameRuleSet", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BoardHeight") + .HasColumnType("integer"); + + b.Property("BoardWidth") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiscardOnMaxHand") + .HasColumnType("boolean"); + + b.Property("DrawPerTurn") + .HasColumnType("integer"); + + b.Property("FirstPlayerSkipsDraw") + .HasColumnType("boolean"); + + b.Property("HandSizeCap") + .HasColumnType("integer"); + + b.Property("IsCustomDefault") + .HasColumnType("boolean"); + + b.Property("IsRankedDefault") + .HasColumnType("boolean"); + + b.Property("LoserOpReward") + .HasColumnType("integer"); + + b.Property("MaxArchTier1") + .HasColumnType("integer"); + + b.Property("MaxDeckSize") + .HasColumnType("integer"); + + b.Property("MinDeckSize") + .HasColumnType("integer"); + + b.Property("MpBuff") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OpeningHandSize") + .HasColumnType("integer"); + + b.Property("RankDiffOpMultiplierPct") + .HasColumnType("integer"); + + b.Property("SpAccumulationPerTurn") + .HasColumnType("integer"); + + b.Property("SpCap") + .HasColumnType("integer"); + + b.Property("SpHasCap") + .HasColumnType("boolean"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("TurnLimit") + .HasColumnType("integer"); + + b.Property("TurnTimerSeconds") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("WinnerOpReward") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IsCustomDefault"); + + b.HasIndex("IsRankedDefault"); + + b.ToTable("game_rule_sets", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EndedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastActionAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PlayerOneAccountId") + .HasColumnType("uuid"); + + b.Property("PlayerOneDeckId") + .HasColumnType("uuid"); + + b.Property("PlayerOneReady") + .HasColumnType("boolean"); + + b.Property("PlayerTwoAccountId") + .HasColumnType("uuid"); + + b.Property("PlayerTwoDeckId") + .HasColumnType("uuid"); + + b.Property("PlayerTwoReady") + .HasColumnType("boolean"); + + b.Property("RuleSnapshotJson") + .HasColumnType("jsonb") + .HasColumnName("rule_snapshot"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("StateJson") + .HasColumnType("jsonb") + .HasColumnName("state"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("WinCondition") + .HasColumnType("text"); + + b.Property("WinnerAccountId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PlayerOneAccountId"); + + b.HasIndex("PlayerTwoAccountId"); + + b.HasIndex("Status", "CreatedAt"); + + b.ToTable("game_sessions", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.LobbyPreset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerAccountId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("OwnerAccountId"); + + b.ToTable("lobby_presets", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountId") + .HasColumnType("uuid"); + + b.Property("DeckId") + .HasColumnType("uuid"); + + b.Property("JoinedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("MatchedGameSessionId") + .HasColumnType("uuid"); + + b.Property("RankScore") + .HasColumnType("integer"); + + b.Property("ResolvedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("AccountId", "Status"); + + b.HasIndex("Status", "RankScore"); + + b.ToTable("matchmaking_entries", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b => + { + b.HasOne("SOR.Database.Entities.Game.GameSession", "Session") + .WithMany("ActionLog") + .HasForeignKey("GameSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Session"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b => + { + b.Navigation("ActionLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Game/20260319125847_AddReadyUpSystem.cs b/Server/src/SOR.Database/Migrations/Game/20260319125847_AddReadyUpSystem.cs new file mode 100644 index 0000000..8e57255 --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Game/20260319125847_AddReadyUpSystem.cs @@ -0,0 +1,81 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SOR.Database.Migrations.Game +{ + /// + public partial class AddReadyUpSystem : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "GuestFirstTurnPref", + schema: "game", + table: "custom_lobbies", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "GuestReady", + schema: "game", + table: "custom_lobbies", + type: "boolean", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "HostFirstTurnPref", + schema: "game", + table: "custom_lobbies", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "HostReady", + schema: "game", + table: "custom_lobbies", + type: "boolean", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "MaxPlayers", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: false, + defaultValue: 0); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "GuestFirstTurnPref", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "GuestReady", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "HostFirstTurnPref", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "HostReady", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "MaxPlayers", + schema: "game", + table: "custom_lobbies"); + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs index e440e11..782a02d 100644 --- a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs +++ b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs @@ -56,6 +56,12 @@ namespace SOR.Database.Migrations.Game b.Property("GuestDeckId") .HasColumnType("uuid"); + b.Property("GuestFirstTurnPref") + .HasColumnType("text"); + + b.Property("GuestReady") + .HasColumnType("boolean"); + b.Property("HandSizeCapOverride") .HasColumnType("integer"); @@ -65,12 +71,21 @@ namespace SOR.Database.Migrations.Game b.Property("HostDeckId") .HasColumnType("uuid"); + b.Property("HostFirstTurnPref") + .HasColumnType("text"); + + b.Property("HostReady") + .HasColumnType("boolean"); + b.Property("MaxArchTier1Override") .HasColumnType("integer"); b.Property("MaxDeckSizeOverride") .HasColumnType("integer"); + b.Property("MaxPlayers") + .HasColumnType("integer"); + b.Property("MinDeckSizeOverride") .HasColumnType("integer"); diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index 4a77e74..2dc7274 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -159,6 +159,23 @@ public sealed record ListCustomLobbiesRequest( string? NameSearch = null, bool ShowPasswordProtected = true); +// ── Ready-up requests ───────────────────────────────────────────────────────── + +/// Mark the caller as ready in a Full lobby with their final deck and first-turn preference. +public sealed record LobbyReadyRequest(Guid LobbyId, Guid DeckId, string FirstTurnPref); + +/// Withdraw the caller's ready status in a Full lobby. +public sealed record UnreadyInLobbyRequest(Guid LobbyId); + +/// Change the caller's deck selection while in a Full lobby (not yet ready). +public sealed record ChangeLobbyDeckRequest(Guid LobbyId, Guid DeckId); + +/// Host updates lobby rule overrides while in Full state (neither player ready yet). +public sealed record UpdateLobbyRulesRequest(Guid LobbyId, CustomRulesOverride Rules); + +/// List all in-progress custom games (Status == Started). Supports paging. +public sealed record ListActiveLobbiesRequest(int Page = 1, int PageSize = 20); + // ── Responses ───────────────────────────────────────────────────────────────── public sealed record GameReadyResponse(Guid SessionId, string Status); @@ -205,8 +222,8 @@ public sealed record CreateCustomLobbyResponse( public sealed record JoinCustomLobbyResponse( Guid LobbyId, - string Status, // "WaitingForHost" | "GameCreated" - Guid? GameSessionId); // set when Status == "GameCreated" + string Status, // "WaitingForReady" + Guid? GameSessionId); // always null; reserved for future use public sealed record LeaveCustomLobbyResponse(Guid LobbyId); @@ -238,6 +255,22 @@ public sealed record ListCustomLobbiesResponse( int Page, int PageSize); +// ── Ready-up responses ──────────────────────────────────────────────────────── + +public sealed record LobbyReadyResponse(Guid LobbyId, bool IsReady); + +public sealed record UnreadyInLobbyResponse(Guid LobbyId); + +public sealed record ChangeLobbyDeckResponse(Guid LobbyId); + +public sealed record UpdateLobbyRulesResponse(Guid LobbyId, CustomRulesDto Rules); + +public sealed record ListActiveLobbiesResponse( + IEnumerable Games, + int TotalCount, + int Page, + int PageSize); + // ── Server Pushes ───────────────────────────────────────────────────────────── /// @@ -309,6 +342,12 @@ public sealed record LobbyUpdatedPush(Guid LobbyId, CustomRulesDto NewRules); /// Pushed to both participants when a preset-load vote is rejected. public sealed record PresetVoteRejectedPush(Guid LobbyId, Guid PresetId); +/// Pushed to both participants whenever a lobby participant's ready status changes. +public sealed record LobbyReadyStatusPush(Guid LobbyId, bool HostReady, bool GuestReady); + +/// Pushed to both participants when a lobby participant changes their selected deck. +public sealed record LobbyDeckChangedPush(Guid LobbyId, Guid AccountId, Guid DeckId); + // ── DTOs ───────────────────────────────────────────────────────────────────── /// @@ -396,10 +435,24 @@ public sealed record CustomLobbyDto( Guid LobbyId, string LobbyName, Guid HostAccountId, + string HostDisplayName, bool HasGuest, + string? GuestDisplayName, CustomRulesDto Rules, DateTimeOffset CreatedAt); +/// Summary of an in-progress custom game, shown in the Active Games browser. +public sealed record ActiveLobbyDto( + Guid LobbyId, + string LobbyName, + Guid HostAccountId, + string HostDisplayName, + Guid GuestAccountId, + string GuestDisplayName, + Guid GameSessionId, + bool HasPassword, + CustomRulesDto Rules); + /// /// Detailed view of a custom lobby, including full rule set and participant presence. /// Returned by game.custom.get. diff --git a/Server/src/SOR.Game/Handlers/GameChangeLobbyDeckHandler.cs b/Server/src/SOR.Game/Handlers/GameChangeLobbyDeckHandler.cs new file mode 100644 index 0000000..2cd2d7c --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameChangeLobbyDeckHandler.cs @@ -0,0 +1,75 @@ +namespace SOR.Game.Handlers; + +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.custom.lobby.change_deck — change the calling player's selected deck while in a Full lobby. +/// +/// Only allowed when the lobby is Full and the caller has not yet marked themselves ready. +/// A LobbyDeckChangedPush is sent to both participants after the update. +/// +internal sealed class GameChangeLobbyDeckHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameChangeLobbyDeckHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.custom.lobby.change_deck"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var accountId = Guid.Parse(connection.UserId); + + var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct) + ?? throw new GameException("LOBBY_NOT_FOUND"); + + if (lobby.Status != CustomLobbyStatus.Full) + throw new GameException("LOBBY_NOT_FULL"); + + var isHost = lobby.HostAccountId == accountId; + var isGuest = lobby.GuestAccountId == accountId; + + if (!isHost && !isGuest) + throw new GameException("NOT_IN_LOBBY"); + + // Cannot change deck once ready. + if (isHost && lobby.HostReady) throw new GameException("ALREADY_READY"); + if (isGuest && lobby.GuestReady) throw new GameException("ALREADY_READY"); + + if (isHost) + lobby.HostDeckId = req.DeckId; + else + lobby.GuestDeckId = req.DeckId; + + await _gameDb.SaveChangesAsync(ct); + + var deckChangedPush = ServerMessage.Push("game.custom.lobby.deck_changed", + new LobbyDeckChangedPush(lobby.Id, accountId, req.DeckId)); + + await Task.WhenAll( + _clientPush.PushAsync(lobby.HostAccountId.ToString(), deckChangedPush, ct), + _clientPush.PushAsync(lobby.GuestAccountId!.Value.ToString(), deckChangedPush, ct)); + + return ServerMessage.Reply("game.custom.lobby.change_deck.ack", message.Seq, + new ChangeLobbyDeckResponse(LobbyId: lobby.Id)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs b/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs index 83bdb63..b21c0af 100644 --- a/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs @@ -1,45 +1,33 @@ namespace SOR.Game.Handlers; -using System.Text.Json; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; using SOR.Database.Contexts; -using SOR.Database.Entities.Game; using SOR.Database.Enums; -using SOR.Networking.Abstractions.EventBus; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Push; using SOR.Networking.Abstractions.Transport; -using SOR.Shared.Nats; using SOR.Shared.Networking; /// /// game.custom.join — guest joins an open custom lobby with their chosen deck. /// -/// When the lobby is full (both host and guest present), a GameSession is created -/// immediately and CustomLobbyGameStartedPush is sent to both players. Both players -/// then send game.ready to start the actual game. +/// When the guest joins, the lobby transitions to Full and both players enter +/// the lobby room. The game does NOT start here — both players must mark themselves +/// ready via game.custom.lobby.ready before the GameSession is created. /// internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHandler { private readonly IMessageSerializer _serializer; private readonly GameDbContext _gameDb; private readonly IClientPush _clientPush; - private readonly IEventBus _eventBus; - private readonly ILogger _logger; public GameJoinCustomLobbyHandler( IMessageSerializer serializer, GameDbContext gameDb, - IClientPush clientPush, - IEventBus eventBus, - ILogger logger) + IClientPush clientPush) { _serializer = serializer; _gameDb = gameDb; _clientPush = clientPush; - _eventBus = eventBus; - _logger = logger; } public string MessageType => "game.custom.join"; @@ -65,81 +53,31 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand if (lobby.Password != null && lobby.Password != req.Password) throw new GameException("WRONG_PASSWORD"); + // Seat the guest and transition to Full. lobby.GuestAccountId = accountId; lobby.GuestDeckId = req.DeckId; lobby.Status = CustomLobbyStatus.Full; - // Build the effective rules from stored overrides (falling back to Default). - var rules = new GameRules - { - OpeningHandSize = lobby.OpeningHandSizeOverride ?? GameRules.Default.OpeningHandSize, - FirstPlayerSkipsDraw = lobby.FirstPlayerSkipsDrawOverride ?? GameRules.Default.FirstPlayerSkipsDraw, - SpAccumulationPerTurn = lobby.SpAccumulationPerTurnOverride ?? GameRules.Default.SpAccumulationPerTurn, - DrawPerTurn = lobby.DrawPerTurnOverride ?? GameRules.Default.DrawPerTurn, - SpHasCap = lobby.SpHasCapOverride ?? GameRules.Default.SpHasCap, - SpCap = lobby.SpCapOverride ?? GameRules.Default.SpCap, - BoardWidth = lobby.BoardWidthOverride ?? GameRules.Default.BoardWidth, - BoardHeight = lobby.BoardHeightOverride ?? GameRules.Default.BoardHeight, - HandSizeCap = lobby.HandSizeCapOverride ?? GameRules.Default.HandSizeCap, - DiscardOnMaxHand = lobby.DiscardOnMaxHandOverride ?? GameRules.Default.DiscardOnMaxHand, - MaxDeckSize = lobby.MaxDeckSizeOverride ?? GameRules.Default.MaxDeckSize, - MinDeckSize = lobby.MinDeckSizeOverride ?? GameRules.Default.MinDeckSize, - MaxArchTier1 = lobby.MaxArchTier1Override ?? GameRules.Default.MaxArchTier1, - TurnTimerSeconds = lobby.TurnTimerSecondsOverride ?? GameRules.Default.TurnTimerSeconds, - TimeLimitMinutes = lobby.TimeLimitMinutesOverride ?? GameRules.Default.TimeLimitMinutes, - TurnLimit = lobby.TurnLimitOverride ?? GameRules.Default.TurnLimit, - MpBuff = lobby.MpBuffOverride ?? GameRules.Default.MpBuff, - }; - - // Create the game session with the rule snapshot. - var session = new GameSession - { - PlayerOneAccountId = lobby.HostAccountId, - PlayerOneDeckId = lobby.HostDeckId, - PlayerTwoAccountId = accountId, - PlayerTwoDeckId = req.DeckId, - Status = GameSessionStatus.Initializing, - CreatedAt = DateTimeOffset.UtcNow, - RuleSnapshotJson = JsonSerializer.Serialize(rules), - }; - - _gameDb.GameSessions.Add(session); - - lobby.GameSessionId = session.Id; - lobby.Status = CustomLobbyStatus.Started; + // Reset readiness — joining always starts a fresh ready-up cycle. + lobby.HostReady = false; + lobby.GuestReady = false; + lobby.HostFirstTurnPref = null; + lobby.GuestFirstTurnPref = null; await _gameDb.SaveChangesAsync(ct); - try - { - await _eventBus.PublishAsync( - NatsSubjects.GameStarted, - new GameStartedEvent( - session.Id, - new[] { lobby.HostAccountId, accountId }, - DateTimeOffset.UtcNow), - ct); - } - catch (Exception ex) - { - _logger.LogError(ex, - "Failed publishing game-started event for custom lobby session {SessionId}", - session.Id); - } - - // Push game-started notification to both players. - await Task.WhenAll( - _clientPush.PushAsync(lobby.HostAccountId.ToString(), - ServerMessage.Push("game.custom.started", - new CustomLobbyGameStartedPush(session.Id, accountId)), ct), - _clientPush.PushAsync(accountId.ToString(), - ServerMessage.Push("game.custom.started", - new CustomLobbyGameStartedPush(session.Id, lobby.HostAccountId)), ct)); + // Notify the host that their guest has arrived. + await _clientPush.PushAsync(lobby.HostAccountId.ToString(), + ServerMessage.Push("game.custom.lobby.guest_joined", + new CustomLobbyGuestJoinedPush( + LobbyId : lobby.Id, + GuestAccountId: accountId, + LobbyName : lobby.Name)), ct); return ServerMessage.Reply("game.custom.join.ack", message.Seq, new JoinCustomLobbyResponse( - LobbyId : lobby.Id, - Status : "GameCreated", - GameSessionId : session.Id)); + LobbyId : lobby.Id, + Status : "WaitingForReady", + GameSessionId: null)); } } diff --git a/Server/src/SOR.Game/Handlers/GameListActiveLobbiesHandler.cs b/Server/src/SOR.Game/Handlers/GameListActiveLobbiesHandler.cs new file mode 100644 index 0000000..fc84c75 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameListActiveLobbiesHandler.cs @@ -0,0 +1,105 @@ +namespace SOR.Game.Handlers; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.custom.list_active — returns a paged list of in-progress custom games (Status == Started). +/// +/// Host and guest display names are batch-loaded from the identity database. +/// The GameSessionId is included so clients can spectate via game.spectate. +/// +internal sealed class GameListActiveLobbiesHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly SorIdentityDbContext _identityDb; + + public GameListActiveLobbiesHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + SorIdentityDbContext identityDb) + { + _serializer = serializer; + _gameDb = gameDb; + _identityDb = identityDb; + } + + public string MessageType => "game.custom.list_active"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + + var page = Math.Max(1, req.Page); + var pageSize = Math.Clamp(req.PageSize, 1, 100); + + var query = _gameDb.CustomLobbies + .AsNoTracking() + .Where(l => l.Status == CustomLobbyStatus.Started + && l.GameSessionId.HasValue + && l.GuestAccountId.HasValue) + .OrderByDescending(l => l.CreatedAt); + + var total = await query.CountAsync(ct); + var lobbies = await query + .Skip((page - 1) * pageSize) + .Take(pageSize) + .ToListAsync(ct); + + // Batch-load display names for all hosts and guests. + var accountIds = lobbies + .SelectMany(l => new[] { l.HostAccountId, l.GuestAccountId!.Value }) + .Distinct() + .ToList(); + + var displayNames = await _identityDb.Users + .AsNoTracking() + .Where(a => accountIds.Contains(a.Id)) + .Select(a => new { a.Id, Name = a.DisplayName ?? a.UserName ?? a.Id.ToString() }) + .ToDictionaryAsync(a => a.Id, a => a.Name, ct); + + var dtos = lobbies.Select(l => new ActiveLobbyDto( + LobbyId : l.Id, + LobbyName : l.Name, + HostAccountId : l.HostAccountId, + HostDisplayName : displayNames.GetValueOrDefault(l.HostAccountId, l.HostAccountId.ToString()[..8]), + GuestAccountId : l.GuestAccountId!.Value, + GuestDisplayName: displayNames.GetValueOrDefault(l.GuestAccountId!.Value, l.GuestAccountId.Value.ToString()[..8]), + GameSessionId : l.GameSessionId!.Value, + HasPassword : l.Password != null, + Rules : new CustomRulesDto( + OpeningHandSize : l.OpeningHandSizeOverride ?? GameRules.Default.OpeningHandSize, + FirstPlayerSkipsDraw : l.FirstPlayerSkipsDrawOverride ?? GameRules.Default.FirstPlayerSkipsDraw, + SpAccumulationPerTurn : l.SpAccumulationPerTurnOverride ?? GameRules.Default.SpAccumulationPerTurn, + DrawPerTurn : l.DrawPerTurnOverride ?? GameRules.Default.DrawPerTurn, + SpHasCap : l.SpHasCapOverride ?? GameRules.Default.SpHasCap, + SpCap : l.SpCapOverride ?? GameRules.Default.SpCap, + BoardWidth : l.BoardWidthOverride ?? GameRules.Default.BoardWidth, + BoardHeight : l.BoardHeightOverride ?? GameRules.Default.BoardHeight, + HandSizeCap : l.HandSizeCapOverride ?? GameRules.Default.HandSizeCap, + DiscardOnMaxHand : l.DiscardOnMaxHandOverride ?? GameRules.Default.DiscardOnMaxHand, + MaxDeckSize : l.MaxDeckSizeOverride ?? GameRules.Default.MaxDeckSize, + MinDeckSize : l.MinDeckSizeOverride ?? GameRules.Default.MinDeckSize, + MaxArchTier1 : l.MaxArchTier1Override ?? GameRules.Default.MaxArchTier1, + TurnTimerSeconds : l.TurnTimerSecondsOverride ?? GameRules.Default.TurnTimerSeconds, + TimeLimitMinutes : l.TimeLimitMinutesOverride ?? GameRules.Default.TimeLimitMinutes, + TurnLimit : l.TurnLimitOverride ?? GameRules.Default.TurnLimit, + MpBuff : l.MpBuffOverride ?? GameRules.Default.MpBuff, + HasPassword : l.Password != null))); + + return ServerMessage.Reply("game.custom.list_active.ack", message.Seq, + new ListActiveLobbiesResponse( + Games : dtos, + TotalCount : total, + Page : page, + PageSize : pageSize)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs b/Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs index a436bbd..0e6e806 100644 --- a/Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs @@ -10,16 +10,22 @@ using SOR.Shared.Networking; /// /// game.custom.list — returns a paged list of open custom lobbies. /// Supports optional NameSearch filter and ShowPasswordProtected toggle. +/// Batch-loads host/guest display names from the identity database. /// internal sealed class GameListCustomLobbiesHandler : GameHandlerBase, IMessageHandler { - private readonly IMessageSerializer _serializer; - private readonly GameDbContext _gameDb; + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly SorIdentityDbContext _identityDb; - public GameListCustomLobbiesHandler(IMessageSerializer serializer, GameDbContext gameDb) + public GameListCustomLobbiesHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + SorIdentityDbContext identityDb) { - _serializer = serializer; - _gameDb = gameDb; + _serializer = serializer; + _gameDb = gameDb; + _identityDb = identityDb; } public string MessageType => "game.custom.list"; @@ -52,11 +58,29 @@ internal sealed class GameListCustomLobbiesHandler : GameHandlerBase, IMessageHa .Take(pageSize) .ToListAsync(ct); + // Batch-load display names for all participants in the result set. + var accountIds = lobbies + .SelectMany(l => l.GuestAccountId.HasValue + ? new[] { l.HostAccountId, l.GuestAccountId.Value } + : new[] { l.HostAccountId }) + .Distinct() + .ToList(); + + var displayNames = await _identityDb.Users + .AsNoTracking() + .Where(a => accountIds.Contains(a.Id)) + .Select(a => new { a.Id, Name = a.DisplayName ?? a.UserName ?? a.Id.ToString() }) + .ToDictionaryAsync(a => a.Id, a => a.Name, ct); + var dtos = lobbies.Select(l => new CustomLobbyDto( - LobbyId : l.Id, - LobbyName : l.Name, - HostAccountId : l.HostAccountId, - HasGuest : l.GuestAccountId.HasValue, + LobbyId : l.Id, + LobbyName : l.Name, + HostAccountId : l.HostAccountId, + HostDisplayName : displayNames.GetValueOrDefault(l.HostAccountId, l.HostAccountId.ToString()[..8]), + HasGuest : l.GuestAccountId.HasValue, + GuestDisplayName: l.GuestAccountId.HasValue + ? displayNames.GetValueOrDefault(l.GuestAccountId.Value, l.GuestAccountId.Value.ToString()[..8]) + : null, Rules : new CustomRulesDto( OpeningHandSize : l.OpeningHandSizeOverride ?? GameRules.Default.OpeningHandSize, FirstPlayerSkipsDraw : l.FirstPlayerSkipsDrawOverride ?? GameRules.Default.FirstPlayerSkipsDraw, diff --git a/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs b/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs new file mode 100644 index 0000000..6e7e83a --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs @@ -0,0 +1,186 @@ +namespace SOR.Game.Handlers; + +using System.Text.Json; +using Microsoft.Extensions.Logging; +using SOR.Database.Contexts; +using SOR.Database.Entities.Game; +using SOR.Database.Enums; +using SOR.Networking.Abstractions.EventBus; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Nats; +using SOR.Shared.Networking; + +/// +/// game.custom.lobby.ready — mark the calling player as ready inside a Full lobby. +/// +/// Updates the caller's deck choice and first-turn preference, then sets their +/// ready flag. When both players are ready the handler resolves who goes first, +/// creates the GameSession, and pushes CustomLobbyGameStartedPush to both. +/// +internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + private readonly IEventBus _eventBus; + private readonly ILogger _logger; + + public GameLobbyReadyHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush, + IEventBus eventBus, + ILogger logger) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + _eventBus = eventBus; + _logger = logger; + } + + public string MessageType => "game.custom.lobby.ready"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var accountId = Guid.Parse(connection.UserId); + + var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct) + ?? throw new GameException("LOBBY_NOT_FOUND"); + + if (lobby.Status != CustomLobbyStatus.Full) + throw new GameException("LOBBY_NOT_FULL"); + + var isHost = lobby.HostAccountId == accountId; + var isGuest = lobby.GuestAccountId == accountId; + + if (!isHost && !isGuest) + throw new GameException("NOT_IN_LOBBY"); + + // Update deck and first-turn pref, then mark ready. + if (isHost) + { + lobby.HostDeckId = req.DeckId; + lobby.HostFirstTurnPref = req.FirstTurnPref; + lobby.HostReady = true; + } + else + { + lobby.GuestDeckId = req.DeckId; + lobby.GuestFirstTurnPref = req.FirstTurnPref; + lobby.GuestReady = true; + } + + await _gameDb.SaveChangesAsync(ct); + + // Push updated ready status to both participants. + var readyPush = ServerMessage.Push("game.custom.lobby.ready_status", + new LobbyReadyStatusPush(lobby.Id, lobby.HostReady, lobby.GuestReady)); + + await Task.WhenAll( + _clientPush.PushAsync(lobby.HostAccountId.ToString(), readyPush, ct), + _clientPush.PushAsync(lobby.GuestAccountId!.Value.ToString(), readyPush, ct)); + + // All-ready check. + bool allReady = lobby.GuestAccountId.HasValue && lobby.HostReady && lobby.GuestReady; + + if (allReady) + await StartGameAsync(lobby, accountId, ct); + + return ServerMessage.Reply("game.custom.lobby.ready.ack", message.Seq, + new LobbyReadyResponse(LobbyId: lobby.Id, IsReady: true)); + } + + private async Task StartGameAsync( + SOR.Database.Entities.Game.CustomLobby lobby, + Guid triggeringAccountId, + CancellationToken ct) + { + var guestId = lobby.GuestAccountId!.Value; + + // Resolve first-turn: matching preferences → that player goes first; otherwise random. + Guid playerOneId; + if (lobby.HostFirstTurnPref == "host" && lobby.GuestFirstTurnPref == "host") + playerOneId = lobby.HostAccountId; + else if (lobby.HostFirstTurnPref == "guest" && lobby.GuestFirstTurnPref == "guest") + playerOneId = guestId; + else + playerOneId = Random.Shared.Next(2) == 0 ? lobby.HostAccountId : guestId; + + var playerTwoId = playerOneId == lobby.HostAccountId ? guestId : lobby.HostAccountId; + var p1DeckId = playerOneId == lobby.HostAccountId ? lobby.HostDeckId : lobby.GuestDeckId!.Value; + var p2DeckId = playerTwoId == lobby.HostAccountId ? lobby.HostDeckId : lobby.GuestDeckId!.Value; + + // Build effective rules from stored overrides. + var rules = new GameRules + { + OpeningHandSize = lobby.OpeningHandSizeOverride ?? GameRules.Default.OpeningHandSize, + FirstPlayerSkipsDraw = lobby.FirstPlayerSkipsDrawOverride ?? GameRules.Default.FirstPlayerSkipsDraw, + SpAccumulationPerTurn = lobby.SpAccumulationPerTurnOverride ?? GameRules.Default.SpAccumulationPerTurn, + DrawPerTurn = lobby.DrawPerTurnOverride ?? GameRules.Default.DrawPerTurn, + SpHasCap = lobby.SpHasCapOverride ?? GameRules.Default.SpHasCap, + SpCap = lobby.SpCapOverride ?? GameRules.Default.SpCap, + BoardWidth = lobby.BoardWidthOverride ?? GameRules.Default.BoardWidth, + BoardHeight = lobby.BoardHeightOverride ?? GameRules.Default.BoardHeight, + HandSizeCap = lobby.HandSizeCapOverride ?? GameRules.Default.HandSizeCap, + DiscardOnMaxHand = lobby.DiscardOnMaxHandOverride ?? GameRules.Default.DiscardOnMaxHand, + MaxDeckSize = lobby.MaxDeckSizeOverride ?? GameRules.Default.MaxDeckSize, + MinDeckSize = lobby.MinDeckSizeOverride ?? GameRules.Default.MinDeckSize, + MaxArchTier1 = lobby.MaxArchTier1Override ?? GameRules.Default.MaxArchTier1, + TurnTimerSeconds = lobby.TurnTimerSecondsOverride ?? GameRules.Default.TurnTimerSeconds, + TimeLimitMinutes = lobby.TimeLimitMinutesOverride ?? GameRules.Default.TimeLimitMinutes, + TurnLimit = lobby.TurnLimitOverride ?? GameRules.Default.TurnLimit, + MpBuff = lobby.MpBuffOverride ?? GameRules.Default.MpBuff, + }; + + var session = new GameSession + { + PlayerOneAccountId = playerOneId, + PlayerOneDeckId = p1DeckId, + PlayerTwoAccountId = playerTwoId, + PlayerTwoDeckId = p2DeckId, + Status = GameSessionStatus.Initializing, + CreatedAt = DateTimeOffset.UtcNow, + RuleSnapshotJson = JsonSerializer.Serialize(rules), + }; + + _gameDb.GameSessions.Add(session); + + lobby.GameSessionId = session.Id; + lobby.Status = CustomLobbyStatus.Started; + + await _gameDb.SaveChangesAsync(ct); + + try + { + await _eventBus.PublishAsync( + NatsSubjects.GameStarted, + new GameStartedEvent( + session.Id, + new[] { playerOneId, playerTwoId }, + DateTimeOffset.UtcNow), + ct); + } + catch (Exception ex) + { + _logger.LogError(ex, + "Failed publishing game-started event for custom lobby session {SessionId}", + session.Id); + } + + // Push game-started notification to both players. + await Task.WhenAll( + _clientPush.PushAsync(playerOneId.ToString(), + ServerMessage.Push("game.custom.started", + new CustomLobbyGameStartedPush(session.Id, playerTwoId)), ct), + _clientPush.PushAsync(playerTwoId.ToString(), + ServerMessage.Push("game.custom.started", + new CustomLobbyGameStartedPush(session.Id, playerOneId)), ct)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameUnreadyHandler.cs b/Server/src/SOR.Game/Handlers/GameUnreadyHandler.cs new file mode 100644 index 0000000..f6c6317 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameUnreadyHandler.cs @@ -0,0 +1,66 @@ +namespace SOR.Game.Handlers; + +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.custom.lobby.unready — withdraw the calling player's ready status in a Full lobby. +/// +/// The caller's ready flag is cleared and a LobbyReadyStatusPush is sent to both participants. +/// +internal sealed class GameUnreadyHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameUnreadyHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.custom.lobby.unready"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var accountId = Guid.Parse(connection.UserId); + + var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct) + ?? throw new GameException("LOBBY_NOT_FOUND"); + + if (lobby.Status != CustomLobbyStatus.Full) + throw new GameException("LOBBY_NOT_FULL"); + + if (lobby.HostAccountId == accountId) + lobby.HostReady = false; + else if (lobby.GuestAccountId == accountId) + lobby.GuestReady = false; + else + throw new GameException("NOT_IN_LOBBY"); + + await _gameDb.SaveChangesAsync(ct); + + var readyPush = ServerMessage.Push("game.custom.lobby.ready_status", + new LobbyReadyStatusPush(lobby.Id, lobby.HostReady, lobby.GuestReady)); + + await Task.WhenAll( + _clientPush.PushAsync(lobby.HostAccountId.ToString(), readyPush, ct), + _clientPush.PushAsync(lobby.GuestAccountId!.Value.ToString(), readyPush, ct)); + + return ServerMessage.Reply("game.custom.lobby.unready.ack", message.Seq, + new UnreadyInLobbyResponse(LobbyId: lobby.Id)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameUpdateLobbyRulesHandler.cs b/Server/src/SOR.Game/Handlers/GameUpdateLobbyRulesHandler.cs new file mode 100644 index 0000000..11c7064 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameUpdateLobbyRulesHandler.cs @@ -0,0 +1,107 @@ +namespace SOR.Game.Handlers; + +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Push; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.custom.update_rules — host updates lobby rule overrides while in Full state. +/// +/// Only allowed when the lobby is Full and neither player is ready. +/// A LobbyUpdatedPush with the new effective rules is sent to both participants. +/// +internal sealed class GameUpdateLobbyRulesHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameUpdateLobbyRulesHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.custom.update_rules"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var accountId = Guid.Parse(connection.UserId); + + var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct) + ?? throw new GameException("LOBBY_NOT_FOUND"); + + if (lobby.Status != CustomLobbyStatus.Full) + throw new GameException("LOBBY_NOT_FULL"); + + if (lobby.HostAccountId != accountId) + throw new GameException("HOST_ONLY"); + + if (lobby.HostReady || lobby.GuestReady) + throw new GameException("CANNOT_CHANGE_RULES_WHILE_READY"); + + // Apply all overrides (null = revert to default). + var r = req.Rules; + lobby.OpeningHandSizeOverride = r.OpeningHandSize; + lobby.FirstPlayerSkipsDrawOverride = r.FirstPlayerSkipsDraw; + lobby.SpAccumulationPerTurnOverride = r.SpAccumulationPerTurn; + lobby.DrawPerTurnOverride = r.DrawPerTurn; + lobby.SpHasCapOverride = r.SpHasCap; + lobby.SpCapOverride = r.SpCap; + lobby.BoardWidthOverride = r.BoardWidth; + lobby.BoardHeightOverride = r.BoardHeight; + lobby.HandSizeCapOverride = r.HandSizeCap; + lobby.DiscardOnMaxHandOverride = r.DiscardOnMaxHand; + lobby.MaxDeckSizeOverride = r.MaxDeckSize; + lobby.MinDeckSizeOverride = r.MinDeckSize; + lobby.MaxArchTier1Override = r.MaxArchTier1; + lobby.TurnTimerSecondsOverride = r.TurnTimerSeconds; + lobby.TimeLimitMinutesOverride = r.TimeLimitMinutes; + lobby.TurnLimitOverride = r.TurnLimit; + lobby.MpBuffOverride = r.MpBuff; + + await _gameDb.SaveChangesAsync(ct); + + var effective = GameCreateCustomLobbyHandler.ToDto(new GameRules + { + OpeningHandSize = r.OpeningHandSize ?? GameRules.Default.OpeningHandSize, + FirstPlayerSkipsDraw = r.FirstPlayerSkipsDraw ?? GameRules.Default.FirstPlayerSkipsDraw, + SpAccumulationPerTurn = r.SpAccumulationPerTurn ?? GameRules.Default.SpAccumulationPerTurn, + DrawPerTurn = r.DrawPerTurn ?? GameRules.Default.DrawPerTurn, + SpHasCap = r.SpHasCap ?? GameRules.Default.SpHasCap, + SpCap = r.SpCap ?? GameRules.Default.SpCap, + BoardWidth = r.BoardWidth ?? GameRules.Default.BoardWidth, + BoardHeight = r.BoardHeight ?? GameRules.Default.BoardHeight, + HandSizeCap = r.HandSizeCap ?? GameRules.Default.HandSizeCap, + DiscardOnMaxHand = r.DiscardOnMaxHand ?? GameRules.Default.DiscardOnMaxHand, + MaxDeckSize = r.MaxDeckSize ?? GameRules.Default.MaxDeckSize, + MinDeckSize = r.MinDeckSize ?? GameRules.Default.MinDeckSize, + MaxArchTier1 = r.MaxArchTier1 ?? GameRules.Default.MaxArchTier1, + TurnTimerSeconds = r.TurnTimerSeconds ?? GameRules.Default.TurnTimerSeconds, + TimeLimitMinutes = r.TimeLimitMinutes ?? GameRules.Default.TimeLimitMinutes, + TurnLimit = r.TurnLimit ?? GameRules.Default.TurnLimit, + MpBuff = r.MpBuff ?? GameRules.Default.MpBuff, + }, lobby.Password != null); + + var updatedPush = ServerMessage.Push("game.custom.lobby_updated", + new LobbyUpdatedPush(lobby.Id, effective)); + + await Task.WhenAll( + _clientPush.PushAsync(lobby.HostAccountId.ToString(), updatedPush, ct), + _clientPush.PushAsync(lobby.GuestAccountId!.Value.ToString(), updatedPush, ct)); + + return ServerMessage.Reply("game.custom.update_rules.ack", message.Seq, + new UpdateLobbyRulesResponse(LobbyId: lobby.Id, Rules: effective)); + } +} diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs index d2be9cb..a2f1b83 100644 --- a/Server/src/SOR.Game/ServiceRegistration.cs +++ b/Server/src/SOR.Game/ServiceRegistration.cs @@ -57,6 +57,13 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + + // Ready-up handlers + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); // Spectator handlers services.AddTransient();