diff --git a/Client/origin-client/autoloads/CustomLobby.gd b/Client/origin-client/autoloads/CustomLobby.gd index 54c860b..f4912e3 100644 --- a/Client/origin-client/autoloads/CustomLobby.gd +++ b/Client/origin-client/autoloads/CustomLobby.gd @@ -44,6 +44,13 @@ signal lobby_left ## reason is "host_cancelled" or "guest_left". signal partner_left(reason: String) +## Pushed to the host when the guest submits a rule suggestion. +## rules is the raw CustomRulesOverride dict (camelCase nullable fields). +signal rule_suggestion_received(rules: Dictionary) + +## Pushed to the guest when the host rejects their rule suggestion. +signal rule_suggestion_rejected + # ── State ───────────────────────────────────────────────────────────────────── var lobby_id : String = "" @@ -209,6 +216,34 @@ func vote_preset(accept: bool) -> void: func(code: String, msg: String) -> void: print("[CustomLobby] ERR vote_preset ", code, " ", msg)) + +## Guest-only: propose rule overrides to the host. rules_override is a camelCase dict +## of nullable fields (omit or null = keep server default). +func suggest_rules(rules_override: Dictionary) -> void: + Network.request("game.custom.suggest_rules", + { "lobbyId": lobby_id, "rules": rules_override }, + func(_t: String, _p: Variant) -> void: pass, + func(code: String, msg: String) -> void: + print("[CustomLobby] ERR suggest_rules ", code, " ", msg)) + + +## Host-only: accept the guest's pending rule suggestion and apply it. +func accept_rule_suggestion() -> void: + Network.request("game.custom.suggest_rules.accept", + { "lobbyId": lobby_id }, + func(_t: String, _p: Variant) -> void: pass, + func(code: String, msg: String) -> void: + print("[CustomLobby] ERR accept_rule_suggestion ", code, " ", msg)) + + +## Host-only: reject the guest's pending rule suggestion. +func reject_rule_suggestion() -> void: + Network.request("game.custom.suggest_rules.reject", + { "lobbyId": lobby_id }, + func(_t: String, _p: Variant) -> void: pass, + func(code: String, msg: String) -> void: + print("[CustomLobby] ERR reject_rule_suggestion ", code, " ", msg)) + # ── Private ─────────────────────────────────────────────────────────────────── func _on_server_push(type: String, payload: Variant) -> void: @@ -265,3 +300,11 @@ func _on_server_push(type: String, payload: Variant) -> void: var reason : String = str(d.get("reason", "")) clear_state() partner_left.emit(reason) + + "game.custom.lobby.rule_suggestion": + var d := payload as Dictionary + var rules := d.get("suggestedRules", {}) as Dictionary + rule_suggestion_received.emit(rules) + + "game.custom.lobby.rule_suggestion.rejected": + rule_suggestion_rejected.emit() diff --git a/Client/origin-client/scenes/free_play/LobbyRoomScreen.tscn b/Client/origin-client/scenes/free_play/LobbyRoomScreen.tscn index e2b30c9..bca90df 100644 --- a/Client/origin-client/scenes/free_play/LobbyRoomScreen.tscn +++ b/Client/origin-client/scenes/free_play/LobbyRoomScreen.tscn @@ -83,6 +83,43 @@ unique_name_in_owner = true layout_mode = 2 text = "No" +[node name="SuggestionBanner" type="PanelContainer" parent="Layout"] +unique_name_in_owner = true +layout_mode = 2 +visible = false + +[node name="SuggestionInner" type="VBoxContainer" parent="Layout/SuggestionBanner"] +layout_mode = 2 +theme_override_constants/separation = 6 + +[node name="SuggestionLabel" type="Label" parent="Layout/SuggestionBanner/SuggestionInner"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +text = "Guest suggested rule changes:" + +[node name="SuggestionRulesLabel" type="Label" parent="Layout/SuggestionBanner/SuggestionInner"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +autowrap_mode = 3 +modulate = Color(0.85, 0.85, 0.85, 1.0) +text = "" + +[node name="SuggestionBtns" type="HBoxContainer" parent="Layout/SuggestionBanner/SuggestionInner"] +layout_mode = 2 +theme_override_constants/separation = 8 + +[node name="SuggestionAcceptBtn" type="Button" parent="Layout/SuggestionBanner/SuggestionInner/SuggestionBtns"] +unique_name_in_owner = true +layout_mode = 2 +text = "Accept" + +[node name="SuggestionRejectBtn" type="Button" parent="Layout/SuggestionBanner/SuggestionInner/SuggestionBtns"] +unique_name_in_owner = true +layout_mode = 2 +text = "Reject" + [node name="MainSplit" type="HSplitContainer" parent="Layout"] layout_mode = 2 size_flags_vertical = 3 @@ -239,7 +276,7 @@ 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" +text = "Edit / Suggest Rules" [node name="PresetSep" type="HSeparator" parent="Layout/MainSplit/RightPanel/RightContent/RightMargin/RightInner"] layout_mode = 2 diff --git a/Client/origin-client/scenes/free_play/lobby_room_screen.gd b/Client/origin-client/scenes/free_play/lobby_room_screen.gd index 8db5b0c..9fc82d9 100644 --- a/Client/origin-client/scenes/free_play/lobby_room_screen.gd +++ b/Client/origin-client/scenes/free_play/lobby_room_screen.gd @@ -26,14 +26,18 @@ extends Control @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 +@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 suggestion_banner : PanelContainer = %SuggestionBanner +@onready var suggestion_rules_label : Label = %SuggestionRulesLabel +@onready var suggestion_accept_btn : Button = %SuggestionAcceptBtn +@onready var suggestion_reject_btn : Button = %SuggestionRejectBtn +@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 ───────────────────────────────────────────────────────────────────── @@ -58,6 +62,8 @@ func _exit_tree() -> void: CustomLobby.preset_vote_rejected.disconnect(_on_preset_vote_rejected) CustomLobby.lobby_left.disconnect(_on_lobby_left) CustomLobby.partner_left.disconnect(_on_partner_left) + CustomLobby.rule_suggestion_received.disconnect(_on_rule_suggestion_received) + CustomLobby.rule_suggestion_rejected.disconnect(_on_rule_suggestion_rejected) # ── Setup ───────────────────────────────────────────────────────────────────── @@ -88,8 +94,9 @@ func _setup_ui() -> void: first_random_btn.button_pressed = true _first_turn_pref = "random" - # Host-only controls - edit_rules_btn.visible = CustomLobby.is_host + # Edit/Suggest Rules button — host edits directly, guest suggests + edit_rules_btn.text = "Edit Rules" if CustomLobby.is_host else "Suggest Rules" + edit_rules_btn.visible = true # both roles can open the editor save_preset_btn.visible = CustomLobby.is_host load_preset_btn.visible = CustomLobby.is_host @@ -101,6 +108,10 @@ func _setup_ui() -> void: vote_no_btn.pressed.connect(func(): CustomLobby.vote_preset(false)) vote_banner.visible = false + suggestion_accept_btn.pressed.connect(_on_suggestion_accept_pressed) + suggestion_reject_btn.pressed.connect(_on_suggestion_reject_pressed) + suggestion_banner.visible = false + deck_picker_dialog.confirmed.connect(_on_deck_picker_confirmed) preset_list_dialog.confirmed.connect(_on_preset_confirmed) @@ -115,6 +126,8 @@ func _connect_signals() -> void: CustomLobby.preset_vote_rejected.connect(_on_preset_vote_rejected) CustomLobby.lobby_left.connect(_on_lobby_left) CustomLobby.partner_left.connect(_on_partner_left) + CustomLobby.rule_suggestion_received.connect(_on_rule_suggestion_received) + CustomLobby.rule_suggestion_rejected.connect(_on_rule_suggestion_rejected) # ── Refresh ─────────────────────────────────────────────────────────────────── @@ -163,7 +176,7 @@ func _update_ready_indicators(host_ready: bool, guest_ready: bool) -> void: first_opp_btn.disabled = CustomLobby.i_am_ready first_random_btn.disabled = CustomLobby.i_am_ready - # Lock edit rules if anyone is ready + # Lock edit/suggest rules if anyone is ready edit_rules_btn.disabled = CustomLobby.i_am_ready or CustomLobby.partner_ready @@ -236,6 +249,56 @@ func _on_preset_vote_rejected(_lid: String, _pid: String) -> void: _show_toast("Preset rejected") +func _on_rule_suggestion_received(rules: Dictionary) -> void: + # Shown to the host — display a summary and Accept/Reject buttons. + suggestion_rules_label.text = _format_rules_summary(rules) + suggestion_banner.visible = true + + +func _on_rule_suggestion_rejected() -> void: + _show_toast("Host rejected your rule suggestion.") + + +func _on_suggestion_accept_pressed() -> void: + suggestion_banner.visible = false + CustomLobby.accept_rule_suggestion() + + +func _on_suggestion_reject_pressed() -> void: + suggestion_banner.visible = false + CustomLobby.reject_rule_suggestion() + + +## Returns a compact human-readable summary of a rules dict (camelCase keys, nullable values). +func _format_rules_summary(rules: Dictionary) -> String: + if rules.is_empty(): + return "(default rules)" + var labels := { + "openingHandSize": "Opening Hand", + "drawPerTurn": "Draw/Turn", + "spAccumulationPerTurn": "SP/Turn", + "spHasCap": "SP Cap", + "spCap": "SP Cap Value", + "handSizeCap": "Hand Cap", + "discardOnMaxHand": "Discard on Max Hand", + "turnTimerSeconds": "Turn Timer (s)", + "timeLimitMinutes": "Time Limit (min)", + "turnLimit": "Turn Limit", + "mpBuff": "MP Buff", + "boardWidth": "Board W", + "boardHeight": "Board H", + "firstPlayerSkipsDraw": "1st Player Skips Draw", + "minDeckSize": "Min Deck", + "maxDeckSize": "Max Deck", + "maxArchTier1": "Max Arch Tier-1", + } + var lines : PackedStringArray = [] + for key in labels: + if rules.has(key) and rules[key] != null: + lines.append("%s: %s" % [labels[key], rules[key]]) + return "\n".join(lines) if not lines.is_empty() else "(no changes)" + + func _on_lobby_left() -> void: get_tree().change_scene_to_file("res://scenes/free_play/FreePlayScreen.tscn") @@ -285,7 +348,166 @@ func _on_deck_picker_confirmed() -> void: func _on_edit_rules_pressed() -> void: - OS.alert("Rules editor: use the preset system or rejoin with custom rules.", "Edit Rules") + _open_rules_editor() + + +## Builds and shows a modal rules editor popup. +## Host: "Apply" commits the new overrides directly. +## Guest: "Suggest" sends them to the host for approval. +func _open_rules_editor() -> void: + var is_host := CustomLobby.is_host + var win := Window.new() + win.title = "Edit Rules" if is_host else "Suggest Rules" + win.initial_position = Window.WINDOW_INITIAL_POSITION_CENTER_MAIN_WINDOW_SCREEN + win.size = Vector2i(480, 600) + win.exclusive = true + + var root_vbox := VBoxContainer.new() + root_vbox.set_anchors_preset(Control.PRESET_FULL_RECT) + root_vbox.add_theme_constant_override("separation", 0) + win.add_child(root_vbox) + + # Scrollable field area + var scroll := ScrollContainer.new() + scroll.size_flags_vertical = Control.SIZE_EXPAND_FILL + root_vbox.add_child(scroll) + + var inner_margin := MarginContainer.new() + for side in ["margin_left", "margin_right", "margin_top", "margin_bottom"]: + inner_margin.add_theme_constant_override(side, 12) + inner_margin.size_flags_horizontal = Control.SIZE_EXPAND_FILL + scroll.add_child(inner_margin) + + var inner := VBoxContainer.new() + inner.size_flags_horizontal = Control.SIZE_EXPAND_FILL + inner.add_theme_constant_override("separation", 8) + inner_margin.add_child(inner) + + # Collect controls keyed by camelCase field name + var controls : Dictionary = {} + var r := _current_rules + + # Value helpers — read current effective value or fall back to game default + var get_i := func(k: String, d: int) -> int: + return int(r[k]) if r.has(k) else d + var get_b := func(k: String, d: bool) -> bool: + return bool(r[k]) if r.has(k) else d + + # Row builders + var add_int := func(label: String, key: String, min_v: int, max_v: int, def_v: int, note: String) -> void: + var hbox := HBoxContainer.new() + var lbl := Label.new() + lbl.text = label + lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL + if note != "": + lbl.tooltip_text = note + hbox.add_child(lbl) + var spin := SpinBox.new() + spin.min_value = min_v + spin.max_value = max_v + spin.value = get_i.call(key, def_v) + spin.custom_minimum_size = Vector2(90, 0) + hbox.add_child(spin) + inner.add_child(hbox) + controls[key] = spin + + var add_bool := func(label: String, key: String, def_v: bool) -> void: + var hbox := HBoxContainer.new() + var lbl := Label.new() + lbl.text = label + lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL + hbox.add_child(lbl) + var chk := CheckBox.new() + chk.button_pressed = get_b.call(key, def_v) + hbox.add_child(chk) + inner.add_child(hbox) + controls[key] = chk + + # ── Hand & Cards ────────────────────────────────────────────────────────── + _section_label(inner, "HAND & CARDS") + add_int.call("Opening Hand Size", "openingHandSize", 1, 20, 6, "") + add_int.call("Draw Per Turn", "drawPerTurn", 1, 10, 1, "") + add_int.call("Hand Size Cap", "handSizeCap", 0, 20, 0, "0 = no cap") + add_bool.call("Discard on Max Hand", "discardOnMaxHand", false) + + # ── SP ───────────────────────────────────────────────────────────────────── + _section_label(inner, "SP") + add_int.call("SP Per Turn", "spAccumulationPerTurn", 1, 20, 3, "") + add_bool.call("SP Has Cap", "spHasCap", false) + add_int.call("SP Cap", "spCap", 1, 100, 10, "") + + # ── Timers & Limits ──────────────────────────────────────────────────────── + _section_label(inner, "TIMERS & LIMITS") + add_int.call("Turn Timer (s)", "turnTimerSeconds", 0, 300, 0, "0 = no timer") + add_int.call("Time Limit (min)", "timeLimitMinutes", 0, 120, 0, "0 = no limit") + add_int.call("Turn Limit", "turnLimit", 0, 200, 0, "0 = no limit") + + # ── Board ────────────────────────────────────────────────────────────────── + _section_label(inner, "BOARD") + add_int.call("Board Width", "boardWidth", 3, 12, 6, "") + add_int.call("Board Height", "boardHeight", 3, 12, 6, "") + + # ── Deck ─────────────────────────────────────────────────────────────────── + _section_label(inner, "DECK") + add_int.call("Min Deck Size", "minDeckSize", 0, 60, 0, "0 = no limit") + add_int.call("Max Deck Size", "maxDeckSize", 0, 120, 0, "0 = no limit") + add_int.call("Max Arch Tier-1", "maxArchTier1", 0, 10, 0, "0 = no limit") + + # ── Misc ─────────────────────────────────────────────────────────────────── + _section_label(inner, "MISC") + add_bool.call("First Player Skips Draw","firstPlayerSkipsDraw", false) + add_int.call("MP Buff Per Turn", "mpBuff", 0, 20, 0, "Flat MP added to each unit at turn start") + + # ── Footer ───────────────────────────────────────────────────────────────── + root_vbox.add_child(HSeparator.new()) + + var footer_margin := MarginContainer.new() + for side in ["margin_left", "margin_right", "margin_top", "margin_bottom"]: + footer_margin.add_theme_constant_override(side, 8) + root_vbox.add_child(footer_margin) + + var btn_row := HBoxContainer.new() + btn_row.add_theme_constant_override("separation", 8) + footer_margin.add_child(btn_row) + + var spacer := Control.new() + spacer.size_flags_horizontal = Control.SIZE_EXPAND_FILL + btn_row.add_child(spacer) + + var cancel_btn := Button.new() + cancel_btn.text = "Cancel" + cancel_btn.pressed.connect(func(): win.queue_free()) + btn_row.add_child(cancel_btn) + + var confirm_btn := Button.new() + confirm_btn.text = "Apply" if is_host else "Suggest" + confirm_btn.pressed.connect(func(): + var overrides := {} + for key in controls: + var ctrl = controls[key] + if ctrl is SpinBox: + overrides[key] = int(ctrl.value) + elif ctrl is CheckBox: + overrides[key] = ctrl.button_pressed + win.queue_free() + if is_host: + CustomLobby.update_rules(overrides) + else: + CustomLobby.suggest_rules(overrides)) + btn_row.add_child(confirm_btn) + + add_child(win) + win.popup() + + +## Inserts a small section heading into an inner VBoxContainer. +func _section_label(container: VBoxContainer, title: String) -> void: + container.add_child(HSeparator.new()) + var lbl := Label.new() + lbl.text = title + lbl.modulate = Color(0.6, 0.6, 0.65) + lbl.add_theme_font_size_override("font_size", 11) + container.add_child(lbl) func _on_save_preset_pressed() -> void: diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index 4172cc1..ad40cbf 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -176,6 +176,17 @@ public sealed record UpdateLobbyRulesRequest(Guid LobbyId, CustomRulesOverride R /// List all in-progress custom games (Status == Started). Supports paging. public sealed record ListActiveLobbiesRequest(int Page = 1, int PageSize = 20); +// ── Rule suggestion requests (guest → host) ─────────────────────────────────── + +/// Guest proposes rule overrides to the host. Host can accept or reject. +public sealed record SuggestRulesRequest(Guid LobbyId, CustomRulesOverride Rules); + +/// Host accepts the guest's pending rule suggestion; applies it as the new overrides. +public sealed record AcceptRuleSuggestionRequest(Guid LobbyId); + +/// Host rejects the guest's pending rule suggestion. +public sealed record RejectRuleSuggestionRequest(Guid LobbyId); + // ── Responses ───────────────────────────────────────────────────────────────── public sealed record GameReadyResponse(Guid SessionId, string Status); @@ -265,6 +276,10 @@ public sealed record ChangeLobbyDeckResponse(Guid LobbyId); public sealed record UpdateLobbyRulesResponse(Guid LobbyId, CustomRulesDto Rules); +public sealed record SuggestRulesResponse(Guid LobbyId); +public sealed record AcceptRuleSuggestionResponse(Guid LobbyId); +public sealed record RejectRuleSuggestionResponse(Guid LobbyId); + public sealed record ListActiveLobbiesResponse( IEnumerable Games, int TotalCount, @@ -354,6 +369,18 @@ public sealed record LobbyDeckChangedPush(Guid LobbyId, Guid AccountId, Guid Dec /// public sealed record LobbyPartnerLeftPush(Guid LobbyId, string Reason); +/// +/// Pushed to the host when the guest submits a rule suggestion. +/// The host can accept (game.custom.suggest_rules.accept) or reject (game.custom.suggest_rules.reject). +/// +public sealed record LobbyRuleSuggestionPush( + Guid LobbyId, + Guid SuggesterAccountId, + CustomRulesOverride SuggestedRules); + +/// Pushed to the guest when the host rejects their rule suggestion. +public sealed record LobbyRuleSuggestionRejectedPush(Guid LobbyId); + // ── DTOs ───────────────────────────────────────────────────────────────────── /// diff --git a/Server/src/SOR.Game/Handlers/GameAcceptRuleSuggestionHandler.cs b/Server/src/SOR.Game/Handlers/GameAcceptRuleSuggestionHandler.cs new file mode 100644 index 0000000..83a540f --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameAcceptRuleSuggestionHandler.cs @@ -0,0 +1,114 @@ +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.suggest_rules.accept — host accepts the guest's pending rule suggestion. +/// +/// Applies the suggested overrides to the lobby entity (same logic as GameUpdateLobbyRulesHandler), +/// clears the pending suggestion, and pushes LobbyUpdatedPush to both participants. +/// +internal sealed class GameAcceptRuleSuggestionHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + private readonly RuleSuggestionService _suggestions; + + public GameAcceptRuleSuggestionHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush, + RuleSuggestionService suggestions) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + _suggestions = suggestions; + } + + public string MessageType => "game.custom.suggest_rules.accept"; + + 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"); + + var suggestion = _suggestions.Get(lobby.Id) + ?? throw new GameException("NO_PENDING_SUGGESTION"); + + // Apply overrides (same mapping as GameUpdateLobbyRulesHandler). + var r = suggestion.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); + _suggestions.Remove(lobby.Id); + + 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.suggest_rules.accept.ack", message.Seq, + new AcceptRuleSuggestionResponse(lobby.Id)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameRejectRuleSuggestionHandler.cs b/Server/src/SOR.Game/Handlers/GameRejectRuleSuggestionHandler.cs new file mode 100644 index 0000000..954bf72 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameRejectRuleSuggestionHandler.cs @@ -0,0 +1,62 @@ +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.suggest_rules.reject — host rejects the guest's pending rule suggestion. +/// +/// Clears the pending suggestion and pushes LobbyRuleSuggestionRejectedPush to the guest. +/// +internal sealed class GameRejectRuleSuggestionHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + private readonly RuleSuggestionService _suggestions; + + public GameRejectRuleSuggestionHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush, + RuleSuggestionService suggestions) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + _suggestions = suggestions; + } + + public string MessageType => "game.custom.suggest_rules.reject"; + + 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.HostAccountId != accountId) + throw new GameException("HOST_ONLY"); + + _suggestions.Remove(lobby.Id); + + if (lobby.GuestAccountId.HasValue) + await _clientPush.PushAsync( + lobby.GuestAccountId.Value.ToString(), + ServerMessage.Push("game.custom.lobby.rule_suggestion.rejected", + new LobbyRuleSuggestionRejectedPush(lobby.Id)), + ct); + + return ServerMessage.Reply("game.custom.suggest_rules.reject.ack", message.Seq, + new RejectRuleSuggestionResponse(lobby.Id)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameSuggestRulesHandler.cs b/Server/src/SOR.Game/Handlers/GameSuggestRulesHandler.cs new file mode 100644 index 0000000..97ff629 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameSuggestRulesHandler.cs @@ -0,0 +1,70 @@ +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.suggest_rules — guest proposes rule overrides to the host. +/// +/// Only allowed when the lobby is Full and neither player is ready. +/// The host receives a LobbyRuleSuggestionPush and can accept or reject via +/// game.custom.suggest_rules.accept / .reject. +/// Any previous pending suggestion for the same lobby is replaced. +/// +internal sealed class GameSuggestRulesHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + private readonly RuleSuggestionService _suggestions; + + public GameSuggestRulesHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush, + RuleSuggestionService suggestions) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + _suggestions = suggestions; + } + + public string MessageType => "game.custom.suggest_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.GuestAccountId != accountId) + throw new GameException("GUEST_ONLY"); + + if (lobby.HostReady || lobby.GuestReady) + throw new GameException("CANNOT_SUGGEST_WHILE_READY"); + + _suggestions.Upsert(lobby.Id, new PendingSuggestion(lobby.Id, accountId, req.Rules)); + + await _clientPush.PushAsync( + lobby.HostAccountId.ToString(), + ServerMessage.Push("game.custom.lobby.rule_suggestion", + new LobbyRuleSuggestionPush(lobby.Id, accountId, req.Rules)), + ct); + + return ServerMessage.Reply("game.custom.suggest_rules.ack", message.Seq, + new SuggestRulesResponse(lobby.Id)); + } +} diff --git a/Server/src/SOR.Game/RuleSuggestionService.cs b/Server/src/SOR.Game/RuleSuggestionService.cs new file mode 100644 index 0000000..8cde896 --- /dev/null +++ b/Server/src/SOR.Game/RuleSuggestionService.cs @@ -0,0 +1,29 @@ +namespace SOR.Game; + +using System.Collections.Concurrent; + +/// +/// In-memory store for pending guest rule suggestions, one active suggestion per lobby. +/// Thread-safe; suggestions are ephemeral and lost on restart (acceptable — they are +/// short-lived lobby interactions). +/// +internal sealed record PendingSuggestion( + Guid LobbyId, + Guid SuggesterAccountId, + CustomRulesOverride Rules); + +internal sealed class RuleSuggestionService +{ + private readonly ConcurrentDictionary _pending = new(); + + /// Adds or replaces the pending suggestion for a lobby. + public void Upsert(Guid lobbyId, PendingSuggestion suggestion) => + _pending[lobbyId] = suggestion; + + /// Returns the pending suggestion for a lobby, or null if none. + public PendingSuggestion? Get(Guid lobbyId) => + _pending.TryGetValue(lobbyId, out var s) ? s : null; + + /// Removes the pending suggestion for a lobby. + public void Remove(Guid lobbyId) => _pending.TryRemove(lobbyId, out _); +} diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs index a2f1b83..8a8b503 100644 --- a/Server/src/SOR.Game/ServiceRegistration.cs +++ b/Server/src/SOR.Game/ServiceRegistration.cs @@ -79,6 +79,14 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); + // Rule suggestion service (in-memory, one pending suggestion per lobby at a time). + services.AddSingleton(); + + // Rule suggestion handlers (guest proposes → host accepts or rejects) + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + return services; } }