diff --git a/Client/origin-client/autoloads/Game.gd b/Client/origin-client/autoloads/Game.gd index 5825872..ac452da 100644 --- a/Client/origin-client/autoloads/Game.gd +++ b/Client/origin-client/autoloads/Game.gd @@ -94,12 +94,19 @@ func get_my_player() -> Dictionary: return _player_by_id(Auth.user_id) -## Returns the PlayerStateDto dict for the opponent, or {}. -func get_opponent() -> Dictionary: +## Returns all opponent PlayerStateDto dicts (non-local, non-eliminated players). +func get_opponents() -> Array: + var result: Array = [] for p: Dictionary in state.get("players", []): if str(p.get("accountId", "")) != Auth.user_id: - return p - return {} + result.append(p) + return result + + +## Returns the PlayerStateDto dict for the (first) opponent — backward-compat alias. +func get_opponent() -> Dictionary: + var opps := get_opponents() + return opps[0] if not opps.is_empty() else {} ## Returns true when it is the local player's turn. diff --git a/Server/src/SOR.Database/Contexts/GameDbContext.cs b/Server/src/SOR.Database/Contexts/GameDbContext.cs index d606f96..c6ae70c 100644 --- a/Server/src/SOR.Database/Contexts/GameDbContext.cs +++ b/Server/src/SOR.Database/Contexts/GameDbContext.cs @@ -50,6 +50,9 @@ public sealed class GameDbContext : DbContext e.Property(s => s.Status).HasConversion(); 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(); + 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); }); diff --git a/Server/src/SOR.Database/Entities/Game/CustomLobby.cs b/Server/src/SOR.Database/Entities/Game/CustomLobby.cs index 35f8632..1c6b9d9 100644 --- a/Server/src/SOR.Database/Entities/Game/CustomLobby.cs +++ b/Server/src/SOR.Database/Entities/Game/CustomLobby.cs @@ -97,9 +97,22 @@ public sealed class CustomLobby /// Guest's first-turn preference: "host" | "guest" | "random" | null. public string? GuestFirstTurnPref { get; set; } - /// Maximum number of players. Default 2; stub for future N-player support. + /// Maximum number of players. Default 2. public int MaxPlayers { get; set; } = 2; + /// "FFA" | "Teams" | "MultiTeam". + public string GameMode { get; set; } = "FFA"; + + /// Number of teams. 1 = FFA, 2 = two-team, etc. + public int TeamCount { get; set; } = 1; + + /// + /// JSON array of additional player slots beyond host/guest. + /// Each element: { "accountId": "...", "deckId": "..." }. + /// Null until 3rd+ player joins. + /// + public string? AdditionalPlayersJson { get; set; } + // ── Timestamps ─────────────────────────────────────────────────────────── public DateTimeOffset CreatedAt { get; set; } diff --git a/Server/src/SOR.Database/Entities/Game/GameSession.cs b/Server/src/SOR.Database/Entities/Game/GameSession.cs index 61aea8b..10970e3 100644 --- a/Server/src/SOR.Database/Entities/Game/GameSession.cs +++ b/Server/src/SOR.Database/Entities/Game/GameSession.cs @@ -48,6 +48,21 @@ public sealed class GameSession /// public string? WinCondition { get; set; } + // ── Multi-player ───────────────────────────────────────────────────────── + + /// Total player count for this session. 2 = standard 1v1. + public int PlayerCount { get; set; } = 2; + + /// "FFA" | "Teams" | "MultiTeam". + public string GameMode { get; set; } = "FFA"; + + /// + /// JSON array of additional player slots beyond P1/P2. + /// Each element: { "accountId": "...", "deckId": "...", "seatIndex": N, "teamIndex": N }. + /// Null for standard 2-player sessions. + /// + public string? AdditionalPlayersJson { get; set; } + // ── Inactivity tracking ────────────────────────────────────────────────────── /// diff --git a/Server/src/SOR.Database/Migrations/Game/20260326035612_AddMultiplayerSlots.Designer.cs b/Server/src/SOR.Database/Migrations/Game/20260326035612_AddMultiplayerSlots.Designer.cs new file mode 100644 index 0000000..4929232 --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Game/20260326035612_AddMultiplayerSlots.Designer.cs @@ -0,0 +1,457 @@ +// +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 + { + /// + 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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AdditionalPlayersJson") + .HasColumnType("text") + .HasColumnName("additional_players_json"); + + b.Property("BoardHeightOverride") + .HasColumnType("integer"); + + b.Property("BoardWidthOverride") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiscardOnMaxHandOverride") + .HasColumnType("boolean"); + + b.Property("DrawPerTurnOverride") + .HasColumnType("integer"); + + b.Property("FirstPlayerSkipsDrawOverride") + .HasColumnType("boolean"); + + b.Property("GameMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("FFA") + .HasColumnName("game_mode"); + + b.Property("GameSessionId") + .HasColumnType("uuid"); + + b.Property("GuestAccountId") + .HasColumnType("uuid"); + + b.Property("GuestDeckId") + .HasColumnType("uuid"); + + b.Property("GuestFirstTurnPref") + .HasColumnType("text"); + + b.Property("GuestReady") + .HasColumnType("boolean"); + + b.Property("HandSizeCapOverride") + .HasColumnType("integer"); + + b.Property("HostAccountId") + .HasColumnType("uuid"); + + b.Property("HostDeckId") + .HasColumnType("uuid"); + + b.Property("HostFirstTurnPref") + .HasColumnType("text"); + + b.Property("HostReady") + .HasColumnType("boolean"); + + b.Property("MaxArchTier1Override") + .HasColumnType("integer"); + + b.Property("MaxDeckSizeOverride") + .HasColumnType("integer"); + + b.Property("MaxPlayers") + .HasColumnType("integer"); + + b.Property("MinDeckSizeOverride") + .HasColumnType("integer"); + + b.Property("MpBuffOverride") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OpeningHandSizeOverride") + .HasColumnType("integer"); + + b.Property("Password") + .HasColumnType("text"); + + b.Property("SpAccumulationPerTurnOverride") + .HasColumnType("integer"); + + b.Property("SpCapOverride") + .HasColumnType("integer"); + + b.Property("SpHasCapOverride") + .HasColumnType("boolean"); + + b.Property("StartingRandomTilePctOverride") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TeamCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("team_count"); + + b.Property("TimeLimitMinutesOverride") + .HasColumnType("integer"); + + b.Property("TurnLimitOverride") + .HasColumnType("integer"); + + b.Property("TurnTimerSecondsOverride") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("HostAccountId"); + + b.HasIndex("Status", "CreatedAt"); + + b.ToTable("custom_lobbies", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ActionType") + .IsRequired() + .HasColumnType("text"); + + b.Property("ActorAccountId") + .HasColumnType("uuid"); + + b.Property("GameSessionId") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PayloadJson") + .HasColumnType("jsonb") + .HasColumnName("payload"); + + b.Property("ResultJson") + .HasColumnType("jsonb") + .HasColumnName("result"); + + b.Property("SequenceNumber") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ActorAccountId"); + + b.HasIndex("GameSessionId", "SequenceNumber") + .IsUnique(); + + b.ToTable("action_logs", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameRuleSet", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BoardHeight") + .HasColumnType("integer"); + + b.Property("BoardWidth") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiscardOnMaxHand") + .HasColumnType("boolean"); + + b.Property("DrawPerTurn") + .HasColumnType("integer"); + + b.Property("FirstPlayerSkipsDraw") + .HasColumnType("boolean"); + + b.Property("HandSizeCap") + .HasColumnType("integer"); + + b.Property("IsCustomDefault") + .HasColumnType("boolean"); + + b.Property("IsRankedDefault") + .HasColumnType("boolean"); + + b.Property("LoserOpReward") + .HasColumnType("integer"); + + b.Property("MaxArchTier1") + .HasColumnType("integer"); + + b.Property("MaxDeckSize") + .HasColumnType("integer"); + + b.Property("MinDeckSize") + .HasColumnType("integer"); + + b.Property("MpBuff") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OpeningHandSize") + .HasColumnType("integer"); + + b.Property("RankDiffOpMultiplierPct") + .HasColumnType("integer"); + + b.Property("SpAccumulationPerTurn") + .HasColumnType("integer"); + + b.Property("SpCap") + .HasColumnType("integer"); + + b.Property("SpHasCap") + .HasColumnType("boolean"); + + b.Property("StartingRandomTilePct") + .HasColumnType("integer"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("TurnLimit") + .HasColumnType("integer"); + + b.Property("TurnTimerSeconds") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("WinnerOpReward") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IsCustomDefault"); + + b.HasIndex("IsRankedDefault"); + + b.ToTable("game_rule_sets", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AdditionalPlayersJson") + .HasColumnType("text") + .HasColumnName("additional_players_json"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EndedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("GameMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("FFA") + .HasColumnName("game_mode"); + + b.Property("LastActionAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PlayerCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(2) + .HasColumnName("player_count"); + + b.Property("PlayerOneAccountId") + .HasColumnType("uuid"); + + b.Property("PlayerOneDeckId") + .HasColumnType("uuid"); + + b.Property("PlayerOneReady") + .HasColumnType("boolean"); + + b.Property("PlayerTwoAccountId") + .HasColumnType("uuid"); + + b.Property("PlayerTwoDeckId") + .HasColumnType("uuid"); + + b.Property("PlayerTwoReady") + .HasColumnType("boolean"); + + b.Property("RuleSnapshotJson") + .HasColumnType("jsonb") + .HasColumnName("rule_snapshot"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("StateJson") + .HasColumnType("jsonb") + .HasColumnName("state"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("WinCondition") + .HasColumnType("text"); + + b.Property("WinnerAccountId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PlayerOneAccountId"); + + b.HasIndex("PlayerTwoAccountId"); + + b.HasIndex("Status", "CreatedAt"); + + b.ToTable("game_sessions", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.LobbyPreset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerAccountId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("OwnerAccountId"); + + b.ToTable("lobby_presets", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountId") + .HasColumnType("uuid"); + + b.Property("DeckId") + .HasColumnType("uuid"); + + b.Property("JoinedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("MatchedGameSessionId") + .HasColumnType("uuid"); + + b.Property("RankScore") + .HasColumnType("integer"); + + b.Property("ResolvedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("AccountId", "Status"); + + b.HasIndex("Status", "RankScore"); + + b.ToTable("matchmaking_entries", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b => + { + b.HasOne("SOR.Database.Entities.Game.GameSession", "Session") + .WithMany("ActionLog") + .HasForeignKey("GameSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Session"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b => + { + b.Navigation("ActionLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Game/20260326035612_AddMultiplayerSlots.cs b/Server/src/SOR.Database/Migrations/Game/20260326035612_AddMultiplayerSlots.cs new file mode 100644 index 0000000..f05d2a6 --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Game/20260326035612_AddMultiplayerSlots.cs @@ -0,0 +1,94 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SOR.Database.Migrations.Game +{ + /// + public partial class AddMultiplayerSlots : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "additional_players_json", + schema: "game", + table: "game_sessions", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "game_mode", + schema: "game", + table: "game_sessions", + type: "text", + nullable: false, + defaultValue: "FFA"); + + migrationBuilder.AddColumn( + name: "player_count", + schema: "game", + table: "game_sessions", + type: "integer", + nullable: false, + defaultValue: 2); + + migrationBuilder.AddColumn( + name: "additional_players_json", + schema: "game", + table: "custom_lobbies", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "game_mode", + schema: "game", + table: "custom_lobbies", + type: "text", + nullable: false, + defaultValue: "FFA"); + + migrationBuilder.AddColumn( + name: "team_count", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: false, + defaultValue: 1); + } + + /// + 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"); + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs index 6e2453b..1d77544 100644 --- a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs +++ b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs @@ -29,6 +29,10 @@ namespace SOR.Database.Migrations.Game .ValueGeneratedOnAdd() .HasColumnType("uuid"); + b.Property("AdditionalPlayersJson") + .HasColumnType("text") + .HasColumnName("additional_players_json"); + b.Property("BoardHeightOverride") .HasColumnType("integer"); @@ -47,6 +51,13 @@ namespace SOR.Database.Migrations.Game b.Property("FirstPlayerSkipsDrawOverride") .HasColumnType("boolean"); + b.Property("GameMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("FFA") + .HasColumnName("game_mode"); + b.Property("GameSessionId") .HasColumnType("uuid"); @@ -118,6 +129,12 @@ namespace SOR.Database.Migrations.Game .IsRequired() .HasColumnType("text"); + b.Property("TeamCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("team_count"); + b.Property("TimeLimitMinutesOverride") .HasColumnType("integer"); @@ -276,15 +293,32 @@ namespace SOR.Database.Migrations.Game .ValueGeneratedOnAdd() .HasColumnType("uuid"); + b.Property("AdditionalPlayersJson") + .HasColumnType("text") + .HasColumnName("additional_players_json"); + b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("EndedAt") .HasColumnType("timestamp with time zone"); + b.Property("GameMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("FFA") + .HasColumnName("game_mode"); + b.Property("LastActionAt") .HasColumnType("timestamp with time zone"); + b.Property("PlayerCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(2) + .HasColumnName("player_count"); + b.Property("PlayerOneAccountId") .HasColumnType("uuid"); diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index d5f5f48..723787b 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -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). /// - 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, diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs index 1e49e67..1c104a9 100644 --- a/Server/src/SOR.Game/GameEngine.cs +++ b/Server/src/SOR.Game/GameEngine.cs @@ -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); + + /// + /// N-player Initialize overload. Each player entry carries their account ID, + /// deck, ArchSpirit definition, seat index (turn order), and team index. + /// + 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(); + 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); + /// + /// Eliminate a player whose ArchSpirit has been destroyed. + /// Sets 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. + /// + 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; + } + + /// + /// Find the player who owns from among non-eliminated + /// players other than . + /// + 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().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 BuildBlockedSet( GameState state, string movingUnitId, MovementType? movType) { diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index 166b9df..b674dc6 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -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); /// /// Per-field rule overrides for a custom lobby. Null fields inherit from the @@ -122,6 +125,11 @@ public sealed record CustomRulesOverride( /// Join an open custom lobby with the specified deck. public sealed record JoinCustomLobbyRequest(Guid LobbyId, Guid DeckId, string? Password = null); +/// +/// Serialized JSON entry in CustomLobby.AdditionalPlayersJson and GameSession.AdditionalPlayersJson. +/// +public sealed record AdditionalLobbyPlayer(Guid AccountId, Guid DeckId); + /// Leave or cancel a custom lobby. public sealed record LeaveCustomLobbyRequest(Guid LobbyId); diff --git a/Server/src/SOR.Game/GameRules.cs b/Server/src/SOR.Game/GameRules.cs index 1af11b8..df8716b 100644 --- a/Server/src/SOR.Game/GameRules.cs +++ b/Server/src/SOR.Game/GameRules.cs @@ -56,5 +56,11 @@ public sealed record GameRules /// public int StartingRandomTilePct { get; init; } = 0; + /// Board shape identifier passed to BoardShapeGenerator. "Rectangle" | "Cross". + public string BoardShape { get; init; } = "Rectangle"; + + /// Number of players in this game. 2 = standard 1v1. + public int PlayerCount { get; init; } = 2; + public static readonly GameRules Default = new(); } diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs index e1a8649..4568fec 100644 --- a/Server/src/SOR.Game/GameState.cs +++ b/Server/src/SOR.Game/GameState.cs @@ -23,6 +23,14 @@ public sealed class GameState /// Per-player state, keyed by AccountId.ToString(). public Dictionary Players { get; set; } = new(); + /// + /// Account IDs in seat / turn order. Empty for legacy 1v1 games (fall back to Players.Keys order). + /// + public List SeatOrder { get; set; } = new(); + + /// "FFA" | "Teams" | "MultiTeam". Used for ability ownership resolution. + public string GameMode { get; set; } = "FFA"; + /// Running sequence number for action log / StateVersion. public int NextActionSequence { get; set; } = 1; @@ -41,6 +49,39 @@ public sealed class GameState /// public List ActiveEffects { get; set; } = new(); + // ── Multi-player helpers ────────────────────────────────────────────────── + + /// Seat IDs in order, skipping eliminated players. + public IEnumerable ActiveSeats() + => SeatOrder.Count > 0 + ? SeatOrder.Where(id => Players.TryGetValue(id, out var p) && !p.IsEliminated) + : Players.Keys.Where(id => !Players[id].IsEliminated); + + /// Returns the next non-eliminated player in seat order after . + 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]; + } + + /// Returns account IDs of all non-eliminated players not on the same team as . + public IEnumerable 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); + } + + /// True when both players are on the same team (or are the same player). + 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; + } + /// /// 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; + /// 0-based position in the turn order. Set during game initialization. + public int SeatIndex { get; set; } = 0; + + /// Team affiliation. FFA = same as SeatIndex (everyone on own team). Shared value = allies. + public int TeamIndex { get; set; } = 0; + + /// True when this player's ArchSpirit has been destroyed in a multi-player game. + public bool IsEliminated { get; set; } = false; + // ── Zones ──────────────────────────────────────────────────────────────── public List Hand { get; set; } = new(); diff --git a/Server/src/SOR.Game/Grid/Board.cs b/Server/src/SOR.Game/Grid/Board.cs index 41c16d8..a7873ea 100644 --- a/Server/src/SOR.Game/Grid/Board.cs +++ b/Server/src/SOR.Game/Grid/Board.cs @@ -15,6 +15,12 @@ public sealed class Board public Dictionary Tiles { get; init; } = new(); + /// + /// Seat index → valid ArchSpirit placement coordinates. + /// Empty dictionary = legacy 2-player game (falls back to row-based validation in GameEngine). + /// + public Dictionary> 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]; diff --git a/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs b/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs new file mode 100644 index 0000000..1ac3c4d --- /dev/null +++ b/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs @@ -0,0 +1,109 @@ +namespace SOR.Game.Grid; + +/// +/// Generates instances for different board shapes, populating +/// for each player seat. +/// +public static class BoardShapeGenerator +{ + /// Generate a board appropriate for the given shape, rules, and player count. + public static Board Generate(string shape, GameRules rules, int playerCount) => + shape switch + { + "Cross" => MakeCross(rules), + _ => MakeRectangle(rules, playerCount), + }; + + /// + /// 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) + /// + 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>(); + + // 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 }; + } + + /// + /// 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. + /// + 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(); + + // 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> + { + [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 CoordsInRows(int r0, int r1, int width) + { + var s = new HashSet(); + 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 CoordsInCols(int c0, int c1, int height) + { + var s = new HashSet(); + 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 tiles, int x, int y) + { + var c = new Coord(x, y); + tiles[c.ToKey()] = new Tile { Coord = c }; + } +} diff --git a/Server/src/SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs b/Server/src/SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs index ed4eed8..20814ba 100644 --- a/Server/src/SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs @@ -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, diff --git a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs index c73c4f0..6ebec30 100644 --- a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs +++ b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs @@ -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) diff --git a/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs b/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs index b60380b..2886cb7 100644 --- a/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs @@ -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() + : JsonSerializer.Deserialize>(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 { 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 + { + _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, diff --git a/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs b/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs index c4275f9..da81aa3 100644 --- a/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameLobbyReadyHandler.cs @@ -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>( + 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>( + 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 + { _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>( + 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() + : JsonSerializer.Deserialize>(lobby.AdditionalPlayersJson) ?? new(); + + // Build the full ordered player list: [P1, P2, P3, ...]. + var allPlayerIds = new List { playerOneId, playerTwoId }; + var allDeckIds = new List { 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 + { _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 ────────────────────────────────────────────────────────── + + /// Tracks a player's readiness state within AdditionalPlayersJson. + 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; } } } diff --git a/Server/src/SOR.Game/Handlers/GameReadyHandler.cs b/Server/src/SOR.Game/Handlers/GameReadyHandler.cs index 2398437..3858693 100644 --- a/Server/src/SOR.Game/Handlers/GameReadyHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameReadyHandler.cs @@ -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>( + 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 ─────────────────────────────────────────────────────────────── + /// JSON shape for AdditionalPlayersJson entries on a GameSession. + 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> LoadDeckCardsAsync(Guid deckId, CancellationToken ct) { var deck = await _collectionDb.Decks