From bd59904ce2de91b2b5c7dd47e8c0ff57a9127361 Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 28 Mar 2026 15:18:53 -0400 Subject: [PATCH] Add Decagonal board shape, team reassignment, and multiplayer considerations - BoardShapeGenerator: add MakeDecagonal() for 7-10 players (10-armed radial, 11x11 arena, 21x21 total); AutoShape now routes 7-10 to Decagonal - CustomLobby: add TeamAssignmentsJson (seat -> team override map) - GameMessages: add ReassignTeamRequest/Response, LobbyTeamAssignmentChangedPush, SeatTeams field on JoinCustomLobbyResponse - GameReassignTeamHandler: new game.custom.reassign_team handler (host-only); pushes team_reassigned to all participants including additional players - EF migration: AddTeamAssignmentsToLobby (applied to pg-forge-01) - Client CustomLobby.gd: seat_teams state, reassign_team() action, push handler - lobby_room_screen.gd: _rebuild_team_controls() renders host-only [<] Tx [>] cycle buttons per seat in team modes; _team_label() reads seat_teams overrides - OVERALL.md: add Considerations for Later (fog of war, asymmetric teams, ranked ELO) 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 | 39 ++ .../scenes/free_play/lobby_room_screen.gd | 108 +++- OVERALL.md | 21 + .../SOR.Database/Entities/Game/CustomLobby.cs | 6 + ...4739_AddTeamAssignmentsToLobby.Designer.cs | 521 ++++++++++++++++++ ...0260328184739_AddTeamAssignmentsToLobby.cs | 30 + .../Game/GameDbContextModelSnapshot.cs | 3 + Server/src/SOR.Game/GameMessages.cs | 15 +- .../src/SOR.Game/Grid/BoardShapeGenerator.cs | 86 ++- .../Handlers/GameJoinCustomLobbyHandler.cs | 7 +- .../Handlers/GameReassignTeamHandler.cs | 137 +++++ Server/src/SOR.Game/ServiceRegistration.cs | 3 + 12 files changed, 968 insertions(+), 8 deletions(-) create mode 100644 Server/src/SOR.Database/Migrations/Game/20260328184739_AddTeamAssignmentsToLobby.Designer.cs create mode 100644 Server/src/SOR.Database/Migrations/Game/20260328184739_AddTeamAssignmentsToLobby.cs create mode 100644 Server/src/SOR.Game/Handlers/GameReassignTeamHandler.cs diff --git a/Client/origin-client/autoloads/CustomLobby.gd b/Client/origin-client/autoloads/CustomLobby.gd index 198844e..a4d6ab6 100644 --- a/Client/origin-client/autoloads/CustomLobby.gd +++ b/Client/origin-client/autoloads/CustomLobby.gd @@ -54,6 +54,9 @@ signal rule_suggestion_rejected ## Emitted when a lobby action is rejected gracefully (non-fatal), for lightweight UX toasts. signal lobby_notice(message: String) +## Pushed (or acked) when the host changes a seat's team assignment. +signal team_assignment_changed(seat_teams: Dictionary) + # ── State ───────────────────────────────────────────────────────────────────── var lobby_id : String = "" @@ -67,6 +70,8 @@ var first_turn_pref : String = "random" var max_players : int = 2 var game_mode : String = "FFA" var team_count : int = 1 +## Seat index → team index overrides. Empty = use default (seat % team_count). +var seat_teams : Dictionary = {} # ── Lifecycle ───────────────────────────────────────────────────────────────── @@ -87,6 +92,7 @@ func clear_state() -> void: max_players = 2 game_mode = "FFA" team_count = 1 + seat_teams = {} # ── Public actions ──────────────────────────────────────────────────────────── @@ -152,6 +158,13 @@ func join(lid: String, deck_id: String, password: String, lobby["guestDisplayName"] = str(d.get("guestDisplayName", "")) lobby["hasGuest"] = true lobby["additionalPlayers"] = d.get("additionalPlayers", []) + # Apply team assignments from join response if present. + var raw_st := d.get("seatTeams", null) + if raw_st != null: + seat_teams.clear() + for k in (raw_st as Dictionary): + seat_teams[int(k)] = int(raw_st[k]) + lobby["seatTeams"] = seat_teams if on_success.is_valid(): on_success.call(d), func(code: String, msg: String) -> void: print("[CustomLobby] ERR join ", code, " ", msg) @@ -290,6 +303,23 @@ func reject_rule_suggestion() -> void: func(code: String, msg: String) -> void: print("[CustomLobby] ERR reject_rule_suggestion ", code, " ", msg)) + +## Host-only: reassign a player seat to a different team. +func reassign_team(seat_index: int, team_index: int) -> void: + Network.request("game.custom.reassign_team", + { "lobbyId": lobby_id, "seatIndex": seat_index, "teamIndex": team_index }, + func(_t: String, p: Variant) -> void: + var d := p as Dictionary + var raw := d.get("seatTeams", {}) as Dictionary + seat_teams.clear() + for k in raw: + seat_teams[int(k)] = int(raw[k]) + lobby["seatTeams"] = seat_teams + team_assignment_changed.emit(seat_teams), + func(code: String, msg: String) -> void: + print("[CustomLobby] ERR reassign_team ", code, " ", msg)) + + # ── Private ─────────────────────────────────────────────────────────────────── func _on_server_push(type: String, payload: Variant) -> void: @@ -381,3 +411,12 @@ func _on_server_push(type: String, payload: Variant) -> void: "game.custom.lobby.rule_suggestion.rejected": rule_suggestion_rejected.emit() + + "game.custom.lobby.team_reassigned": + var d := payload as Dictionary + var raw := d.get("seatTeams", {}) as Dictionary + seat_teams.clear() + for k in raw: + seat_teams[int(k)] = int(raw[k]) + lobby["seatTeams"] = seat_teams + team_assignment_changed.emit(seat_teams) 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 63a66b5..878cb07 100644 --- a/Client/origin-client/scenes/free_play/lobby_room_screen.gd +++ b/Client/origin-client/scenes/free_play/lobby_room_screen.gd @@ -49,6 +49,7 @@ const RULES_DIALOG = preload("res://scenes/free_play/components/RulesEditorDialo var _first_turn_pref : String = "random" var _current_rules : Dictionary = {} +var _team_panel : VBoxContainer = null # dynamically added team-controls section # ── Lifecycle ───────────────────────────────────────────────────────────────── @@ -72,6 +73,7 @@ func _exit_tree() -> void: CustomLobby.rule_suggestion_received.disconnect(_on_rule_suggestion_received) CustomLobby.rule_suggestion_rejected.disconnect(_on_rule_suggestion_rejected) CustomLobby.lobby_notice.disconnect(_on_lobby_notice) + CustomLobby.team_assignment_changed.disconnect(_on_team_assignment_changed) # ── Setup ───────────────────────────────────────────────────────────────────── @@ -137,6 +139,7 @@ func _connect_signals() -> void: CustomLobby.rule_suggestion_received.connect(_on_rule_suggestion_received) CustomLobby.rule_suggestion_rejected.connect(_on_rule_suggestion_rejected) CustomLobby.lobby_notice.connect(_on_lobby_notice) + CustomLobby.team_assignment_changed.connect(_on_team_assignment_changed) # ── Refresh ─────────────────────────────────────────────────────────────────── @@ -173,6 +176,9 @@ func _refresh_display() -> void: # Additional players (3+) from lobby dict. _rebuild_additional_players_panel(lobby, max_players) + # Team assignment controls (host-only, team modes only). + _rebuild_team_controls(lobby, max_players, game_mode, team_count) + # Hide first-turn buttons for lobbies with more than 2 players (seat order is the turn order). var show_first_turn : bool = max_players <= 2 _first_turn_section.visible = show_first_turn @@ -230,7 +236,11 @@ func _rebuild_additional_players_panel(lobby: Dictionary, max_players: int) -> v func _team_label(game_mode: String, seat_index: int, team_count: int) -> String: if game_mode == "FFA" or team_count <= 1: return "" - var tidx : int = seat_index % team_count + var tidx : int + if CustomLobby.seat_teams.has(seat_index): + tidx = int(CustomLobby.seat_teams[seat_index]) + else: + tidx = seat_index % team_count return " [T%d]" % tidx @@ -249,6 +259,98 @@ func _make_player_slot_row(label_text: String, is_ready: bool) -> HBoxContainer: return hbox +## Rebuild the host-only team assignment panel (shown only in team game modes). +## Each row: "[Seat N: ] [<] T0 [>]" +func _rebuild_team_controls(lobby: Dictionary, max_players: int, + game_mode: String, team_count: int) -> void: + # Remove old panel if present. + if _team_panel != null and is_instance_valid(_team_panel): + _team_panel.queue_free() + _team_panel = null + + # Only show for host in non-FFA team games. + if not CustomLobby.is_host or game_mode == "FFA" or team_count <= 1: + return + + var panel := VBoxContainer.new() + panel.add_theme_constant_override("separation", 4) + + var header := Label.new() + header.text = "— Team Assignments —" + header.add_theme_font_size_override("font_size", 12) + header.modulate = Color(0.7, 0.7, 0.7) + panel.add_child(header) + + # Seat names: host = 0, guest = 1, additional = 2+ + var host_name : String = str(lobby.get("hostDisplayName", "Host")) + var guest_name : String = str(lobby.get("guestDisplayName", "Guest")) + var addl : Array = lobby.get("additionalPlayers", []) as Array + + for seat_index in range(max_players): + var seat_name : String + if seat_index == 0: + seat_name = host_name + elif seat_index == 1: + seat_name = guest_name + else: + var ap_idx : int = seat_index - 2 + if ap_idx < addl.size(): + var ap := addl[ap_idx] as Dictionary + seat_name = str(ap.get("displayName", "Player %d" % (seat_index + 1))) + else: + seat_name = "Seat %d" % (seat_index + 1) + + var current_team : int + if CustomLobby.seat_teams.has(seat_index): + current_team = int(CustomLobby.seat_teams[seat_index]) + else: + current_team = seat_index % team_count + + var row := HBoxContainer.new() + row.add_theme_constant_override("separation", 6) + + var name_lbl := Label.new() + name_lbl.text = "Seat %d (%s):" % [seat_index + 1, seat_name] + name_lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL + name_lbl.add_theme_font_size_override("font_size", 12) + + var prev_btn := Button.new() + prev_btn.text = "<" + prev_btn.custom_minimum_size = Vector2(24, 24) + + var team_lbl := Label.new() + team_lbl.text = "T%d" % current_team + team_lbl.add_theme_font_size_override("font_size", 12) + team_lbl.custom_minimum_size = Vector2(28, 0) + team_lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + + var next_btn := Button.new() + next_btn.text = ">" + next_btn.custom_minimum_size = Vector2(24, 24) + + # Capture values for the closures. + var captured_seat : int = seat_index + var captured_tc : int = team_count + prev_btn.pressed.connect(func(): + var t : int = int(CustomLobby.seat_teams.get(captured_seat, captured_seat % captured_tc)) + CustomLobby.reassign_team(captured_seat, (t - 1 + captured_tc) % captured_tc)) + next_btn.pressed.connect(func(): + var t : int = int(CustomLobby.seat_teams.get(captured_seat, captured_seat % captured_tc)) + CustomLobby.reassign_team(captured_seat, (t + 1) % captured_tc)) + + row.add_child(name_lbl) + row.add_child(prev_btn) + row.add_child(team_lbl) + row.add_child(next_btn) + panel.add_child(row) + + # Insert panel after the additional players container. + var parent := additional_players_container.get_parent() + if parent != null: + parent.add_child(panel) + _team_panel = panel + + 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) @@ -363,6 +465,10 @@ func _on_lobby_notice(message: String) -> void: _show_toast(message) +func _on_team_assignment_changed(_seat_teams: Dictionary) -> void: + _refresh_display() + + func _on_suggestion_accept_pressed() -> void: suggestion_banner.visible = false CustomLobby.accept_rule_suggestion() diff --git a/OVERALL.md b/OVERALL.md index e75457f..bfdfc95 100644 --- a/OVERALL.md +++ b/OVERALL.md @@ -116,3 +116,24 @@ - [ ] Delta identity decoupling: replace client-visible `accountId` usage in game wire payloads with session-scoped `playerRef` identifiers. - [ ] Server identity map: maintain authoritative `sessionId + playerRef -> accountId` mapping with strict invariants on join/reconnect/resume. - [ ] Logging/telemetry split: keep internal accountId linkage in server logs only; expose `playerRef` (and display name) in client-visible/debug payloads. + +--- + +## Considerations for Later + +These features are intentionally deferred — they require significant design work or depend on +other foundational systems not yet in place. + +- **Fog of War**: Restrict each player's board visibility to tiles/units within a defined sight + range. Requires a server-side visibility model (per-player tile sets), partial state + serialisation in game messages, and client-side fog overlay rendering. Non-trivial for + multiplayer without leaking hidden state. + +- **Asymmetric team sizes**: Allow lobbies where teams have different player counts (e.g. 3v1, + 2v1v1). Currently `teamCount` divides seats evenly. Requires a seat-to-team mapping override, + balancing rules, matchmaking weight adjustments, and UI to expose the configuration. + +- **Ranked multiplayer ELO**: Extend the ranked system to support multi-player ELO/MMR — rating + deltas when 3+ players participate in one match, handling partial concessions, and per-format + rating tracks (2v2, FFA, etc.). Requires consensus on the scoring algorithm and + anti-manipulation rules before implementation. diff --git a/Server/src/SOR.Database/Entities/Game/CustomLobby.cs b/Server/src/SOR.Database/Entities/Game/CustomLobby.cs index 6ab6790..5964ce4 100644 --- a/Server/src/SOR.Database/Entities/Game/CustomLobby.cs +++ b/Server/src/SOR.Database/Entities/Game/CustomLobby.cs @@ -122,6 +122,12 @@ public sealed class CustomLobby /// public string? AdditionalPlayersJson { get; set; } + /// + /// Host-overridden seat → team assignments. JSON object mapping seat index (string key) + /// to team index (int). Null = default assignment (seat % teamCount). + /// + public string? TeamAssignmentsJson { get; set; } + // ── Timestamps ─────────────────────────────────────────────────────────── public DateTimeOffset CreatedAt { get; set; } diff --git a/Server/src/SOR.Database/Migrations/Game/20260328184739_AddTeamAssignmentsToLobby.Designer.cs b/Server/src/SOR.Database/Migrations/Game/20260328184739_AddTeamAssignmentsToLobby.Designer.cs new file mode 100644 index 0000000..1d6f079 --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Game/20260328184739_AddTeamAssignmentsToLobby.Designer.cs @@ -0,0 +1,521 @@ +// +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("20260328184739_AddTeamAssignmentsToLobby")] + partial class AddTeamAssignmentsToLobby + { + /// + 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.BoardTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAvailableForCustom") + .HasColumnType("boolean"); + + b.Property("IsAvailableForRanked") + .HasColumnType("boolean"); + + b.Property("IsEnabled") + .HasColumnType("boolean"); + + b.Property("MaxPlayers") + .HasColumnType("integer"); + + b.Property("MinPlayers") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartingZonesJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("TilesJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IsEnabled"); + + b.ToTable("board_templates", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AdditionalPlayersJson") + .HasColumnType("text") + .HasColumnName("additional_players_json"); + + b.Property("BoardHeightOverride") + .HasColumnType("integer"); + + b.Property("BoardShapeOverride") + .HasColumnType("text"); + + b.Property("BoardTemplateIdOverride") + .HasColumnType("uuid"); + + 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("GameMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("FFA") + .HasColumnName("game_mode"); + + 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("StartingRandomTilePctOverride") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TeamAssignmentsJson") + .HasColumnType("text"); + + b.Property("TeamCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("team_count"); + + 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("BoardTemplateId") + .HasColumnType("uuid"); + + 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("StartingRandomTilePct") + .HasColumnType("integer"); + + 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("AdditionalPlayersJson") + .HasColumnType("text") + .HasColumnName("additional_players_json"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EndedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("GameMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("FFA") + .HasColumnName("game_mode"); + + b.Property("LastActionAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PlayerCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(2) + .HasColumnName("player_count"); + + 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/20260328184739_AddTeamAssignmentsToLobby.cs b/Server/src/SOR.Database/Migrations/Game/20260328184739_AddTeamAssignmentsToLobby.cs new file mode 100644 index 0000000..0607ff2 --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Game/20260328184739_AddTeamAssignmentsToLobby.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SOR.Database.Migrations.Game +{ + /// + public partial class AddTeamAssignmentsToLobby : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "TeamAssignmentsJson", + schema: "game", + table: "custom_lobbies", + type: "text", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "TeamAssignmentsJson", + 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 e3a1f4d..e3701a8 100644 --- a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs +++ b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs @@ -187,6 +187,9 @@ namespace SOR.Database.Migrations.Game .IsRequired() .HasColumnType("text"); + b.Property("TeamAssignmentsJson") + .HasColumnType("text"); + b.Property("TeamCount") .ValueGeneratedOnAdd() .HasColumnType("integer") diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index 82f154a..5dde313 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -206,6 +206,9 @@ public sealed record AcceptRuleSuggestionRequest(Guid LobbyId); /// Host rejects the guest's pending rule suggestion. public sealed record RejectRuleSuggestionRequest(Guid LobbyId); +/// Host-only: move a player seat to a different team. +public sealed record ReassignTeamRequest(Guid LobbyId, int SeatIndex, int TeamIndex); + // ── Responses ───────────────────────────────────────────────────────────────── public sealed record GameReadyResponse( @@ -273,7 +276,9 @@ public sealed record JoinCustomLobbyResponse( string GameMode, int TeamCount, bool IsAdditionalPlayer = false, // true for 3rd+ players (not host or first guest) - IEnumerable? AdditionalPlayers = null); + IEnumerable? AdditionalPlayers = null, + /// Seat index → team index map. Null = default (seat % teamCount). + Dictionary? SeatTeams = null); public sealed record LeaveCustomLobbyResponse(Guid LobbyId); @@ -319,6 +324,8 @@ public sealed record SuggestRulesResponse(Guid LobbyId); public sealed record AcceptRuleSuggestionResponse(Guid LobbyId); public sealed record RejectRuleSuggestionResponse(Guid LobbyId); +public sealed record ReassignTeamResponse(Guid LobbyId, Dictionary SeatTeams); + public sealed record ListActiveLobbiesResponse( IEnumerable Games, int TotalCount, @@ -453,6 +460,12 @@ public sealed record LobbyRuleSuggestionPush( /// Pushed to the guest when the host rejects their rule suggestion. public sealed record LobbyRuleSuggestionRejectedPush(Guid LobbyId); +/// +/// Pushed to all lobby participants when the host changes a seat's team assignment. +/// SeatTeams is the full seat → team map for all seats. +/// +public sealed record LobbyTeamAssignmentChangedPush(Guid LobbyId, Dictionary SeatTeams); + /// /// Pushed to each viewer after any game action that changes state. /// Replaces the full for incremental updates. diff --git a/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs b/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs index a1a8dc3..968f961 100644 --- a/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs +++ b/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs @@ -14,11 +14,15 @@ public static class BoardShapeGenerator /// public static string AutoShape(int playerCount) => playerCount switch { - 3 => "Triangular", - 4 => "Cross", - 5 => "RadialStar", - 6 => "HexRing", - _ => "Rectangle", // 2 and 7–10 + 3 => "Triangular", + 4 => "Cross", + 5 => "RadialStar", + 6 => "HexRing", + 7 => "Decagonal", + 8 => "Decagonal", + 9 => "Decagonal", + 10 => "Decagonal", + _ => "Rectangle", // 2 }; /// @@ -38,6 +42,7 @@ public static class BoardShapeGenerator "triangle" => "Triangular", // alias accepted from older/alternate clients "radialstar" => "RadialStar", "hexring" => "HexRing", + "decagonal" => "Decagonal", _ => "Rectangle", }; } @@ -52,6 +57,7 @@ public static class BoardShapeGenerator "Triangular" => MakeTriangular(rules), "RadialStar" => MakeRadialStar(rules), "HexRing" => MakeHexRing(rules), + "Decagonal" => MakeDecagonal(rules, playerCount), _ => MakeRectangle(rules, playerCount), }; } @@ -269,6 +275,76 @@ public static class BoardShapeGenerator return new Board { Width = board.Width, Height = board.Height, Tiles = board.Tiles, StartingZones = zones }; } + /// + /// Decagonal radial board for 7–10 players. + /// A filled square central arena with up to 10 arms evenly spaced around it. + /// Only the first arms are activated; the rest are omitted. + /// Arm tips in clockwise order starting at the bottom: 270°, 306°, 342°, 18°, 54°, 90°, + /// 126°, 162°, 198°, 234°. + /// + private static Board MakeDecagonal(GameRules rules, int playerCount) + { + const int armLen = 5; + const int arenaR = 5; // half-width of central square (11×11) + int center = arenaR * 2 + 1; // 11 + int total = center + armLen * 2; // 21 + + var tiles = new Dictionary(); + + int c = total / 2; + // Central arena + for (int x = c - arenaR; x <= c + arenaR; x++) + for (int y = c - arenaR; y <= c + arenaR; y++) + AddTile(tiles, x, y, rules.StartingRandomTilePct); + + // 10 arm directions evenly spaced at 36° each. + // Grid-approximated unit directions (dx, dy) — chosen so each arm has + // a non-degenerate path from the arena edge to its tip. + // Angles: 270°, 306°, 342°, 18°, 54°, 90°, 126°, 162°, 198°, 234° + (int dx, int dy)[] allDirs = + [ + ( 0, -1), // 0: 270° bottom + ( 1, -1), // 1: 306° lower-right diagonal + ( 1, 0), // 2: 342°/0° right + ( 1, 1), // 3: 54° upper-right diagonal + ( 0, 1), // 4: 90° top + (-1, 1), // 5: 126° upper-left diagonal + (-1, 0), // 6: 162°/180° left + (-1, -1), // 7: 198°/216° lower-left diagonal + // Two extra arms split the diagonal sectors for 9/10 players. + // These reuse adjacent diagonals with a slight offset (arm root shifted). + ( 1, -1), // 8: duplicate lower-right — arm rooted 2 cols right of center + (-1, 1), // 9: duplicate upper-left — arm rooted 2 cols left of center + ]; + + // Root offsets for arms 8 and 9 to avoid overlap with arms 1/5. + int[] rootOffsetX = [0, 0, 0, 0, 0, 0, 0, 0, 2, -2]; + int[] rootOffsetY = [0, 0, 0, 0, 0, 0, 0, 0, -2, 2]; + + int seats = Math.Clamp(playerCount, 7, 10); + var zones = new Dictionary>(); + + for (int seat = 0; seat < seats; seat++) + { + var (dx, dy) = allDirs[seat]; + int rx = c + rootOffsetX[seat]; + int ry = c + rootOffsetY[seat]; + int tipX = rx, tipY = ry; + for (int step = 1; step <= armLen; step++) + { + int ax = rx + dx * step; + int ay = ry + dy * step; + // Clamp to grid bounds. + if (ax < 0 || ax >= total || ay < 0 || ay >= total) break; + AddTile(tiles, ax, ay, rules.StartingRandomTilePct); + tipX = ax; tipY = ay; + } + zones[seat] = new HashSet { new Coord(tipX, tipY) }; + } + + return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones }; + } + // ── Template-based board ────────────────────────────────────────────────── /// diff --git a/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs b/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs index 4651d3b..8145a5f 100644 --- a/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs @@ -177,6 +177,10 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand notifyTasks.Add(_clientPush.PushAsync(ap.AccountId.ToString(), joinPush, ct)); await Task.WhenAll(notifyTasks); + var seatTeams = lobby.TeamAssignmentsJson is not null + ? GameReassignTeamHandler.DeserializeAssignments(lobby.TeamAssignmentsJson, lobby.MaxPlayers, lobby.TeamCount) + : null; + return ServerMessage.Reply("game.custom.join.ack", message.Seq, new JoinCustomLobbyResponse( LobbyId : lobby.Id, @@ -191,6 +195,7 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand GameMode : lobby.GameMode, TeamCount : lobby.TeamCount, IsAdditionalPlayer : !isFirstGuest, - AdditionalPlayers : additionalViews)); + AdditionalPlayers : additionalViews, + SeatTeams : seatTeams)); } } diff --git a/Server/src/SOR.Game/Handlers/GameReassignTeamHandler.cs b/Server/src/SOR.Game/Handlers/GameReassignTeamHandler.cs new file mode 100644 index 0000000..8c2e5bf --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameReassignTeamHandler.cs @@ -0,0 +1,137 @@ +namespace SOR.Game.Handlers; + +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Database.Entities.Game; +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.reassign_team — host-only action to change which team a seat belongs to. +/// +/// Allowed when the lobby is Open or Full and neither player is ready. +/// Pushes to every current participant so +/// the lobby room can update team badges without requiring a full page refresh. +/// +internal sealed class GameReassignTeamHandler : GameHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly GameDbContext _gameDb; + private readonly IClientPush _clientPush; + + public GameReassignTeamHandler( + IMessageSerializer serializer, + GameDbContext gameDb, + IClientPush clientPush) + { + _serializer = serializer; + _gameDb = gameDb; + _clientPush = clientPush; + } + + public string MessageType => "game.custom.reassign_team"; + + 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"); + + if (lobby.Status != CustomLobbyStatus.Open && lobby.Status != CustomLobbyStatus.Full) + throw new GameException("LOBBY_NOT_OPEN_OR_FULL"); + + if (lobby.HostReady || lobby.GuestReady) + throw new GameException("CANNOT_CHANGE_TEAMS_WHILE_READY"); + + if (req.SeatIndex < 0 || req.SeatIndex >= lobby.MaxPlayers) + throw new GameException("INVALID_SEAT"); + + if (lobby.TeamCount <= 1) + throw new GameException("NOT_A_TEAM_GAME"); + + if (req.TeamIndex < 0 || req.TeamIndex >= lobby.TeamCount) + throw new GameException("INVALID_TEAM"); + + var assignments = DeserializeAssignments(lobby.TeamAssignmentsJson, lobby.MaxPlayers, lobby.TeamCount); + assignments[req.SeatIndex] = req.TeamIndex; + lobby.TeamAssignmentsJson = JsonSerializer.Serialize(assignments); + + await _gameDb.SaveChangesAsync(ct); + + var push = ServerMessage.Push("game.custom.lobby.team_reassigned", + new LobbyTeamAssignmentChangedPush(lobby.Id, assignments)); + + var pushTasks = new List + { + _clientPush.PushAsync(lobby.HostAccountId.ToString(), push, ct), + }; + if (lobby.GuestAccountId.HasValue) + pushTasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), push, ct)); + + if (lobby.AdditionalPlayersJson is not null) + { + try + { + var extra = JsonSerializer.Deserialize( + lobby.AdditionalPlayersJson, + new JsonSerializerOptions(JsonSerializerDefaults.Web)); + if (extra is not null) + foreach (var ap in extra) + pushTasks.Add(_clientPush.PushAsync(ap.AccountId.ToString(), push, ct)); + } + catch { } + } + + await Task.WhenAll(pushTasks); + + return ServerMessage.Reply("game.custom.reassign_team.ack", message.Seq, + new ReassignTeamResponse(lobby.Id, assignments)); + } + + /// + /// Deserialise the stored JSON into a seat → team dictionary, or build the default + /// (seat % teamCount) mapping when nothing has been stored yet. + /// + internal static Dictionary DeserializeAssignments( + string? json, int maxPlayers, int teamCount) + { + if (json is not null) + { + try + { + var raw = JsonSerializer.Deserialize>(json, + new JsonSerializerOptions(JsonSerializerDefaults.Web)); + if (raw is not null) + { + var result = new Dictionary(); + foreach (var (k, v) in raw) + if (int.TryParse(k, out int seat)) + result[seat] = v; + // Fill any missing seats with default. + for (int i = 0; i < maxPlayers; i++) + if (!result.ContainsKey(i)) + result[i] = teamCount <= 1 ? 0 : i % teamCount; + return result; + } + } + catch { } + } + + var defaults = new Dictionary(); + for (int i = 0; i < maxPlayers; i++) + defaults[i] = teamCount <= 1 ? 0 : i % teamCount; + return defaults; + } +} diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs index 12f13dd..6239051 100644 --- a/Server/src/SOR.Game/ServiceRegistration.cs +++ b/Server/src/SOR.Game/ServiceRegistration.cs @@ -94,6 +94,9 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); + // Team assignment handler (host reassigns seats to teams) + services.AddTransient(); + return services; } }