Implement multiplayer extension: 2-10 players FFA/Team/Multi-Team
Core engine: - Add SeatIndex, TeamIndex, IsEliminated to PlayerState - Add SeatOrder, GameMode to GameState with helpers: ActiveSeats(), GetNextActiveSeat(), GetEnemyIds(), AreAllies() - Add StartingZones to Board for per-seat placement validation - Add BoardShape, PlayerCount to GameRules - New BoardShapeGenerator: Rectangle (up to 4 seats) + Cross shapes - N-player Initialize() overload; old 2-player overload delegates to it - EndTurn uses GetNextActiveSeat() instead of hardcoded GetOpponentId() - Attack finds target across all enemy players; EliminatePlayer() helper allows multi-player elimination without immediate game over - PlaceArchSpirit validates via StartingZones (legacy row fallback preserved) - AbilitySystem.Own() uses AreAllies() for team-aware ownership checks Database: - GameSession: +player_count, +game_mode, +additional_players_json - CustomLobby: +game_mode, +team_count, +additional_players_json - EF migration: AddMultiplayerSlots (applied) Handlers: - GameCreateCustomLobbyHandler: honours MaxPlayers/GameMode/TeamCount from request - GameJoinCustomLobbyHandler: multi-slot join up to MaxPlayers - GameLobbyReadyHandler: N-player all-ready check; seats/team assignment by mode - GameReadyHandler: builds N-player list from AdditionalPlayersJson - GameHandlerBase.LoadActiveSessionAsync: recognises additional players Client: - Game.gd: get_opponents() returns all non-local players; get_opponent() kept as backward-compat alias returning first opponent 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:
@@ -50,6 +50,9 @@ public sealed class GameDbContext : DbContext
|
||||
e.Property(s => s.Status).HasConversion<string>();
|
||||
e.Property(s => s.StateJson).HasColumnType("jsonb").HasColumnName("state");
|
||||
e.Property(s => s.RuleSnapshotJson).HasColumnType("jsonb").HasColumnName("rule_snapshot");
|
||||
e.Property(s => s.PlayerCount).HasColumnName("player_count").HasDefaultValue(2);
|
||||
e.Property(s => s.GameMode).HasColumnName("game_mode").HasDefaultValue("FFA");
|
||||
e.Property(s => s.AdditionalPlayersJson).HasColumnName("additional_players_json");
|
||||
e.HasIndex(s => s.PlayerOneAccountId);
|
||||
e.HasIndex(s => s.PlayerTwoAccountId);
|
||||
e.HasIndex(s => new { s.Status, s.CreatedAt });
|
||||
@@ -84,6 +87,9 @@ public sealed class GameDbContext : DbContext
|
||||
e.ToTable("custom_lobbies");
|
||||
e.HasKey(l => l.Id);
|
||||
e.Property(l => l.Status).HasConversion<string>();
|
||||
e.Property(l => l.GameMode).HasColumnName("game_mode").HasDefaultValue("FFA");
|
||||
e.Property(l => l.TeamCount).HasColumnName("team_count").HasDefaultValue(1);
|
||||
e.Property(l => l.AdditionalPlayersJson).HasColumnName("additional_players_json");
|
||||
e.HasIndex(l => new { l.Status, l.CreatedAt });
|
||||
e.HasIndex(l => l.HostAccountId);
|
||||
});
|
||||
|
||||
@@ -97,9 +97,22 @@ public sealed class CustomLobby
|
||||
/// <summary>Guest's first-turn preference: "host" | "guest" | "random" | null.</summary>
|
||||
public string? GuestFirstTurnPref { get; set; }
|
||||
|
||||
/// <summary>Maximum number of players. Default 2; stub for future N-player support.</summary>
|
||||
/// <summary>Maximum number of players. Default 2.</summary>
|
||||
public int MaxPlayers { get; set; } = 2;
|
||||
|
||||
/// <summary>"FFA" | "Teams" | "MultiTeam".</summary>
|
||||
public string GameMode { get; set; } = "FFA";
|
||||
|
||||
/// <summary>Number of teams. 1 = FFA, 2 = two-team, etc.</summary>
|
||||
public int TeamCount { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// JSON array of additional player slots beyond host/guest.
|
||||
/// Each element: { "accountId": "...", "deckId": "..." }.
|
||||
/// Null until 3rd+ player joins.
|
||||
/// </summary>
|
||||
public string? AdditionalPlayersJson { get; set; }
|
||||
|
||||
// ── Timestamps ───────────────────────────────────────────────────────────
|
||||
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
|
||||
@@ -48,6 +48,21 @@ public sealed class GameSession
|
||||
/// </summary>
|
||||
public string? WinCondition { get; set; }
|
||||
|
||||
// ── Multi-player ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Total player count for this session. 2 = standard 1v1.</summary>
|
||||
public int PlayerCount { get; set; } = 2;
|
||||
|
||||
/// <summary>"FFA" | "Teams" | "MultiTeam".</summary>
|
||||
public string GameMode { get; set; } = "FFA";
|
||||
|
||||
/// <summary>
|
||||
/// JSON array of additional player slots beyond P1/P2.
|
||||
/// Each element: { "accountId": "...", "deckId": "...", "seatIndex": N, "teamIndex": N }.
|
||||
/// Null for standard 2-player sessions.
|
||||
/// </summary>
|
||||
public string? AdditionalPlayersJson { get; set; }
|
||||
|
||||
// ── Inactivity tracking ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
|
||||
+457
@@ -0,0 +1,457 @@
|
||||
// <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("20260326035612_AddMultiplayerSlots")]
|
||||
partial class AddMultiplayerSlots
|
||||
{
|
||||
/// <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.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<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<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<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,94 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SOR.Database.Migrations.Game
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddMultiplayerSlots : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "additional_players_json",
|
||||
schema: "game",
|
||||
table: "game_sessions",
|
||||
type: "text",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "game_mode",
|
||||
schema: "game",
|
||||
table: "game_sessions",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
defaultValue: "FFA");
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "player_count",
|
||||
schema: "game",
|
||||
table: "game_sessions",
|
||||
type: "integer",
|
||||
nullable: false,
|
||||
defaultValue: 2);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "additional_players_json",
|
||||
schema: "game",
|
||||
table: "custom_lobbies",
|
||||
type: "text",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "game_mode",
|
||||
schema: "game",
|
||||
table: "custom_lobbies",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
defaultValue: "FFA");
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "team_count",
|
||||
schema: "game",
|
||||
table: "custom_lobbies",
|
||||
type: "integer",
|
||||
nullable: false,
|
||||
defaultValue: 1);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "additional_players_json",
|
||||
schema: "game",
|
||||
table: "game_sessions");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "game_mode",
|
||||
schema: "game",
|
||||
table: "game_sessions");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "player_count",
|
||||
schema: "game",
|
||||
table: "game_sessions");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "additional_players_json",
|
||||
schema: "game",
|
||||
table: "custom_lobbies");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "game_mode",
|
||||
schema: "game",
|
||||
table: "custom_lobbies");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "team_count",
|
||||
schema: "game",
|
||||
table: "custom_lobbies");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,10 @@ namespace SOR.Database.Migrations.Game
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("AdditionalPlayersJson")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("additional_players_json");
|
||||
|
||||
b.Property<int?>("BoardHeightOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
@@ -47,6 +51,13 @@ namespace SOR.Database.Migrations.Game
|
||||
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");
|
||||
|
||||
@@ -118,6 +129,12 @@ namespace SOR.Database.Migrations.Game
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("TeamCount")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer")
|
||||
.HasDefaultValue(1)
|
||||
.HasColumnName("team_count");
|
||||
|
||||
b.Property<int?>("TimeLimitMinutesOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
@@ -276,15 +293,32 @@ namespace SOR.Database.Migrations.Game
|
||||
.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");
|
||||
|
||||
|
||||
@@ -1810,14 +1810,16 @@ public static class AbilitySystem
|
||||
/// Only used for the "ExactSelf" scope: the trigger fires only when this unit
|
||||
/// is the specific unit that caused the event (occ.Data.SourceId == evalUnitId).
|
||||
/// </param>
|
||||
private static bool Own(string? scope, TriggerOccurrence occ, string unitOwnerId, GameState _,
|
||||
private static bool Own(string? scope, TriggerOccurrence occ, string unitOwnerId, GameState state,
|
||||
string? evalUnitId = null)
|
||||
=> (scope?.ToLowerInvariant()) switch
|
||||
{
|
||||
null or "any" => true,
|
||||
"own" or "self" or "owner" => occ.ActorId == unitOwnerId,
|
||||
"enemy" => occ.ActorId != unitOwnerId,
|
||||
"ally" => occ.ActorId == unitOwnerId,
|
||||
// "own"/"self"/"owner" and "ally" both use team-aware ally check so that
|
||||
// in Teams / MultiTeam modes, triggered abilities fire for all teammates.
|
||||
"own" or "self" or "owner" => state.AreAllies(occ.ActorId, unitOwnerId),
|
||||
"ally" => state.AreAllies(occ.ActorId, unitOwnerId),
|
||||
"enemy" => !state.AreAllies(occ.ActorId, unitOwnerId),
|
||||
// ExactSelf: fires only for the specific unit that performed the action.
|
||||
// Requires occ.Data.SourceId to carry the acting unit's instance ID.
|
||||
"exactself" => evalUnitId is not null && occ.Data?.SourceId == evalUnitId,
|
||||
|
||||
@@ -64,22 +64,46 @@ public static class GameEngine
|
||||
Guid p1AccountId, IEnumerable<(CardDefinition def, int qty)> p1Deck, CardDefinition p1ArchSpirit,
|
||||
Guid p2AccountId, IEnumerable<(CardDefinition def, int qty)> p2Deck, CardDefinition p2ArchSpirit,
|
||||
GameRules? rules = null)
|
||||
=> Initialize(sessionId, new[]
|
||||
{
|
||||
(p1AccountId, p1Deck, p1ArchSpirit, 0, 0),
|
||||
(p2AccountId, p2Deck, p2ArchSpirit, 1, 1),
|
||||
}, "FFA", "Rectangle", rules);
|
||||
|
||||
/// <summary>
|
||||
/// N-player Initialize overload. Each player entry carries their account ID,
|
||||
/// deck, ArchSpirit definition, seat index (turn order), and team index.
|
||||
/// </summary>
|
||||
public static GameState Initialize(
|
||||
Guid sessionId,
|
||||
IReadOnlyList<(Guid accountId, IEnumerable<(CardDefinition def, int qty)> deck,
|
||||
CardDefinition archSpirit, int seatIndex, int teamIndex)> players,
|
||||
string gameMode = "FFA",
|
||||
string boardShape = "Rectangle",
|
||||
GameRules? rules = null)
|
||||
{
|
||||
rules ??= GameRules.Default;
|
||||
var r = rules ?? GameRules.Default;
|
||||
|
||||
var state = new GameState
|
||||
{
|
||||
SessionId = sessionId,
|
||||
GameMode = gameMode,
|
||||
TurnNumber = 1,
|
||||
ActivePlayerAccountId = p1AccountId.ToString(),
|
||||
PlayerOneAccountId = p1AccountId.ToString(),
|
||||
Rules = rules,
|
||||
ActivePlayerAccountId = players[0].accountId.ToString(),
|
||||
PlayerOneAccountId = players[0].accountId.ToString(),
|
||||
SeatOrder = players.Select(p => p.accountId.ToString()).ToList(),
|
||||
Phase = GamePhase.Placement,
|
||||
Board = Board.Create(rules.BoardWidth, rules.BoardHeight, rules.StartingRandomTilePct),
|
||||
Rules = r with { PlayerCount = players.Count, BoardShape = boardShape },
|
||||
Board = BoardShapeGenerator.Generate(boardShape, r, players.Count),
|
||||
};
|
||||
|
||||
state.Players[p1AccountId.ToString()] = BuildPlayerState(p1AccountId, p1Deck, p1ArchSpirit);
|
||||
state.Players[p2AccountId.ToString()] = BuildPlayerState(p2AccountId, p2Deck, p2ArchSpirit);
|
||||
foreach (var (accountId, deck, arch, seatIdx, teamIdx) in players)
|
||||
{
|
||||
var ps = BuildPlayerState(accountId, deck, arch);
|
||||
ps.SeatIndex = seatIdx;
|
||||
ps.TeamIndex = teamIdx;
|
||||
state.Players[accountId.ToString()] = ps;
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
@@ -106,10 +130,21 @@ public static class GameEngine
|
||||
var archSpirit = player.ArchSpirit ?? throw new GameException("NO_ARCH_SPIRIT");
|
||||
if (archSpirit.Position.HasValue) throw new GameException("ARCH_SPIRIT_ALREADY_PLACED");
|
||||
|
||||
// Validate placement row.
|
||||
bool isP1 = actorId == state.PlayerOneAccountId;
|
||||
int expectedRow = isP1 ? 0 : board.Height - 1;
|
||||
if (coord.Y != expectedRow) throw new GameException("INVALID_PLACEMENT_ROW");
|
||||
// Validate placement zone.
|
||||
var zones = board.StartingZones;
|
||||
if (zones.Count > 0)
|
||||
{
|
||||
var seatZone = zones.TryGetValue(player.SeatIndex, out var z) ? z : new HashSet<Coord>();
|
||||
if (!seatZone.Contains(coord))
|
||||
throw new GameException("INVALID_PLACEMENT_ROW");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Legacy fallback: P1 = row 0, P2 = top row.
|
||||
bool isP1 = actorId == state.PlayerOneAccountId;
|
||||
int expectedRow = isP1 ? 0 : board.Height - 1;
|
||||
if (coord.Y != expectedRow) throw new GameException("INVALID_PLACEMENT_ROW");
|
||||
}
|
||||
|
||||
// Validate tile.
|
||||
var tile = board.GetTile(coord) ?? throw new GameException("TILE_OUT_OF_BOUNDS");
|
||||
@@ -642,9 +677,10 @@ public static class GameEngine
|
||||
ValidateActivePlayer(state, actorId);
|
||||
ValidatePhase(state, GamePhase.Main);
|
||||
|
||||
var opponentId = GetOpponentId(state, actorId);
|
||||
var attacker = GetFieldCard(state.Players[actorId], attackerInstanceId);
|
||||
var target = GetFieldCard(state.Players[opponentId], targetInstanceId);
|
||||
var attacker = GetFieldCard(state.Players[actorId], attackerInstanceId);
|
||||
// Find the target across all non-eliminated enemy players.
|
||||
var (opponentId, opponentPlayer) = FindTargetOwner(state, actorId, targetInstanceId);
|
||||
var target = GetFieldCard(opponentPlayer, targetInstanceId);
|
||||
|
||||
if (attacker.IsExhausted) throw new GameException("CARD_EXHAUSTED");
|
||||
if (!attacker.CanAttack) throw new GameException("CARD_CANNOT_ATTACK");
|
||||
@@ -678,9 +714,8 @@ public static class GameEngine
|
||||
else
|
||||
attacker.IsExhausted = true;
|
||||
|
||||
bool gameOver = false;
|
||||
var activePlayer = state.Players[actorId];
|
||||
var opponentPlayer = state.Players[opponentId];
|
||||
bool gameOver = false;
|
||||
var activePlayer = state.Players[actorId];
|
||||
|
||||
AbilitySystem.FireTrigger(state, new TriggerOccurrence
|
||||
{
|
||||
@@ -722,8 +757,7 @@ public static class GameEngine
|
||||
{
|
||||
if (target.IsLeader)
|
||||
{
|
||||
state.Phase = GamePhase.GameOver;
|
||||
gameOver = true;
|
||||
EliminatePlayer(state, opponentPlayer, out gameOver);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -852,7 +886,7 @@ public static class GameEngine
|
||||
AbilitySystem.ExpireActiveEffects(state, actorId, isEndOfTurn: true);
|
||||
|
||||
// Switch active player and increment turn counter.
|
||||
state.ActivePlayerAccountId = GetOpponentId(state, actorId);
|
||||
state.ActivePlayerAccountId = state.GetNextActiveSeat(actorId);
|
||||
state.TurnNumber++;
|
||||
|
||||
// Check turn limit BEFORE setting up the new turn.
|
||||
@@ -1179,6 +1213,56 @@ public static class GameEngine
|
||||
private static string GetOpponentId(GameState state, string actorId)
|
||||
=> state.Players.Keys.First(k => k != actorId);
|
||||
|
||||
/// <summary>
|
||||
/// Eliminate a player whose ArchSpirit has been destroyed.
|
||||
/// Sets <see cref="PlayerState.IsEliminated"/> and checks whether all remaining
|
||||
/// players share the same team (game over) or the game continues.
|
||||
/// When gameOver = true the caller should finalize the session.
|
||||
/// </summary>
|
||||
private static bool EliminatePlayer(GameState state, PlayerState victim, out bool gameOver)
|
||||
{
|
||||
victim.IsEliminated = true;
|
||||
gameOver = false;
|
||||
|
||||
var survivingTeams = state.Players.Values
|
||||
.Where(p => !p.IsEliminated)
|
||||
.Select(p => p.TeamIndex)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
|
||||
if (survivingTeams.Count <= 1)
|
||||
{
|
||||
state.Phase = GamePhase.GameOver;
|
||||
gameOver = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Game continues — if the eliminated player was active, advance the turn.
|
||||
if (state.ActivePlayerAccountId == victim.AccountId)
|
||||
state.ActivePlayerAccountId = state.GetNextActiveSeat(victim.AccountId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Find the player who owns <paramref name="targetInstanceId"/> from among non-eliminated
|
||||
/// players other than <paramref name="actorId"/>.
|
||||
/// </summary>
|
||||
private static (string ownerId, PlayerState ownerState) FindTargetOwner(
|
||||
GameState state, string actorId, string targetInstanceId)
|
||||
{
|
||||
foreach (var (id, player) in state.Players)
|
||||
{
|
||||
if (id == actorId) continue;
|
||||
if (player.IsEliminated) continue;
|
||||
if (player.Field.OfType<FieldCard>().Any(c => c.InstanceId == targetInstanceId))
|
||||
return (id, player);
|
||||
if (player.ArchSpirit?.InstanceId == targetInstanceId)
|
||||
return (id, player);
|
||||
}
|
||||
throw new GameException("CARD_NOT_ON_FIELD");
|
||||
}
|
||||
|
||||
private static HashSet<Coord> BuildBlockedSet(
|
||||
GameState state, string movingUnitId, MovementType? movType)
|
||||
{
|
||||
|
||||
@@ -92,8 +92,11 @@ public sealed record GameForceConcedeRequest(Guid SessionId);
|
||||
public sealed record CreateCustomLobbyRequest(
|
||||
string LobbyName,
|
||||
Guid DeckId,
|
||||
string? Password = null,
|
||||
CustomRulesOverride? Rules = null);
|
||||
string? Password = null,
|
||||
CustomRulesOverride? Rules = null,
|
||||
int MaxPlayers = 2,
|
||||
string GameMode = "FFA",
|
||||
int TeamCount = 1);
|
||||
|
||||
/// <summary>
|
||||
/// Per-field rule overrides for a custom lobby. Null fields inherit from the
|
||||
@@ -122,6 +125,11 @@ public sealed record CustomRulesOverride(
|
||||
/// <summary>Join an open custom lobby with the specified deck.</summary>
|
||||
public sealed record JoinCustomLobbyRequest(Guid LobbyId, Guid DeckId, string? Password = null);
|
||||
|
||||
/// <summary>
|
||||
/// Serialized JSON entry in CustomLobby.AdditionalPlayersJson and GameSession.AdditionalPlayersJson.
|
||||
/// </summary>
|
||||
public sealed record AdditionalLobbyPlayer(Guid AccountId, Guid DeckId);
|
||||
|
||||
/// <summary>Leave or cancel a custom lobby.</summary>
|
||||
public sealed record LeaveCustomLobbyRequest(Guid LobbyId);
|
||||
|
||||
|
||||
@@ -56,5 +56,11 @@ public sealed record GameRules
|
||||
/// </summary>
|
||||
public int StartingRandomTilePct { get; init; } = 0;
|
||||
|
||||
/// <summary>Board shape identifier passed to BoardShapeGenerator. "Rectangle" | "Cross".</summary>
|
||||
public string BoardShape { get; init; } = "Rectangle";
|
||||
|
||||
/// <summary>Number of players in this game. 2 = standard 1v1.</summary>
|
||||
public int PlayerCount { get; init; } = 2;
|
||||
|
||||
public static readonly GameRules Default = new();
|
||||
}
|
||||
|
||||
@@ -23,6 +23,14 @@ public sealed class GameState
|
||||
/// <summary>Per-player state, keyed by AccountId.ToString().</summary>
|
||||
public Dictionary<string, PlayerState> Players { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Account IDs in seat / turn order. Empty for legacy 1v1 games (fall back to Players.Keys order).
|
||||
/// </summary>
|
||||
public List<string> SeatOrder { get; set; } = new();
|
||||
|
||||
/// <summary>"FFA" | "Teams" | "MultiTeam". Used for ability ownership resolution.</summary>
|
||||
public string GameMode { get; set; } = "FFA";
|
||||
|
||||
/// <summary>Running sequence number for action log / StateVersion.</summary>
|
||||
public int NextActionSequence { get; set; } = 1;
|
||||
|
||||
@@ -41,6 +49,39 @@ public sealed class GameState
|
||||
/// </summary>
|
||||
public List<ActiveEffect> ActiveEffects { get; set; } = new();
|
||||
|
||||
// ── Multi-player helpers ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Seat IDs in order, skipping eliminated players.</summary>
|
||||
public IEnumerable<string> ActiveSeats()
|
||||
=> SeatOrder.Count > 0
|
||||
? SeatOrder.Where(id => Players.TryGetValue(id, out var p) && !p.IsEliminated)
|
||||
: Players.Keys.Where(id => !Players[id].IsEliminated);
|
||||
|
||||
/// <summary>Returns the next non-eliminated player in seat order after <paramref name="actorId"/>.</summary>
|
||||
public string GetNextActiveSeat(string actorId)
|
||||
{
|
||||
var active = ActiveSeats().ToList();
|
||||
if (active.Count == 0) return actorId;
|
||||
var idx = active.IndexOf(actorId);
|
||||
return active[(idx + 1) % active.Count];
|
||||
}
|
||||
|
||||
/// <summary>Returns account IDs of all non-eliminated players not on the same team as <paramref name="actorId"/>.</summary>
|
||||
public IEnumerable<string> GetEnemyIds(string actorId)
|
||||
{
|
||||
var myTeam = Players.TryGetValue(actorId, out var p) ? p.TeamIndex : -1;
|
||||
return Players.Values
|
||||
.Where(x => x.TeamIndex != myTeam && !x.IsEliminated)
|
||||
.Select(x => x.AccountId);
|
||||
}
|
||||
|
||||
/// <summary>True when both players are on the same team (or are the same player).</summary>
|
||||
public bool AreAllies(string a, string b)
|
||||
{
|
||||
if (!Players.TryGetValue(a, out var pa) || !Players.TryGetValue(b, out var pb)) return false;
|
||||
return pa.TeamIndex == pb.TeamIndex;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deferred effects (from ApplyOnEventEffect) waiting to fire when their trigger occurs.
|
||||
/// Consumed on firing; cancelled when source unit leaves the battlefield.
|
||||
@@ -52,6 +93,15 @@ public sealed class PlayerState
|
||||
{
|
||||
public string AccountId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>0-based position in the turn order. Set during game initialization.</summary>
|
||||
public int SeatIndex { get; set; } = 0;
|
||||
|
||||
/// <summary>Team affiliation. FFA = same as SeatIndex (everyone on own team). Shared value = allies.</summary>
|
||||
public int TeamIndex { get; set; } = 0;
|
||||
|
||||
/// <summary>True when this player's ArchSpirit has been destroyed in a multi-player game.</summary>
|
||||
public bool IsEliminated { get; set; } = false;
|
||||
|
||||
// ── Zones ────────────────────────────────────────────────────────────────
|
||||
|
||||
public List<CardInstance> Hand { get; set; } = new();
|
||||
|
||||
@@ -15,6 +15,12 @@ public sealed class Board
|
||||
|
||||
public Dictionary<string, Tile> Tiles { get; init; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Seat index → valid ArchSpirit placement coordinates.
|
||||
/// Empty dictionary = legacy 2-player game (falls back to row-based validation in GameEngine).
|
||||
/// </summary>
|
||||
public Dictionary<int, HashSet<Coord>> StartingZones { get; init; } = new();
|
||||
|
||||
// Base1 pool: elemental basics + Aether (never Void — Base1 always carries a real affinity).
|
||||
private static readonly Affinity[] _base1Pool =
|
||||
[Affinity.Lake, Affinity.Hill, Affinity.Forest, Affinity.Field, Affinity.Aether];
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
namespace SOR.Game.Grid;
|
||||
|
||||
/// <summary>
|
||||
/// Generates <see cref="Board"/> instances for different board shapes, populating
|
||||
/// <see cref="Board.StartingZones"/> for each player seat.
|
||||
/// </summary>
|
||||
public static class BoardShapeGenerator
|
||||
{
|
||||
/// <summary>Generate a board appropriate for the given shape, rules, and player count.</summary>
|
||||
public static Board Generate(string shape, GameRules rules, int playerCount) =>
|
||||
shape switch
|
||||
{
|
||||
"Cross" => MakeCross(rules),
|
||||
_ => MakeRectangle(rules, playerCount),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Rectangle board. Starting zones per seat:
|
||||
/// Seat 0 = rows 0–1 (bottom edge)
|
||||
/// Seat 1 = rows Height-2 .. Height-1 (top edge)
|
||||
/// Seat 2 = cols 0–1 (left edge)
|
||||
/// Seat 3 = cols Width-2 .. Width-1 (right edge)
|
||||
/// </summary>
|
||||
private static Board MakeRectangle(GameRules rules, int playerCount)
|
||||
{
|
||||
var board = Board.Create(rules.BoardWidth, rules.BoardHeight, rules.StartingRandomTilePct);
|
||||
int w = rules.BoardWidth, h = rules.BoardHeight;
|
||||
|
||||
var zones = new Dictionary<int, HashSet<Coord>>();
|
||||
|
||||
// Seat 0 = bottom 2 rows
|
||||
zones[0] = CoordsInRows(0, 1, w);
|
||||
if (playerCount >= 2)
|
||||
zones[1] = CoordsInRows(h - 2, h - 1, w);
|
||||
if (playerCount >= 3)
|
||||
zones[2] = CoordsInCols(0, 1, h);
|
||||
if (playerCount >= 4)
|
||||
zones[3] = CoordsInCols(w - 2, w - 1, h);
|
||||
|
||||
// Return a new Board with the zones attached (Board is a reference type with mutable Tiles
|
||||
// so we create a wrapper that shares the same Tiles dictionary).
|
||||
return new Board { Width = board.Width, Height = board.Height, Tiles = board.Tiles, StartingZones = zones };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cross (plus-sign) board for 4 players.
|
||||
/// A square center arena with 4 arms; the tip of each arm is one player's starting zone.
|
||||
/// </summary>
|
||||
private static Board MakeCross(GameRules rules)
|
||||
{
|
||||
const int arm = 4;
|
||||
const int center = 5;
|
||||
int total = center + arm * 2; // 13 in each dimension
|
||||
|
||||
var tiles = new Dictionary<string, Tile>();
|
||||
|
||||
// Center square
|
||||
for (int x = arm; x < arm + center; x++)
|
||||
for (int y = arm; y < arm + center; y++)
|
||||
AddTile(tiles, x, y);
|
||||
|
||||
int mid = arm + center / 2; // midpoint column/row of the center section
|
||||
|
||||
// Bottom arm
|
||||
for (int i = 0; i < arm; i++) AddTile(tiles, mid, i);
|
||||
// Top arm
|
||||
for (int i = 0; i < arm; i++) AddTile(tiles, mid, arm + center + i);
|
||||
// Left arm
|
||||
for (int i = 0; i < arm; i++) AddTile(tiles, i, mid);
|
||||
// Right arm
|
||||
for (int i = 0; i < arm; i++) AddTile(tiles, arm + center + i, mid);
|
||||
|
||||
var zones = new Dictionary<int, HashSet<Coord>>
|
||||
{
|
||||
[0] = new() { new Coord(mid, 0) }, // bottom tip
|
||||
[1] = new() { new Coord(mid, arm + center - 1 + arm) }, // top tip
|
||||
[2] = new() { new Coord(0, mid) }, // left tip
|
||||
[3] = new() { new Coord(arm + center - 1 + arm, mid) }, // right tip
|
||||
};
|
||||
|
||||
return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones };
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static HashSet<Coord> CoordsInRows(int r0, int r1, int width)
|
||||
{
|
||||
var s = new HashSet<Coord>();
|
||||
for (int x = 0; x < width; x++)
|
||||
for (int y = r0; y <= r1; y++)
|
||||
s.Add(new Coord(x, y));
|
||||
return s;
|
||||
}
|
||||
|
||||
private static HashSet<Coord> CoordsInCols(int c0, int c1, int height)
|
||||
{
|
||||
var s = new HashSet<Coord>();
|
||||
for (int x = c0; x <= c1; x++)
|
||||
for (int y = 0; y < height; y++)
|
||||
s.Add(new Coord(x, y));
|
||||
return s;
|
||||
}
|
||||
|
||||
private static void AddTile(Dictionary<string, Tile> tiles, int x, int y)
|
||||
{
|
||||
var c = new Coord(x, y);
|
||||
tiles[c.ToKey()] = new Tile { Coord = c };
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,9 @@ internal sealed class GameCreateCustomLobbyHandler : GameHandlerBase, IMessageHa
|
||||
HostDeckId = req.DeckId,
|
||||
Status = CustomLobbyStatus.Open,
|
||||
Password = req.Password,
|
||||
MaxPlayers = Math.Clamp(req.MaxPlayers, 2, 10),
|
||||
GameMode = req.GameMode,
|
||||
TeamCount = Math.Max(1, req.TeamCount),
|
||||
OpeningHandSizeOverride = req.Rules?.OpeningHandSize,
|
||||
FirstPlayerSkipsDrawOverride = req.Rules?.FirstPlayerSkipsDraw,
|
||||
SpAccumulationPerTurnOverride = req.Rules?.SpAccumulationPerTurn,
|
||||
|
||||
@@ -44,8 +44,12 @@ internal abstract class GameHandlerBase
|
||||
.SingleOrDefaultAsync(ct)
|
||||
?? throw new GameException("SESSION_NOT_FOUND");
|
||||
|
||||
if (session.PlayerOneAccountId.ToString() != actorId &&
|
||||
session.PlayerTwoAccountId.ToString() != actorId)
|
||||
bool isKnownPlayer = session.PlayerOneAccountId.ToString() == actorId ||
|
||||
session.PlayerTwoAccountId.ToString() == actorId ||
|
||||
(session.AdditionalPlayersJson != null &&
|
||||
session.AdditionalPlayersJson.Contains(actorId));
|
||||
|
||||
if (!isKnownPlayer)
|
||||
throw new GameException("NOT_IN_SESSION");
|
||||
|
||||
if (session.Status != GameSessionStatus.Active)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Enums;
|
||||
@@ -57,16 +58,48 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand
|
||||
if (lobby.Password != null && lobby.Password != req.Password)
|
||||
throw new GameException("WRONG_PASSWORD");
|
||||
|
||||
// Seat the guest and transition to Full.
|
||||
lobby.GuestAccountId = accountId;
|
||||
lobby.GuestDeckId = req.DeckId;
|
||||
lobby.Status = CustomLobbyStatus.Full;
|
||||
// Compute current player count: host + guest slot + additional slots.
|
||||
var additionalPlayers = string.IsNullOrEmpty(lobby.AdditionalPlayersJson)
|
||||
? new List<AdditionalLobbyPlayer>()
|
||||
: JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(lobby.AdditionalPlayersJson) ?? new();
|
||||
|
||||
// Reset readiness — joining always starts a fresh ready-up cycle.
|
||||
lobby.HostReady = false;
|
||||
lobby.GuestReady = false;
|
||||
lobby.HostFirstTurnPref = null;
|
||||
lobby.GuestFirstTurnPref = null;
|
||||
int currentCount = 1 + (lobby.GuestAccountId.HasValue ? 1 : 0) + additionalPlayers.Count;
|
||||
|
||||
if (currentCount >= lobby.MaxPlayers)
|
||||
throw new GameException("LOBBY_FULL");
|
||||
|
||||
// Check not already in lobby.
|
||||
if (lobby.GuestAccountId == accountId ||
|
||||
additionalPlayers.Any(p => p.AccountId == accountId))
|
||||
throw new GameException("ALREADY_IN_LOBBY");
|
||||
|
||||
bool isFirstGuest = !lobby.GuestAccountId.HasValue;
|
||||
|
||||
if (isFirstGuest)
|
||||
{
|
||||
// Seat as primary guest.
|
||||
lobby.GuestAccountId = accountId;
|
||||
lobby.GuestDeckId = req.DeckId;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Add to additional players list.
|
||||
additionalPlayers.Add(new AdditionalLobbyPlayer(accountId, req.DeckId));
|
||||
lobby.AdditionalPlayersJson = JsonSerializer.Serialize(additionalPlayers);
|
||||
}
|
||||
|
||||
int newCount = 1 + (lobby.GuestAccountId.HasValue ? 1 : 0) + additionalPlayers.Count;
|
||||
|
||||
// Transition to Full only when the last seat is taken.
|
||||
if (newCount >= lobby.MaxPlayers)
|
||||
{
|
||||
lobby.Status = CustomLobbyStatus.Full;
|
||||
// Reset readiness — joining always starts a fresh ready-up cycle.
|
||||
lobby.HostReady = false;
|
||||
lobby.GuestReady = false;
|
||||
lobby.HostFirstTurnPref = null;
|
||||
lobby.GuestFirstTurnPref = null;
|
||||
}
|
||||
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
@@ -100,30 +133,44 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand
|
||||
StartingRandomTilePct = lobby.StartingRandomTilePctOverride ?? dbDefaults?.StartingRandomTilePct ?? GameRules.Default.StartingRandomTilePct,
|
||||
};
|
||||
|
||||
// Fetch display names for host and guest.
|
||||
var ids = new[] { lobby.HostAccountId, accountId };
|
||||
var names = await _identityDb.Users
|
||||
// Fetch display names for all current lobby members.
|
||||
var allMemberIds = new List<Guid> { lobby.HostAccountId };
|
||||
if (lobby.GuestAccountId.HasValue) allMemberIds.Add(lobby.GuestAccountId.Value);
|
||||
foreach (var ap in additionalPlayers) allMemberIds.Add(ap.AccountId);
|
||||
allMemberIds.Add(accountId); // ensure joiner is included
|
||||
|
||||
var allIds = allMemberIds.Distinct().ToArray();
|
||||
var names = await _identityDb.Users
|
||||
.AsNoTracking()
|
||||
.Where(a => ids.Contains(a.Id))
|
||||
.Where(a => allIds.Contains(a.Id))
|
||||
.Select(a => new { a.Id, Name = a.DisplayName ?? a.UserName ?? a.Id.ToString().Substring(0, 8) })
|
||||
.ToDictionaryAsync(a => a.Id, a => a.Name, ct);
|
||||
|
||||
var hostName = names.GetValueOrDefault(lobby.HostAccountId, lobby.HostAccountId.ToString()[..8]);
|
||||
var guestName = names.GetValueOrDefault(accountId, accountId.ToString()[..8]);
|
||||
|
||||
// Notify the host that their guest has arrived.
|
||||
await _clientPush.PushAsync(lobby.HostAccountId.ToString(),
|
||||
ServerMessage.Push("game.custom.lobby.guest_joined",
|
||||
new CustomLobbyGuestJoinedPush(
|
||||
LobbyId : lobby.Id,
|
||||
GuestAccountId : accountId,
|
||||
GuestDisplayName: guestName,
|
||||
LobbyName : lobby.Name)), ct);
|
||||
// Notify all existing lobby members that a new player has joined.
|
||||
var joinPush = ServerMessage.Push("game.custom.lobby.guest_joined",
|
||||
new CustomLobbyGuestJoinedPush(
|
||||
LobbyId : lobby.Id,
|
||||
GuestAccountId : accountId,
|
||||
GuestDisplayName: guestName,
|
||||
LobbyName : lobby.Name));
|
||||
|
||||
var notifyTasks = new List<Task>
|
||||
{
|
||||
_clientPush.PushAsync(lobby.HostAccountId.ToString(), joinPush, ct),
|
||||
};
|
||||
if (lobby.GuestAccountId.HasValue && lobby.GuestAccountId.Value != accountId)
|
||||
notifyTasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), joinPush, ct));
|
||||
foreach (var ap in additionalPlayers.Where(p => p.AccountId != accountId))
|
||||
notifyTasks.Add(_clientPush.PushAsync(ap.AccountId.ToString(), joinPush, ct));
|
||||
await Task.WhenAll(notifyTasks);
|
||||
|
||||
return ServerMessage.Reply("game.custom.join.ack", message.Seq,
|
||||
new JoinCustomLobbyResponse(
|
||||
LobbyId : lobby.Id,
|
||||
Status : "WaitingForReady",
|
||||
Status : lobby.Status == CustomLobbyStatus.Full ? "WaitingForReady" : "WaitingForPlayers",
|
||||
ActiveRules : GameCreateCustomLobbyHandler.ToDto(effective, lobby.Password != null),
|
||||
GameSessionId : null,
|
||||
HostAccountId : lobby.HostAccountId,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Database.Contexts;
|
||||
@@ -64,7 +65,18 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
var isHost = lobby.HostAccountId == accountId;
|
||||
var isGuest = lobby.GuestAccountId == accountId;
|
||||
|
||||
if (!isHost && !isGuest)
|
||||
// For 3+ player lobbies, also accept additional players.
|
||||
bool isAdditional = false;
|
||||
if (!isHost && !isGuest && lobby.AdditionalPlayersJson != null)
|
||||
{
|
||||
var addlCheck = JsonSerializer.Deserialize<List<AdditionalLobbyPlayerReady>>(
|
||||
lobby.AdditionalPlayersJson,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
||||
?? new();
|
||||
isAdditional = addlCheck.Any(p => p.AccountId == accountId);
|
||||
}
|
||||
|
||||
if (!isHost && !isGuest && !isAdditional)
|
||||
throw new GameException("NOT_IN_LOBBY");
|
||||
|
||||
// Update deck and first-turn pref, then mark ready.
|
||||
@@ -83,16 +95,42 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
// Push updated ready status to both participants.
|
||||
// Update readiness in AdditionalPlayersJson for players 3+.
|
||||
if (!isHost && !isGuest && lobby.AdditionalPlayersJson != null)
|
||||
{
|
||||
var addl = JsonSerializer.Deserialize<List<AdditionalLobbyPlayerReady>>(
|
||||
lobby.AdditionalPlayersJson,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
||||
?? new();
|
||||
var entry = addl.FirstOrDefault(p => p.AccountId == accountId);
|
||||
if (entry != null)
|
||||
entry.IsReady = true;
|
||||
lobby.AdditionalPlayersJson = JsonSerializer.Serialize(addl);
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
// Push updated ready status to all participants.
|
||||
var readyPush = ServerMessage.Push("game.custom.lobby.ready_status",
|
||||
new LobbyReadyStatusPush(lobby.Id, lobby.HostReady, lobby.GuestReady));
|
||||
|
||||
await Task.WhenAll(
|
||||
var pushTasks = new List<Task>
|
||||
{
|
||||
_clientPush.PushAsync(lobby.HostAccountId.ToString(), readyPush, ct),
|
||||
_clientPush.PushAsync(lobby.GuestAccountId!.Value.ToString(), readyPush, ct));
|
||||
};
|
||||
if (lobby.GuestAccountId.HasValue)
|
||||
pushTasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), readyPush, ct));
|
||||
await Task.WhenAll(pushTasks);
|
||||
|
||||
// All-ready check.
|
||||
// All-ready check: host + guest must be ready; for 3+ players all must be ready.
|
||||
bool allReady = lobby.GuestAccountId.HasValue && lobby.HostReady && lobby.GuestReady;
|
||||
if (allReady && lobby.AdditionalPlayersJson != null)
|
||||
{
|
||||
var addl = JsonSerializer.Deserialize<List<AdditionalLobbyPlayerReady>>(
|
||||
lobby.AdditionalPlayersJson,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
||||
?? new();
|
||||
allReady = addl.All(p => p.IsReady);
|
||||
}
|
||||
|
||||
if (allReady)
|
||||
await StartGameAsync(lobby, accountId, ct);
|
||||
@@ -121,9 +159,30 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
var p1DeckId = playerOneId == lobby.HostAccountId ? lobby.HostDeckId : lobby.GuestDeckId!.Value;
|
||||
var p2DeckId = playerTwoId == lobby.HostAccountId ? lobby.HostDeckId : lobby.GuestDeckId!.Value;
|
||||
|
||||
// Load the admin-configured custom-default ruleset so that lobby fields not
|
||||
// explicitly overridden by the host inherit the current admin settings rather
|
||||
// than the hard-coded GameRules.Default values.
|
||||
// Additional players (seats 2+).
|
||||
var additionalPlayers = string.IsNullOrEmpty(lobby.AdditionalPlayersJson)
|
||||
? new List<AdditionalLobbyPlayer>()
|
||||
: JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(lobby.AdditionalPlayersJson) ?? new();
|
||||
|
||||
// Build the full ordered player list: [P1, P2, P3, ...].
|
||||
var allPlayerIds = new List<Guid> { playerOneId, playerTwoId };
|
||||
var allDeckIds = new List<Guid> { p1DeckId, p2DeckId };
|
||||
foreach (var ap in additionalPlayers)
|
||||
{
|
||||
allPlayerIds.Add(ap.AccountId);
|
||||
allDeckIds.Add(ap.DeckId);
|
||||
}
|
||||
|
||||
int playerCount = allPlayerIds.Count;
|
||||
int teamCount = Math.Max(1, lobby.TeamCount);
|
||||
|
||||
// Compute team indices based on game mode:
|
||||
// FFA → teamIndex = seatIndex (everyone on own team)
|
||||
// Teams (≥2) → teamIndex = seatIndex % teamCount (alternating assignment)
|
||||
static int ComputeTeamIndex(string gameMode, int seatIndex, int teamCount) =>
|
||||
gameMode == "FFA" ? seatIndex : seatIndex % teamCount;
|
||||
|
||||
// Load the admin-configured custom-default ruleset.
|
||||
var dbDefaults = await _gameDb.GameRuleSets
|
||||
.AsNoTracking()
|
||||
.Where(r => r.IsCustomDefault)
|
||||
@@ -152,15 +211,32 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
StartingRandomTilePct = lobby.StartingRandomTilePctOverride ?? dbDefaults?.StartingRandomTilePct ?? GameRules.Default.StartingRandomTilePct,
|
||||
};
|
||||
|
||||
// Build additional players JSON for the session (seats 2+).
|
||||
string? sessionAdditionalJson = null;
|
||||
if (additionalPlayers.Count > 0)
|
||||
{
|
||||
var sessionAddl = additionalPlayers.Select((ap, i) => new
|
||||
{
|
||||
accountId = ap.AccountId,
|
||||
deckId = ap.DeckId,
|
||||
seatIndex = i + 2,
|
||||
teamIndex = ComputeTeamIndex(lobby.GameMode, i + 2, teamCount),
|
||||
});
|
||||
sessionAdditionalJson = JsonSerializer.Serialize(sessionAddl);
|
||||
}
|
||||
|
||||
var session = new GameSession
|
||||
{
|
||||
PlayerOneAccountId = playerOneId,
|
||||
PlayerOneDeckId = p1DeckId,
|
||||
PlayerTwoAccountId = playerTwoId,
|
||||
PlayerTwoDeckId = p2DeckId,
|
||||
Status = GameSessionStatus.Initializing,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
RuleSnapshotJson = JsonSerializer.Serialize(rules),
|
||||
PlayerOneAccountId = playerOneId,
|
||||
PlayerOneDeckId = p1DeckId,
|
||||
PlayerTwoAccountId = playerTwoId,
|
||||
PlayerTwoDeckId = p2DeckId,
|
||||
PlayerCount = playerCount,
|
||||
GameMode = lobby.GameMode,
|
||||
AdditionalPlayersJson = sessionAdditionalJson,
|
||||
Status = GameSessionStatus.Initializing,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
RuleSnapshotJson = JsonSerializer.Serialize(rules),
|
||||
};
|
||||
|
||||
_gameDb.GameSessions.Add(session);
|
||||
@@ -176,7 +252,7 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
NatsSubjects.GameStarted,
|
||||
new GameStartedEvent(
|
||||
session.Id,
|
||||
new[] { playerOneId, playerTwoId },
|
||||
allPlayerIds.ToArray(),
|
||||
DateTimeOffset.UtcNow),
|
||||
ct);
|
||||
}
|
||||
@@ -187,24 +263,45 @@ internal sealed class GameLobbyReadyHandler : GameHandlerBase, IMessageHandler
|
||||
session.Id);
|
||||
}
|
||||
|
||||
// Fetch display names for both players for the game-started push.
|
||||
var ids = new[] { playerOneId, playerTwoId };
|
||||
var names = await _identityDb.Users
|
||||
// Fetch display names for all players for the game-started push.
|
||||
var allIds = allPlayerIds.ToArray();
|
||||
var names = await _identityDb.Users
|
||||
.AsNoTracking()
|
||||
.Where(a => ids.Contains(a.Id))
|
||||
.Where(a => allIds.Contains(a.Id))
|
||||
.Select(a => new { a.Id, Name = a.DisplayName ?? a.UserName ?? a.Id.ToString().Substring(0, 8) })
|
||||
.ToDictionaryAsync(a => a.Id, a => a.Name, ct);
|
||||
|
||||
var p1Name = names.GetValueOrDefault(playerOneId, playerOneId.ToString()[..8]);
|
||||
var p2Name = names.GetValueOrDefault(playerTwoId, playerTwoId.ToString()[..8]);
|
||||
|
||||
// Push game-started notification to both players.
|
||||
await Task.WhenAll(
|
||||
// Push game-started notification to all players.
|
||||
var startTasks = new List<Task>
|
||||
{
|
||||
_clientPush.PushAsync(playerOneId.ToString(),
|
||||
ServerMessage.Push("game.custom.started",
|
||||
new CustomLobbyGameStartedPush(session.Id, playerTwoId, p2Name)), ct),
|
||||
_clientPush.PushAsync(playerTwoId.ToString(),
|
||||
ServerMessage.Push("game.custom.started",
|
||||
new CustomLobbyGameStartedPush(session.Id, playerOneId, p1Name)), ct),
|
||||
};
|
||||
for (int i = 0; i < additionalPlayers.Count; i++)
|
||||
{
|
||||
var apId = additionalPlayers[i].AccountId;
|
||||
var apName = names.GetValueOrDefault(apId, apId.ToString()[..8]);
|
||||
startTasks.Add(_clientPush.PushAsync(apId.ToString(),
|
||||
ServerMessage.Push("game.custom.started",
|
||||
new CustomLobbyGameStartedPush(session.Id, playerOneId, p1Name)), ct));
|
||||
}
|
||||
await Task.WhenAll(startTasks);
|
||||
}
|
||||
|
||||
// ── Helper types ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Tracks a player's readiness state within AdditionalPlayersJson.</summary>
|
||||
private sealed class AdditionalLobbyPlayerReady
|
||||
{
|
||||
[JsonPropertyName("accountId")] public Guid AccountId { get; set; }
|
||||
[JsonPropertyName("deckId")] public Guid DeckId { get; set; }
|
||||
[JsonPropertyName("isReady")] public bool IsReady { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
namespace SOR.Game.Handlers;
|
||||
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Catalog;
|
||||
@@ -68,7 +69,11 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler
|
||||
.SingleOrDefaultAsync(ct)
|
||||
?? throw new GameException("SESSION_NOT_FOUND");
|
||||
|
||||
if (session.PlayerOneAccountId != accountId && session.PlayerTwoAccountId != accountId)
|
||||
bool isP1orP2 = session.PlayerOneAccountId == accountId || session.PlayerTwoAccountId == accountId;
|
||||
bool isAdditional = !isP1orP2 && session.AdditionalPlayersJson != null &&
|
||||
session.AdditionalPlayersJson.Contains(accountId.ToString());
|
||||
|
||||
if (!isP1orP2 && !isAdditional)
|
||||
throw new GameException("NOT_IN_SESSION");
|
||||
|
||||
if (session.Status == GameSessionStatus.Active)
|
||||
@@ -106,21 +111,73 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler
|
||||
}
|
||||
|
||||
// Both ready — initialize game state.
|
||||
var p1DeckCards = await LoadDeckCardsAsync(session.PlayerOneDeckId, ct);
|
||||
var p2DeckCards = await LoadDeckCardsAsync(session.PlayerTwoDeckId, ct);
|
||||
var p1ArchSpirit = await LoadDeckArchSpiritAsync(session.PlayerOneDeckId, ct);
|
||||
var p2ArchSpirit = await LoadDeckArchSpiritAsync(session.PlayerTwoDeckId, ct);
|
||||
|
||||
// Deserialize rule snapshot (falls back to default if none stored).
|
||||
var rules = session.RuleSnapshotJson is not null
|
||||
? GameEngine.DeserializeRules(session.RuleSnapshotJson)
|
||||
: null;
|
||||
|
||||
var state = GameEngine.Initialize(
|
||||
session.Id,
|
||||
session.PlayerOneAccountId, p1DeckCards, p1ArchSpirit,
|
||||
session.PlayerTwoAccountId, p2DeckCards, p2ArchSpirit,
|
||||
rules);
|
||||
GameState state;
|
||||
|
||||
if (session.PlayerCount <= 2 || string.IsNullOrEmpty(session.AdditionalPlayersJson))
|
||||
{
|
||||
// Standard 2-player path.
|
||||
var p1DeckCards = await LoadDeckCardsAsync(session.PlayerOneDeckId, ct);
|
||||
var p2DeckCards = await LoadDeckCardsAsync(session.PlayerTwoDeckId, ct);
|
||||
var p1ArchSpirit = await LoadDeckArchSpiritAsync(session.PlayerOneDeckId, ct);
|
||||
var p2ArchSpirit = await LoadDeckArchSpiritAsync(session.PlayerTwoDeckId, ct);
|
||||
|
||||
state = GameEngine.Initialize(
|
||||
session.Id,
|
||||
session.PlayerOneAccountId, p1DeckCards, p1ArchSpirit,
|
||||
session.PlayerTwoAccountId, p2DeckCards, p2ArchSpirit,
|
||||
rules);
|
||||
}
|
||||
else
|
||||
{
|
||||
// N-player path: read additional players from session JSON.
|
||||
var additionalEntries = JsonSerializer.Deserialize<List<SessionAdditionalPlayer>>(
|
||||
session.AdditionalPlayersJson,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
||||
?? new();
|
||||
|
||||
// Build player list with seat/team indices.
|
||||
// P1 and P2 always have seatIndex 0 and 1; teamIndex from GameMode.
|
||||
int teamCount = 1; // FFA default
|
||||
static int TeamIdx(string gameMode, int seat, int tc) =>
|
||||
gameMode == "FFA" ? seat : seat % tc;
|
||||
|
||||
var playerList = new List<(Guid, IEnumerable<(SOR.Database.Entities.Catalog.CardDefinition, int)>,
|
||||
SOR.Database.Entities.Catalog.CardDefinition, int, int)>
|
||||
{
|
||||
(session.PlayerOneAccountId,
|
||||
await LoadDeckCardsAsync(session.PlayerOneDeckId, ct),
|
||||
await LoadDeckArchSpiritAsync(session.PlayerOneDeckId, ct),
|
||||
0,
|
||||
TeamIdx(session.GameMode, 0, teamCount)),
|
||||
(session.PlayerTwoAccountId,
|
||||
await LoadDeckCardsAsync(session.PlayerTwoDeckId, ct),
|
||||
await LoadDeckArchSpiritAsync(session.PlayerTwoDeckId, ct),
|
||||
1,
|
||||
TeamIdx(session.GameMode, 1, teamCount)),
|
||||
};
|
||||
|
||||
foreach (var entry in additionalEntries)
|
||||
{
|
||||
playerList.Add((
|
||||
entry.AccountId,
|
||||
await LoadDeckCardsAsync(entry.DeckId, ct),
|
||||
await LoadDeckArchSpiritAsync(entry.DeckId, ct),
|
||||
entry.SeatIndex,
|
||||
entry.TeamIndex));
|
||||
}
|
||||
|
||||
state = GameEngine.Initialize(
|
||||
session.Id,
|
||||
playerList.AsReadOnly(),
|
||||
session.GameMode,
|
||||
rules?.BoardShape ?? "Rectangle",
|
||||
rules);
|
||||
}
|
||||
|
||||
session.StateJson = GameEngine.Serialize(state);
|
||||
session.Status = GameSessionStatus.Active;
|
||||
@@ -138,6 +195,15 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>JSON shape for AdditionalPlayersJson entries on a GameSession.</summary>
|
||||
private sealed class SessionAdditionalPlayer
|
||||
{
|
||||
public Guid AccountId { get; set; }
|
||||
public Guid DeckId { get; set; }
|
||||
public int SeatIndex { get; set; }
|
||||
public int TeamIndex { get; set; }
|
||||
}
|
||||
|
||||
private async Task<IEnumerable<(CardDefinition, int)>> LoadDeckCardsAsync(Guid deckId, CancellationToken ct)
|
||||
{
|
||||
var deck = await _collectionDb.Decks
|
||||
|
||||
Reference in New Issue
Block a user