- Extend CustomLobby with 12 new rule override columns (Password, HandSizeCap, DiscardOnMaxHand, MaxDeckSize, MinDeckSize, MaxArchTier1, TurnTimerSeconds, TimeLimitMinutes, TurnLimit, MpBuff, BoardWidth/Height) - Extend GameRuleSet with matching non-nullable rule fields (same set) - Extend GameRules record with 9 new rule fields (all default to 0/false) - Add LobbyPreset entity (owner-scoped named rule presets) - Register LobbyPreset in GameDbContext with index on OwnerAccountId - Migration: AddCustomGameExtensions (applied to pg-forge-01) - Add custom-game-system-plan.md with full 8-phase architecture plan and deferred features tracking list - Also includes: AbilityBuilder ValueExpr dropdowns + help panel, Affinity enum/system fixes (from prior sessions) 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>
19 KiB
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):
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
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
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<LobbyPreset> LobbyPresetstoGameDbContext. - EF config:
ToTable("lobby_presets", "game"), index onOwnerAccountId.
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:
DrawPerTurn— currently ignored in the Draw phase; find the draw logic and applystate.Rules.DrawPerTurninstead of hardcoded 1.HandSizeCap/DiscardOnMaxHand— after drawing: ifHandSizeCap > 0 && hand.Count > HandSizeCap, discard excess from top (or block draw if!DiscardOnMaxHand).MpBuff— at start of each player's turn, addRules.MpBuffto all friendly unit MP values (clamped to max MP).TurnLimit— at the start of a turn, ifRules.TurnLimit > 0 && state.TurnNumber > Rules.TurnLimit, trigger game over with win condition"turn_limit"(winner = player with most ArchSpirit HP; tie = draw, loser = P2).TimeLimitMinutes— stored in rules; enforced inGameTurnTimerService(Phase 3) by checkingsession.CreatedAt.- Deck validation (
MaxDeckSize,MinDeckSize,MaxArchTier1) — add aGameEngine.ValidateDeck(deck, rules)method returning validation errors. Called inGameJoinCustomLobbyHandlerbefore 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:
internal sealed class GameTurnTimerService : BackgroundService
{
// sessionId → CancellationTokenSource for the current turn timer
private readonly ConcurrentDictionary<Guid, CancellationTokenSource> _timers = new();
public void ResetTimer(Guid sessionId, int turnTimerSeconds, int timeLimitMinutes,
DateTimeOffset sessionCreatedAt, Func<Guid, Task> onExpired) { ... }
public void CancelTimer(Guid sessionId) { ... }
}
Integration:
SaveStateAsyncinGameHandlerBasecallsGameTurnTimerService.ResetTimer(...)after committing, passing thestate.Rules.TurnTimerSecondsand anonExpiredcallback.- On expiry: the service calls
EndTurnAsync(sessionId)— a helper that loads the session and injects a syntheticgame.end_turnaction (reusingGameEndTurnHandlerlogic 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
internal sealed class SpectatorRegistryService
{
private readonly ConcurrentDictionary<Guid, ImmutableHashSet<Guid>> _map = new();
public void Register(Guid sessionId, Guid accountId) { ... }
public void Unregister(Guid sessionId, Guid accountId) { ... }
public void RemoveSession(Guid sessionId) { ... }
public IReadOnlySet<Guid> 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.ackwithGameStateDtoSpectator.
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:
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
internal sealed record ActiveVote(Guid LobbyId, Guid PresetId, CustomRulesOverride Rules,
Dictionary<Guid, bool?> Votes);
internal sealed class VoteSessionService
{
private readonly ConcurrentDictionary<Guid, ActiveVote> _votes = new(); // lobbyId → vote
public void Start(Guid lobbyId, Guid presetId, CustomRulesOverride rules, IEnumerable<Guid> 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)
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: addstring? Password = null.CustomLobby: storePassword(hashed? plain text is fine for game lobbies).JoinCustomLobbyRequest: addstring? Password = null.GameJoinCustomLobbyHandler: iflobby.Password != null && lobby.Password != req.Password→ throwGameException("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_joinedto host withGuestAccountId.
Lobby browser filters
File: Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs
ListCustomLobbiesRequest: addstring? 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 fullCustomLobbyDetailDto(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
effectiveGameRulesconstruction +CustomLobbyoverride storage to cover all new rule fields. - Pass
Passwordfrom request to entity.
GameJoinCustomLobbyHandler
File: Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs
- Extend
GameRulesconstruction to include all new fields. - Call
GameEngine.ValidateDeck(hostDeck, rules)andGameEngine.ValidateDeck(guestDeck, rules)before creating the session (requires loading decks — useCatalogDbContext).
GameListCustomLobbiesHandler
- Extend
CustomRulesDtomapping 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
CustomRulesEditorpanel → sendsgame.custom.create→ navigates toCustomLobbyRoom. - On Join: sends
game.custom.join(with optional password prompt) → navigates toCustomLobbyRoom.
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.startedpush: navigate toGameScreenwith 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
- Phase 1 — DB schema + migration (new columns + LobbyPreset table)
- Phase 2 — GameRules record extension + GameEngine fixes (DrawPerTurn, HandSizeCap, MpBuff, TurnLimit, ValidateDeck)
- Phase 7 — Extend existing create/join/list handlers + DTOs for all new rule fields
- Phase 3 — GameTurnTimerService
- Phase 4 — SpectatorRegistryService + GameSpectateHandler + PushStateToPlayersAsync changes
- Phase 5 — VoteSessionService + all preset handlers
- Phase 6 — Password, host-join push, lobby filters, GameGetLobbyHandler
- 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
- Full lobby flow: Create lobby → second client joins → both navigate to game screen → game starts normally.
- New rules applied: Set
DrawPerTurn = 2, play to Draw phase → confirm 2 cards drawn. SetHandSizeCap = 5→ confirm hand is trimmed. - Turn timer: Set
TurnTimerSeconds = 30→ leave a turn idle for 30s → confirm turn auto-ends. - Spectator: Third client sends
game.spectate→ receives state with hand counts only → receives state updates as game progresses. - Preset save/load: Host saves preset → Guest proposes loading it → Host votes yes → lobby rules update → both clients see new rules.
- Password: Create lobby with password → join without password → error. Join with correct password → succeeds.
- Deck validation: Set
MinDeckSize = 40→ try to join with 30-card deck → error.