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
@@ -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;
}
}