# Plan: Extended Custom Game System ## Context The game already has a minimal 2-player custom lobby (create/join/list), but it is missing most of the requested features: the full rule set, spectating, board templates, preset save/reload with voting, and all client-side UI. This plan extends the existing foundation into a complete custom game system. **Scope decisions:** - **2-player only** for now (engine is strictly 2-player; MaxPlayers is a UI-only stub) - **Hex tile** is a stub (field stored, option shown as disabled in client) - **Save/reload** = named lobby-config presets (NOT mid-match state resume) - **Turn timer** = auto-end turn when expired (not auto-concede) - **Lobby privacy** = public + optional password --- ## Deferred / Out of Scope The following features are intentionally excluded from this implementation pass. Track these for future work: | Feature | Notes | |---|---| | **Board templates** | `BoardTemplateIdOverride` column added to schema as a nullable `Guid`, but no `BoardTemplate` entity, no admin page to create/edit templates, and no engine logic to apply a template. Wire-up deferred until template format is designed. | | **Admin: BoardTemplate editor** | Full CRUD page for named board templates (tile layout, size, special tiles). Requires defining what a template actually stores (JSON layout? preset size only?). | | **Admin: Custom lobby oversight** | Admin page listing all active/recent custom lobbies, with ability to cancel a lobby or kick a player. | | **Hex tile shape** | `TileShape` field can be stored as an enum stub (Square / Hex), but the engine, client renderer, and pathfinding are square-only. Hex is UI-disabled. | | **3+ player support** | `MinPlayers` / `MaxPlayers` are UI-only stubs. Engine is strictly 2-player. Multi-player requires engine rewrite. | | **Lobby chat** | In-lobby text chat between host and guest before the game starts. | | **Friend invite / direct invite** | Invite a specific player by name/ID to your lobby, bypassing the browser. | | **Spectate from browser** | Browsing and joining in-progress games as a spectator. Current plan only covers `game.spectate` by known `SessionId`. Requires a `game.custom.list_active` endpoint and browser UI flow. | | **Public preset sharing** | Presets are personal (owner-scoped) only. Public presets browsable by all players are deferred. | | **Replay system** | Recording and replaying completed games. Related to spectating infrastructure. | | **OP/ELO rewards for custom games** | Custom games give 0 OP and no ELO change. A configurable rewards toggle is deferred. | | **Vote "concede" option** | The preset-load vote only supports yes/no. A third "concede the lobby" option (host or guest exits if vote drags on) is deferred. | | **Lobby update while waiting** | Host changing rules after the guest has joined (without a preset vote) — rules are currently only editable while lobby is `Open`. Real-time rule editing in `Full` state requires a push + guest acknowledgement flow. | --- ## Phase 1 — DB Schema Extensions ### New fields on `CustomLobby` **File:** `Server/src/SOR.Database/Entities/Game/CustomLobby.cs` Add nullable override columns (parallel to existing pattern): ```csharp public string? Password { get; set; } // null = no password public int? HandSizeCapOverride { get; set; } // 0 = no cap public bool? DiscardOnMaxHandOverride { get; set; } public int? MaxDeckSizeOverride { get; set; } // 0 = no limit public int? MinDeckSizeOverride { get; set; } public int? MaxArchTier1Override { get; set; } // 0 = no limit public int? TurnTimerSecondsOverride { get; set; } // 0 = no timer public int? TimeLimitMinutesOverride { get; set; } // 0 = no limit public int? TurnLimitOverride { get; set; } // 0 = no limit public int? MpBuffOverride { get; set; } // flat bonus to unit MP per turn public int? BoardWidthOverride { get; set; } public int? BoardHeightOverride { get; set; } ``` ### New fields on `GameRuleSet` **File:** `Server/src/SOR.Database/Entities/Game/GameRuleSet.cs` Same set of non-nullable fields with sensible defaults (0 = disabled for caps/limits). ### Extend `GameRules` record **File:** `Server/src/SOR.Game/GameRules.cs` ```csharp public int HandSizeCap { get; init; } = 0; // 0 = no cap public bool DiscardOnMaxHand { get; init; } = false; public int MaxDeckSize { get; init; } = 0; public int MinDeckSize { get; init; } = 0; public int MaxArchTier1 { get; init; } = 0; // 0 = no limit public int TurnTimerSeconds { get; init; } = 0; // 0 = no timer public int TimeLimitMinutes { get; init; } = 0; public int TurnLimit { get; init; } = 0; public int MpBuff { get; init; } = 0; // added to each unit's MP at turn start ``` ### New entity: `LobbyPreset` **File (new):** `Server/src/SOR.Database/Entities/Game/LobbyPreset.cs` ```csharp public sealed class LobbyPreset { public Guid Id { get; set; } = Guid.NewGuid(); public Guid OwnerAccountId { get; set; } public string Name { get; set; } = string.Empty; public string RulesJson { get; set; } = "{}"; // serialized CustomRulesOverride public DateTimeOffset CreatedAt { get; set; } } ``` - Add `DbSet LobbyPresets` to `GameDbContext`. - EF config: `ToTable("lobby_presets", "game")`, index on `OwnerAccountId`. ### Migration **Dir:** `Server/src/SOR.Database/Migrations/Game/` One migration (`AddCustomGameExtensions`) adding: - All new columns to `game.custom_lobbies` - All new columns to `game.game_rule_sets` - New table `game.lobby_presets` - Update `GameDbContextModelSnapshot.cs` --- ## Phase 2 — GameRules Application in GameEngine **File:** `Server/src/SOR.Game/GameEngine.cs` (and related engine files) Fixes and new rule enforcement: 1. **`DrawPerTurn`** — currently ignored in the Draw phase; find the draw logic and apply `state.Rules.DrawPerTurn` instead of hardcoded 1. 2. **`HandSizeCap` / `DiscardOnMaxHand`** — after drawing: if `HandSizeCap > 0 && hand.Count > HandSizeCap`, discard excess from top (or block draw if `!DiscardOnMaxHand`). 3. **`MpBuff`** — at start of each player's turn, add `Rules.MpBuff` to all friendly unit MP values (clamped to max MP). 4. **`TurnLimit`** — at the start of a turn, if `Rules.TurnLimit > 0 && state.TurnNumber > Rules.TurnLimit`, trigger game over with win condition `"turn_limit"` (winner = player with most ArchSpirit HP; tie = draw, loser = P2). 5. **`TimeLimitMinutes`** — stored in rules; enforced in `GameTurnTimerService` (Phase 3) by checking `session.CreatedAt`. 6. **Deck validation** (`MaxDeckSize`, `MinDeckSize`, `MaxArchTier1`) — add a `GameEngine.ValidateDeck(deck, rules)` method returning validation errors. Called in `GameJoinCustomLobbyHandler` before creating the session (only when custom rules have non-zero limits). --- ## Phase 3 — Turn Timer Service **File (new):** `Server/src/SOR.Game/GameTurnTimerService.cs` A `BackgroundService` singleton managing per-session turn timers: ```csharp internal sealed class GameTurnTimerService : BackgroundService { // sessionId → CancellationTokenSource for the current turn timer private readonly ConcurrentDictionary _timers = new(); public void ResetTimer(Guid sessionId, int turnTimerSeconds, int timeLimitMinutes, DateTimeOffset sessionCreatedAt, Func onExpired) { ... } public void CancelTimer(Guid sessionId) { ... } } ``` **Integration:** - `SaveStateAsync` in `GameHandlerBase` calls `GameTurnTimerService.ResetTimer(...)` after committing, passing the `state.Rules.TurnTimerSeconds` and an `onExpired` callback. - On expiry: the service calls `EndTurnAsync(sessionId)` — a helper that loads the session and injects a synthetic `game.end_turn` action (reusing `GameEndTurnHandler` logic via a shared static method extracted from the handler). - Register as singleton + hosted service in `ServiceRegistration.cs`. --- ## Phase 4 — Spectator Support ### `SpectatorRegistryService` (singleton) **File (new):** `Server/src/SOR.Game/SpectatorRegistryService.cs` ```csharp internal sealed class SpectatorRegistryService { private readonly ConcurrentDictionary> _map = new(); public void Register(Guid sessionId, Guid accountId) { ... } public void Unregister(Guid sessionId, Guid accountId) { ... } public void RemoveSession(Guid sessionId) { ... } public IReadOnlySet GetSpectators(Guid sessionId) { ... } } ``` ### New handler: `GameSpectateHandler` **File (new):** `Server/src/SOR.Game/Handlers/GameSpectateHandler.cs` - Message: `game.spectate` - Request: `SpectateRequest(Guid SessionId)` - Loads session (must be Active), registers caller in `SpectatorRegistryService`. - Returns current state filtered for spectator (both hands as count-only). - Ack: `game.spectate.ack` with `GameStateDtoSpectator`. ### `GameStateDto` spectator variant **File:** `Server/src/SOR.Game/GameMessages.cs` or engine DTO file Add `GameEngine.ToDtoSpectator(state)` — same as `ToDto` but both `MyHand` and `OpponentHand` contain only the card count (no `CardId`, no `InstanceId`). Alternatively, pass a new `viewerAccountId = null` sentinel to `ToDto` that triggers the spectator path. ### Push to spectators **File:** `Server/src/SOR.Game/Handlers/GameHandlerBase.cs` Extend `PushStateToPlayersAsync` to also push to spectators: ```csharp foreach (var specId in spectatorRegistry.GetSpectators(session.Id)) await clientPush.PushAsync(specId.ToString(), ServerMessage.Push("game.state_update", new GameStateUpdatePush(GameEngine.ToDtoSpectator(state))), ct); ``` Also call `spectatorRegistry.RemoveSession` in `FinalizeGameAsync` after pushing `game.over` to spectators. --- ## Phase 5 — Preset Save / Propose / Vote ### `VoteSessionService` (singleton) **File (new):** `Server/src/SOR.Game/VoteSessionService.cs` ```csharp internal sealed record ActiveVote(Guid LobbyId, Guid PresetId, CustomRulesOverride Rules, Dictionary Votes); internal sealed class VoteSessionService { private readonly ConcurrentDictionary _votes = new(); // lobbyId → vote public void Start(Guid lobbyId, Guid presetId, CustomRulesOverride rules, IEnumerable voters); public VoteOutcome Cast(Guid lobbyId, Guid accountId, bool vote); // Pending/Approved/Rejected public ActiveVote? Get(Guid lobbyId); public void Cancel(Guid lobbyId); } ``` ### New handlers (in `Server/src/SOR.Game/Handlers/`) | Handler | Message | Description | |---|---|---| | `GameSavePresetHandler` | `game.custom.preset.save` | Save lobby's current rules as a named `LobbyPreset` (only participants). | | `GameListPresetsHandler` | `game.custom.preset.list` | Return caller's saved presets. | | `GameDeletePresetHandler` | `game.custom.preset.delete` | Delete a preset owned by the caller. | | `GameProposePresetHandler` | `game.custom.preset.propose` | Host proposes loading a preset; starts `VoteSession`; pushes `game.custom.preset.vote_requested` to other player. | | `GameVotePresetHandler` | `game.custom.preset.vote` | Cast yes/no. If approved: update lobby rule overrides + push `game.custom.lobby_updated` to both. If rejected: push `game.custom.preset.vote_rejected`. | ### New message types (in `GameMessages.cs`) ```csharp record SavePresetRequest(Guid LobbyId, string PresetName); record ListPresetsRequest; record DeletePresetRequest(Guid PresetId); record ProposePresetRequest(Guid LobbyId, Guid PresetId); record VotePresetRequest(Guid LobbyId, bool Accept); record LobbyPresetDto(Guid PresetId, string Name, CustomRulesOverride Rules, DateTimeOffset CreatedAt); record PresetVoteRequestedPush(Guid LobbyId, Guid PresetId, string PresetName, CustomRulesOverride Rules); record LobbyUpdatedPush(Guid LobbyId, CustomRulesDto NewRules); ``` --- ## Phase 6 — Lobby Enhancements ### Password protection - `CreateCustomLobbyRequest`: add `string? Password = null`. - `CustomLobby`: store `Password` (hashed? plain text is fine for game lobbies). - `JoinCustomLobbyRequest`: add `string? Password = null`. - `GameJoinCustomLobbyHandler`: if `lobby.Password != null && lobby.Password != req.Password` → throw `GameException("WRONG_PASSWORD")`. ### Host notification on guest join **File:** `Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs` - After guest joins (lobby now Full), push `game.custom.guest_joined` to host with `GuestAccountId`. ### Lobby browser filters **File:** `Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs` - `ListCustomLobbiesRequest`: add `string? NameSearch = null`, `bool ShowPasswordProtected = true`. - Apply `.Where(l => NameSearch == null || l.Name.Contains(NameSearch))` etc. ### Get single lobby **File (new):** `Server/src/SOR.Game/Handlers/GameGetLobbyHandler.cs` - `game.custom.get` — returns full `CustomLobbyDetailDto` (all rules, host/guest presence) for a specific lobby ID. --- ## Phase 7 — Update Existing Handlers for New Rules ### `GameCreateCustomLobbyHandler` **File:** `Server/src/SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs` - Extend `effective` `GameRules` construction + `CustomLobby` override storage to cover all new rule fields. - Pass `Password` from request to entity. ### `GameJoinCustomLobbyHandler` **File:** `Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs` - Extend `GameRules` construction to include all new fields. - Call `GameEngine.ValidateDeck(hostDeck, rules)` and `GameEngine.ValidateDeck(guestDeck, rules)` before creating the session (requires loading decks — use `CatalogDbContext`). ### `GameListCustomLobbiesHandler` - Extend `CustomRulesDto` mapping to include new rule fields. - Apply new filters. ### `CustomRulesDto` and `CustomRulesOverride` records **File:** `Server/src/SOR.Game/GameMessages.cs` - Add all new fields with defaults to both records. --- ## Phase 8 — Client Scenes ### New: `CustomLobbyBrowser.tscn` + `custom_lobby_browser.gd` **Dir:** `Client/origin-client/scenes/lobby/` - Full-screen scene with filter bar + lobby list. - Filter: name search input, refresh button. - Each row: lobby name, host username, player count (1/2), key rules summary, Join button. - "Create Lobby" button → opens `CustomRulesEditor` panel → sends `game.custom.create` → navigates to `CustomLobbyRoom`. - On Join: sends `game.custom.join` (with optional password prompt) → navigates to `CustomLobbyRoom`. ### New: `CustomLobbyRoom.tscn` + `custom_lobby_room.gd` **Dir:** `Client/origin-client/scenes/lobby/` - Shows both player slots (host / guest or "Waiting..."). - Rules panel (read-only for guest, editable for host). - Preset buttons: Save, Load (host only) — opens preset list dialog. - Start is automatic when guest joins (game.custom.started push). - Leave button → `game.custom.leave`. - On receiving `game.custom.started` push: navigate to `GameScreen` with session ID. ### New: `CustomRulesEditor.tscn` + `custom_rules_editor.gd` - Panel component embedded in both browser (create flow) and lobby room (host editing). - One control per rule (sliders/spinboxes for ints, checkboxes for bools). - "Save as Preset" button (in room only). ### `game_screen.gd` — spectator mode **File:** `Client/origin-client/scenes/game/game_screen.gd` - On `game.spectate.ack`: set `_is_spectator = true`. - When `_is_spectator`: hide hand panel and action buttons; show "SPECTATING" label. - Hand display for both players shows count label only. --- ## Implementation Order 1. **Phase 1** — DB schema + migration (new columns + LobbyPreset table) 2. **Phase 2** — GameRules record extension + GameEngine fixes (DrawPerTurn, HandSizeCap, MpBuff, TurnLimit, ValidateDeck) 3. **Phase 7** — Extend existing create/join/list handlers + DTOs for all new rule fields 4. **Phase 3** — GameTurnTimerService 5. **Phase 4** — SpectatorRegistryService + GameSpectateHandler + PushStateToPlayersAsync changes 6. **Phase 5** — VoteSessionService + all preset handlers 7. **Phase 6** — Password, host-join push, lobby filters, GameGetLobbyHandler 8. **Phase 8** — Client scenes (CustomLobbyBrowser, CustomLobbyRoom, CustomRulesEditor, spectator mode) --- ## Key Files Summary | File | Change | |---|---| | `SOR.Database/Entities/Game/CustomLobby.cs` | +12 new override columns | | `SOR.Database/Entities/Game/GameRuleSet.cs` | +9 new rule fields | | `SOR.Database/Entities/Game/LobbyPreset.cs` | **NEW** entity | | `SOR.Database/Migrations/Game/` | **NEW** migration `AddCustomGameExtensions` | | `SOR.Game/GameRules.cs` | +9 new rule fields | | `SOR.Game/GameEngine.cs` | Fix DrawPerTurn; add HandSizeCap, MpBuff, TurnLimit, ValidateDeck | | `SOR.Game/GameMessages.cs` | Extend DTOs + add preset/spectate/vote message types | | `SOR.Game/GameTurnTimerService.cs` | **NEW** BackgroundService | | `SOR.Game/SpectatorRegistryService.cs` | **NEW** singleton | | `SOR.Game/VoteSessionService.cs` | **NEW** singleton | | `SOR.Game/Handlers/GameHandlerBase.cs` | Extend PushStateToPlayersAsync for spectators | | `SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs` | Extend for all new rules + password | | `SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs` | Extend rules + deck validation + password check | | `SOR.Game/Handlers/GameListCustomLobbiesHandler.cs` | Extend DTO + filters | | `SOR.Game/Handlers/GameSpectateHandler.cs` | **NEW** | | `SOR.Game/Handlers/GameSavePresetHandler.cs` | **NEW** | | `SOR.Game/Handlers/GameListPresetsHandler.cs` | **NEW** | | `SOR.Game/Handlers/GameDeletePresetHandler.cs` | **NEW** | | `SOR.Game/Handlers/GameProposePresetHandler.cs` | **NEW** | | `SOR.Game/Handlers/GameVotePresetHandler.cs` | **NEW** | | `SOR.Game/Handlers/GameGetLobbyHandler.cs` | **NEW** | | `SOR.Game/ServiceRegistration.cs` | Register all new services + handlers | | `SOR.Host/Program.cs` | *(No changes — wiring stays in ServiceRegistration)* | | `Client/origin-client/scenes/lobby/CustomLobbyBrowser.tscn` | **NEW** | | `Client/origin-client/scenes/lobby/custom_lobby_browser.gd` | **NEW** | | `Client/origin-client/scenes/lobby/CustomLobbyRoom.tscn` | **NEW** | | `Client/origin-client/scenes/lobby/custom_lobby_room.gd` | **NEW** | | `Client/origin-client/scenes/lobby/CustomRulesEditor.tscn` | **NEW** | | `Client/origin-client/scenes/lobby/custom_rules_editor.gd` | **NEW** | | `Client/origin-client/scenes/game/game_screen.gd` | +spectator mode | --- ## Verification 1. **Full lobby flow**: Create lobby → second client joins → both navigate to game screen → game starts normally. 2. **New rules applied**: Set `DrawPerTurn = 2`, play to Draw phase → confirm 2 cards drawn. Set `HandSizeCap = 5` → confirm hand is trimmed. 3. **Turn timer**: Set `TurnTimerSeconds = 30` → leave a turn idle for 30s → confirm turn auto-ends. 4. **Spectator**: Third client sends `game.spectate` → receives state with hand counts only → receives state updates as game progresses. 5. **Preset save/load**: Host saves preset → Guest proposes loading it → Host votes yes → lobby rules update → both clients see new rules. 6. **Password**: Create lobby with password → join without password → error. Join with correct password → succeeds. 7. **Deck validation**: Set `MinDeckSize = 40` → try to join with 30-card deck → error.