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 <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-03-28 15:18:53 -04:00
co-authored by Claude Happy
parent 450c71544d
commit bd59904ce2
12 changed files with 968 additions and 8 deletions
@@ -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)
@@ -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: <name>] [<] 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()
+21
View File
@@ -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.
@@ -122,6 +122,12 @@ public sealed class CustomLobby
/// </summary>
public string? AdditionalPlayersJson { get; set; }
/// <summary>
/// Host-overridden seat → team assignments. JSON object mapping seat index (string key)
/// to team index (int). Null = default assignment (seat % teamCount).
/// </summary>
public string? TeamAssignmentsJson { get; set; }
// ── Timestamps ───────────────────────────────────────────────────────────
public DateTimeOffset CreatedAt { get; set; }
@@ -0,0 +1,521 @@
// <auto-generated />
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
{
/// <inheritdoc />
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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("Height")
.HasColumnType("integer");
b.Property<bool>("IsAvailableForCustom")
.HasColumnType("boolean");
b.Property<bool>("IsAvailableForRanked")
.HasColumnType("boolean");
b.Property<bool>("IsEnabled")
.HasColumnType("boolean");
b.Property<int>("MaxPlayers")
.HasColumnType("integer");
b.Property<int>("MinPlayers")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("StartingZonesJson")
.IsRequired()
.HasColumnType("jsonb");
b.Property<string>("TilesJson")
.IsRequired()
.HasColumnType("jsonb");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("Width")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("IsEnabled");
b.ToTable("board_templates", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AdditionalPlayersJson")
.HasColumnType("text")
.HasColumnName("additional_players_json");
b.Property<int?>("BoardHeightOverride")
.HasColumnType("integer");
b.Property<string>("BoardShapeOverride")
.HasColumnType("text");
b.Property<Guid?>("BoardTemplateIdOverride")
.HasColumnType("uuid");
b.Property<int?>("BoardWidthOverride")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool?>("DiscardOnMaxHandOverride")
.HasColumnType("boolean");
b.Property<int?>("DrawPerTurnOverride")
.HasColumnType("integer");
b.Property<bool?>("FirstPlayerSkipsDrawOverride")
.HasColumnType("boolean");
b.Property<string>("GameMode")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("FFA")
.HasColumnName("game_mode");
b.Property<Guid?>("GameSessionId")
.HasColumnType("uuid");
b.Property<Guid?>("GuestAccountId")
.HasColumnType("uuid");
b.Property<Guid?>("GuestDeckId")
.HasColumnType("uuid");
b.Property<string>("GuestFirstTurnPref")
.HasColumnType("text");
b.Property<bool>("GuestReady")
.HasColumnType("boolean");
b.Property<int?>("HandSizeCapOverride")
.HasColumnType("integer");
b.Property<Guid>("HostAccountId")
.HasColumnType("uuid");
b.Property<Guid>("HostDeckId")
.HasColumnType("uuid");
b.Property<string>("HostFirstTurnPref")
.HasColumnType("text");
b.Property<bool>("HostReady")
.HasColumnType("boolean");
b.Property<int?>("MaxArchTier1Override")
.HasColumnType("integer");
b.Property<int?>("MaxDeckSizeOverride")
.HasColumnType("integer");
b.Property<int>("MaxPlayers")
.HasColumnType("integer");
b.Property<int?>("MinDeckSizeOverride")
.HasColumnType("integer");
b.Property<int?>("MpBuffOverride")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("OpeningHandSizeOverride")
.HasColumnType("integer");
b.Property<string>("Password")
.HasColumnType("text");
b.Property<int?>("SpAccumulationPerTurnOverride")
.HasColumnType("integer");
b.Property<int?>("SpCapOverride")
.HasColumnType("integer");
b.Property<bool?>("SpHasCapOverride")
.HasColumnType("boolean");
b.Property<int?>("StartingRandomTilePctOverride")
.HasColumnType("integer");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<string>("TeamAssignmentsJson")
.HasColumnType("text");
b.Property<int>("TeamCount")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(1)
.HasColumnName("team_count");
b.Property<int?>("TimeLimitMinutesOverride")
.HasColumnType("integer");
b.Property<int?>("TurnLimitOverride")
.HasColumnType("integer");
b.Property<int?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ActionType")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("ActorAccountId")
.HasColumnType("uuid");
b.Property<Guid>("GameSessionId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("OccurredAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("PayloadJson")
.HasColumnType("jsonb")
.HasColumnName("payload");
b.Property<string>("ResultJson")
.HasColumnType("jsonb")
.HasColumnName("result");
b.Property<int>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("BoardHeight")
.HasColumnType("integer");
b.Property<Guid?>("BoardTemplateId")
.HasColumnType("uuid");
b.Property<int>("BoardWidth")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("DiscardOnMaxHand")
.HasColumnType("boolean");
b.Property<int>("DrawPerTurn")
.HasColumnType("integer");
b.Property<bool>("FirstPlayerSkipsDraw")
.HasColumnType("boolean");
b.Property<int>("HandSizeCap")
.HasColumnType("integer");
b.Property<bool>("IsCustomDefault")
.HasColumnType("boolean");
b.Property<bool>("IsRankedDefault")
.HasColumnType("boolean");
b.Property<int>("LoserOpReward")
.HasColumnType("integer");
b.Property<int>("MaxArchTier1")
.HasColumnType("integer");
b.Property<int>("MaxDeckSize")
.HasColumnType("integer");
b.Property<int>("MinDeckSize")
.HasColumnType("integer");
b.Property<int>("MpBuff")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("OpeningHandSize")
.HasColumnType("integer");
b.Property<int>("RankDiffOpMultiplierPct")
.HasColumnType("integer");
b.Property<int>("SpAccumulationPerTurn")
.HasColumnType("integer");
b.Property<int>("SpCap")
.HasColumnType("integer");
b.Property<bool>("SpHasCap")
.HasColumnType("boolean");
b.Property<int>("StartingRandomTilePct")
.HasColumnType("integer");
b.Property<int>("TimeLimitMinutes")
.HasColumnType("integer");
b.Property<int>("TurnLimit")
.HasColumnType("integer");
b.Property<int>("TurnTimerSeconds")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AdditionalPlayersJson")
.HasColumnType("text")
.HasColumnName("additional_players_json");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("EndedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("GameMode")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("FFA")
.HasColumnName("game_mode");
b.Property<DateTimeOffset?>("LastActionAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("PlayerCount")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(2)
.HasColumnName("player_count");
b.Property<Guid>("PlayerOneAccountId")
.HasColumnType("uuid");
b.Property<Guid>("PlayerOneDeckId")
.HasColumnType("uuid");
b.Property<bool>("PlayerOneReady")
.HasColumnType("boolean");
b.Property<Guid>("PlayerTwoAccountId")
.HasColumnType("uuid");
b.Property<Guid>("PlayerTwoDeckId")
.HasColumnType("uuid");
b.Property<bool>("PlayerTwoReady")
.HasColumnType("boolean");
b.Property<string>("RuleSnapshotJson")
.HasColumnType("jsonb")
.HasColumnName("rule_snapshot");
b.Property<DateTimeOffset?>("StartedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("StateJson")
.HasColumnType("jsonb")
.HasColumnName("state");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<string>("WinCondition")
.HasColumnType("text");
b.Property<Guid?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("OwnerAccountId")
.HasColumnType("uuid");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<Guid>("DeckId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("JoinedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("MatchedGameSessionId")
.HasColumnType("uuid");
b.Property<int>("RankScore")
.HasColumnType("integer");
b.Property<DateTimeOffset?>("ResolvedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("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
}
}
}
@@ -0,0 +1,30 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Game
{
/// <inheritdoc />
public partial class AddTeamAssignmentsToLobby : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "TeamAssignmentsJson",
schema: "game",
table: "custom_lobbies",
type: "text",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "TeamAssignmentsJson",
schema: "game",
table: "custom_lobbies");
}
}
}
@@ -187,6 +187,9 @@ namespace SOR.Database.Migrations.Game
.IsRequired()
.HasColumnType("text");
b.Property<string>("TeamAssignmentsJson")
.HasColumnType("text");
b.Property<int>("TeamCount")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
+14 -1
View File
@@ -206,6 +206,9 @@ public sealed record AcceptRuleSuggestionRequest(Guid LobbyId);
/// <summary>Host rejects the guest's pending rule suggestion.</summary>
public sealed record RejectRuleSuggestionRequest(Guid LobbyId);
/// <summary>Host-only: move a player seat to a different team.</summary>
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<AdditionalLobbyPlayerViewDto>? AdditionalPlayers = null);
IEnumerable<AdditionalLobbyPlayerViewDto>? AdditionalPlayers = null,
/// <summary>Seat index → team index map. Null = default (seat % teamCount).</summary>
Dictionary<int, int>? 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<int, int> SeatTeams);
public sealed record ListActiveLobbiesResponse(
IEnumerable<ActiveLobbyDto> Games,
int TotalCount,
@@ -453,6 +460,12 @@ public sealed record LobbyRuleSuggestionPush(
/// <summary>Pushed to the guest when the host rejects their rule suggestion.</summary>
public sealed record LobbyRuleSuggestionRejectedPush(Guid LobbyId);
/// <summary>
/// Pushed to all lobby participants when the host changes a seat's team assignment.
/// SeatTeams is the full seat → team map for all seats.
/// </summary>
public sealed record LobbyTeamAssignmentChangedPush(Guid LobbyId, Dictionary<int, int> SeatTeams);
/// <summary>
/// Pushed to each viewer after any game action that changes state.
/// Replaces the full <see cref="GameStateUpdatePush"/> for incremental updates.
@@ -14,11 +14,15 @@ public static class BoardShapeGenerator
/// </summary>
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
};
/// <summary>
@@ -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 };
}
/// <summary>
/// Decagonal radial board for 7–10 players.
/// A filled square central arena with up to 10 arms evenly spaced around it.
/// Only the first <paramref name="playerCount"/> 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°.
/// </summary>
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<string, Tile>();
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<int, HashSet<Coord>>();
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<Coord> { new Coord(tipX, tipY) };
}
return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones };
}
// ── Template-based board ──────────────────────────────────────────────────
/// <summary>
@@ -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));
}
}
@@ -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;
/// <summary>
/// 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 <see cref="LobbyTeamAssignmentChangedPush"/> to every current participant so
/// the lobby room can update team badges without requiring a full page refresh.
/// </summary>
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<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<ReassignTeamRequest>(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<Task>
{
_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<AdditionalLobbyPlayer[]>(
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));
}
/// <summary>
/// Deserialise the stored JSON into a seat → team dictionary, or build the default
/// (seat % teamCount) mapping when nothing has been stored yet.
/// </summary>
internal static Dictionary<int, int> DeserializeAssignments(
string? json, int maxPlayers, int teamCount)
{
if (json is not null)
{
try
{
var raw = JsonSerializer.Deserialize<Dictionary<string, int>>(json,
new JsonSerializerOptions(JsonSerializerDefaults.Web));
if (raw is not null)
{
var result = new Dictionary<int, int>();
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<int, int>();
for (int i = 0; i < maxPlayers; i++)
defaults[i] = teamCount <= 1 ? 0 : i % teamCount;
return defaults;
}
}
@@ -94,6 +94,9 @@ public static class ServiceRegistration
services.AddTransient<IMessageHandler, GameAcceptRuleSuggestionHandler>();
services.AddTransient<IMessageHandler, GameRejectRuleSuggestionHandler>();
// Team assignment handler (host reassigns seats to teams)
services.AddTransient<IMessageHandler, GameReassignTeamHandler>();
return services;
}
}