8280 lines
310 KiB
Markdown
8280 lines
310 KiB
Markdown
# Combined Markdown Report
|
||
|
||
Generated: 2026-04-15T14:03:39Z
|
||
|
||
Total files: 40
|
||
|
||
---
|
||
|
||
## File: Client/context-files/global.md
|
||
|
||
# Global Client Rules and Shared Contracts
|
||
|
||
## Global Persistent UI (All Scenes)
|
||
- `Settings` button is present in every scene.
|
||
- `Report Bug` button is present in every scene.
|
||
- Placement and interaction pattern must remain consistent across scenes.
|
||
|
||
## Global Scene Transition Rules
|
||
- Ordered startup/auth flow: `ClientLaunch` -> `Login` -> `MainMenu`.
|
||
- `Register` is reachable from `Login` and returns to `Login` unless server returns immediate auth tokens.
|
||
- Gameplay scenes are reachable from lobby scenes (`RankedPlay`, `CustomPlay`) only after server-authoritative match start.
|
||
|
||
## Shared Transport Notes
|
||
- Persistent real-time session to relay/hub for presence + notifications.
|
||
- HTTPS API calls for auth/account/content operations.
|
||
- Auth model: short-lived access token + refresh token.
|
||
- Device/session id tracked by server.
|
||
- Every payload includes `requestId` and `serverTimeUtc`.
|
||
- List endpoints support paging (`page`, `pageSize`) and sorting.
|
||
|
||
## Global Input Consistency Rules
|
||
- Multi-touch support is required for touch-capable devices.
|
||
- Core camera gestures and selection semantics are shared across all scenes.
|
||
- Scene-specific controls may add actions, but must not override baseline navigation behavior.
|
||
- Input remapping and accessibility options should apply globally, not per-scene.
|
||
|
||
## Global Social/Chat Rules
|
||
- Baseline channels: `System`, `General`, `Friends`.
|
||
- Friend moderation actions where identity is visible: `Add Friend`, `Remove Friend`, `Block`.
|
||
- Lobby-specific channel sections are context-sensitive and shown only inside the active lobby scene.
|
||
|
||
## Security and Validation Baseline
|
||
- Server authoritative for identity/session, ownership, deck legality, and entitlements.
|
||
- Client authoritative for rendering and non-authoritative UI state (filters/sorts).
|
||
- Every mutating request requires:
|
||
- valid access token
|
||
- account ownership check
|
||
- anti-replay safeguards (`requestId`, timestamp window)
|
||
|
||
---
|
||
|
||
## File: Client/context-files/README.md
|
||
|
||
# Client Context Files
|
||
|
||
Client-specific planning lives here.
|
||
|
||
Shared domain context files were moved to:
|
||
`../../Shared/context-files/`
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/account-management.scene.md
|
||
|
||
# AccountManagement Scene
|
||
|
||
## UI
|
||
- Identity panel: username, email, profile image
|
||
- Password change modal:
|
||
- fields: `new password`, `confirm password`
|
||
- actions: `Submit`, `Cancel`
|
||
- Linked accounts panel:
|
||
- `Link Account` for OAuth providers
|
||
- linked provider status list
|
||
- Stats panel:
|
||
- Origin points, Win, Loss, Forfeit, Draw, Cards owned, Cards played
|
||
- Spending panel:
|
||
- `Total Spent` censored by default
|
||
- uncensor toggle
|
||
- money spent + origin points spent
|
||
- `Download Report` for full spending profile
|
||
- Spending controls panel:
|
||
- set monthly spending cap (money and/or origin points)
|
||
- cap lock-enforced once set
|
||
- cap can be changed once per month
|
||
- warnings required before set/change
|
||
- show next eligible cap-change date/time
|
||
- Legal links panel:
|
||
- TOS, EULA, other required legal docs
|
||
|
||
## Client
|
||
- Display profile, linked providers, stats, spending, legal docs.
|
||
- Support password update workflow.
|
||
- Support spending cap update workflow with warning acknowledgment.
|
||
|
||
## Server
|
||
- Return account profile, linked providers, stats, spending summary.
|
||
- Process password changes.
|
||
- Enforce spending cap locks and cooldown windows.
|
||
- Return spending report export URL.
|
||
- Return legal document metadata and URLs.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`AccountOverviewRequest`)
|
||
- `requestId`, `accountId`
|
||
|
||
### Server -> Client (`AccountOverviewResponse`)
|
||
- `requestId`, `username`, `email`, `profileImageUrl`, `linkedProviders`
|
||
- `stats`: `originPoints`, `wins`, `losses`, `forfeits`, `draws`, `cardsOwned`, `cardsPlayed`
|
||
- `spendingSummary`: `moneySpent`, `originPointsSpent`, `censoredByDefault`
|
||
- `spendingCap`: `capEnabled`, `moneyCapAmount`, `originPointsCapAmount`, `effectiveFromUtc`, `nextCapChangeAllowedAtUtc`, `lockReason`
|
||
- `legalDocuments` (name + url)
|
||
|
||
### Client -> Server (`ChangePasswordRequest`)
|
||
- `requestId`, `currentPassword` (if policy requires), `newPassword`, `confirmPassword`
|
||
|
||
### Server -> Client (`ChangePasswordResponse`)
|
||
- `requestId`, `success`, `errorCode`
|
||
|
||
### Client -> Server (`LinkOAuthRequest`)
|
||
- `requestId`, `provider`
|
||
|
||
### Server -> Client (`LinkOAuthResponse`)
|
||
- `requestId`, `success`, `linkedProviders`, `errorCode`
|
||
|
||
### Client -> Server (`SpendingCapUpdateRequest`)
|
||
- `requestId`, `moneyCapAmount` (optional), `originPointsCapAmount` (optional), `acceptWarning`
|
||
|
||
### Server -> Client (`SpendingCapUpdateResponse`)
|
||
- `requestId`, `success`, `spendingCap`, `nextCapChangeAllowedAtUtc`, `warningMessage`, `errorCode`
|
||
|
||
### Client -> Server (`SpendingReportRequest`)
|
||
- `requestId`, `format` (`csv`, `json`, `pdf`)
|
||
|
||
### Server -> Client (`SpendingReportResponse`)
|
||
- `requestId`, `success`, `downloadUrl`, `expiresAtUtc`, `errorCode`
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/bazaar.scene.md
|
||
|
||
# Bazaar Scene
|
||
|
||
## Status
|
||
Active draft.
|
||
|
||
## Goals
|
||
- Provide a trusted in-game economy hub.
|
||
- Support player-to-player card marketplace using Origin Points.
|
||
- Support first-party store purchases (booster packs, premade decks, Origin Points).
|
||
- Support card sacrifice/disenchant flow for Origin Points.
|
||
- Ensure full transaction auditability and chain of custody for anti-cheat and bug investigation.
|
||
|
||
## Bazaar Sections (UI)
|
||
|
||
### 1) Player Marketplace
|
||
- Search/browse listed cards.
|
||
- View listing details:
|
||
- card identity (definition + variant)
|
||
- seller
|
||
- price (Origin Points)
|
||
- listed-at timestamp
|
||
- listing status
|
||
- Actions:
|
||
- buy listing
|
||
- cancel own listing
|
||
- create listing from owned inventory
|
||
- Filters/sort:
|
||
- card name/type/rarity/affinity
|
||
- min/max price
|
||
- newest/price asc/price desc
|
||
|
||
### 2) Official Store
|
||
- Buy booster packs.
|
||
- Buy premade decks.
|
||
- Buy Origin Points (USD purchase flow).
|
||
- Payment method display + confirmation modal.
|
||
- Show SKU details and pricing in:
|
||
- USD (fiat)
|
||
- Origin Points (when applicable)
|
||
|
||
### 3) Sacrifice / Disenchant
|
||
- Select cards from owned inventory.
|
||
- Preview Origin Points return before confirm.
|
||
- Explicit irreversible warning.
|
||
- Confirm action flow:
|
||
- cards are removed from active inventory (or flagged destroyed server-side)
|
||
- Origin Points credited
|
||
|
||
### 4) Ledger / History (Player View)
|
||
- Personal transaction history timeline:
|
||
- marketplace buys/sells
|
||
- store purchases
|
||
- sacrifices
|
||
- refunds/reversals
|
||
- Receipt details with transaction id.
|
||
|
||
## Client Interactions
|
||
- Load Bazaar bootstrap on scene open.
|
||
- Keep balances (Origin Points) fresh after every economy mutation.
|
||
- Use optimistic UI sparingly for economy operations; server response is source of truth.
|
||
- Require explicit confirmation modals for:
|
||
- listing creation
|
||
- purchase
|
||
- sacrifice
|
||
- USD spend
|
||
- Show clear pending/success/failure states for every transaction.
|
||
|
||
## Server Rules and Authority
|
||
- Server is fully authoritative for inventory ownership, balances, listing state, and purchase validity.
|
||
- Marketplace transactions must be atomic (debit buyer, credit seller, transfer card ownership, write ledger).
|
||
- Sacrifice operation must be atomic (mark destroyed/remove ownership, grant points, write ledger).
|
||
- All purchases (USD and Origin Points) must write immutable audit records.
|
||
- Every item/asset transaction must maintain chain-of-custody links.
|
||
|
||
## Data Contracts (Draft)
|
||
|
||
### Client -> Server (`BazaarBootstrapRequest`)
|
||
- `requestId`
|
||
- `accountId`
|
||
|
||
### Server -> Client (`BazaarBootstrapResponse`)
|
||
- `requestId`
|
||
- `originPointsBalance`
|
||
- `marketplaceSummary`
|
||
- `storeCatalog` (boosters, premade decks, point packs)
|
||
- `sacrificeRules`
|
||
- `recentTransactions`
|
||
|
||
---
|
||
|
||
### Marketplace
|
||
|
||
#### Client -> Server (`MarketplaceSearchRequest`)
|
||
- `requestId`
|
||
- `filters`
|
||
- `sort`
|
||
- `page`
|
||
- `pageSize`
|
||
|
||
#### Server -> Client (`MarketplaceSearchResponse`)
|
||
- `requestId`
|
||
- `results`
|
||
- `totalCount`
|
||
|
||
#### Client -> Server (`MarketplaceCreateListingRequest`)
|
||
- `requestId`
|
||
- `cardInstanceId`
|
||
- `priceOriginPoints`
|
||
|
||
#### Server -> Client (`MarketplaceCreateListingResponse`)
|
||
- `requestId`
|
||
- `success`
|
||
- `listingId`
|
||
- `errorCode` (if failed)
|
||
|
||
#### Client -> Server (`MarketplaceBuyListingRequest`)
|
||
- `requestId`
|
||
- `listingId`
|
||
|
||
#### Server -> Client (`MarketplaceBuyListingResponse`)
|
||
- `requestId`
|
||
- `success`
|
||
- `transactionId`
|
||
- `updatedBalance`
|
||
- `errorCode` (if failed)
|
||
|
||
#### Client -> Server (`MarketplaceCancelListingRequest`)
|
||
- `requestId`
|
||
- `listingId`
|
||
|
||
#### Server -> Client (`MarketplaceCancelListingResponse`)
|
||
- `requestId`
|
||
- `success`
|
||
- `errorCode` (if failed)
|
||
|
||
---
|
||
|
||
### Store Purchases
|
||
|
||
#### Client -> Server (`StorePurchaseRequest`)
|
||
- `requestId`
|
||
- `skuId`
|
||
- `currency` (`USD` | `ORIGIN_POINTS`)
|
||
- `paymentMethodId` (required for USD)
|
||
|
||
#### Server -> Client (`StorePurchaseResponse`)
|
||
- `requestId`
|
||
- `success`
|
||
- `transactionId`
|
||
- `receiptId`
|
||
- `updatedBalance`
|
||
- `grantedItems`
|
||
- `errorCode` (if failed)
|
||
|
||
---
|
||
|
||
### Sacrifice / Disenchant
|
||
|
||
#### Client -> Server (`SacrificeCardsRequest`)
|
||
- `requestId`
|
||
- `cardInstanceIds`
|
||
- `confirmIrreversible` (`true` required)
|
||
|
||
#### Server -> Client (`SacrificeCardsResponse`)
|
||
- `requestId`
|
||
- `success`
|
||
- `transactionId`
|
||
- `originPointsGranted`
|
||
- `updatedBalance`
|
||
- `destroyedCardRefs`
|
||
- `errorCode` (if failed)
|
||
|
||
---
|
||
|
||
### Ledger / Audit
|
||
|
||
#### Client -> Server (`TransactionHistoryRequest`)
|
||
- `requestId`
|
||
- `filters`
|
||
- `page`
|
||
- `pageSize`
|
||
|
||
#### Server -> Client (`TransactionHistoryResponse`)
|
||
- `requestId`
|
||
- `entries`
|
||
- `totalCount`
|
||
|
||
## Audit / Chain of Custody Requirements (Critical)
|
||
- Every economy event writes an immutable ledger entry with:
|
||
- `transactionId`
|
||
- `eventType`
|
||
- `accountId`(s) involved
|
||
- asset references (`cardInstanceId`, `skuId`, etc.)
|
||
- balance deltas (before/after)
|
||
- timestamp + request correlation (`requestId`)
|
||
- Every card instance should have a custody trail:
|
||
- minted/acquired -> listed -> sold/transferred -> sacrificed/destroyed
|
||
- USD purchases must include payment provider reference id(s) and receipt linkage.
|
||
- Support admin/internal investigation queries for suspicious activity patterns.
|
||
|
||
## Fraud / Abuse Signals (Planned)
|
||
- Repeated rapid buy/sell loops between same accounts.
|
||
- Outlier pricing patterns.
|
||
- High-frequency sacrifices after suspicious acquisitions.
|
||
- Chargeback/refund correlation with asset transfers.
|
||
- Multi-account linkage risk indicators.
|
||
|
||
## Open Questions
|
||
1. Should marketplace fees/taxes apply on player sales?
|
||
2. Are there listing limits per user or per card rarity?
|
||
3. Is there a hold/escrow period before purchased cards can be relisted?
|
||
4. What refund policy exists for Origin Points and digital goods?
|
||
5. Should sacrifice values be static or dynamic by card metadata?
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/card-viewer.scene.md
|
||
|
||
# CardViewer Scene
|
||
|
||
## UI
|
||
- Search input
|
||
- Filter/sort controls
|
||
- Card grid/list
|
||
- Card detail drawer/modal
|
||
|
||
## Client
|
||
- Browse card library and owned-only views.
|
||
|
||
## Server
|
||
- Return searchable metadata, ownership projection, and variant manifests.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`CardSearchRequest`)
|
||
- `requestId`, `query`, `filters`, `sort`, `page`, `pageSize`
|
||
|
||
### Server -> Client (`CardSearchResponse`)
|
||
- `requestId`, `results`, `totalCount`, `facets`
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/client-launch.scene.md
|
||
|
||
# ClientLaunch Scene
|
||
|
||
## UI
|
||
- Splash/logo
|
||
- Build/version text
|
||
- Background init indicator
|
||
- Version/patch status panel when update checks run
|
||
- Patch progress bar when updates are required
|
||
|
||
## Client
|
||
- Boot local config, device fingerprint, cached token state.
|
||
- Initialize telemetry/session id.
|
||
- Perform client/content version check during launch.
|
||
- If update required: show patch flow, apply update, and continue.
|
||
- If up-to-date: initialize transport prerequisites and transition to `Login`.
|
||
|
||
## Server
|
||
- Provide version support status and update manifest metadata.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`VersionStatusRequest`)
|
||
- `requestId`, `clientVersion`, `contentVersion`, `platform`
|
||
|
||
### Server -> Client (`VersionStatusResponse`)
|
||
- `requestId`, `isClientSupported`, `requiresClientUpdate`, `requiresContentUpdate`
|
||
- `minimumAllowedVersion`, `targetClientVersion`, `targetContentVersion`
|
||
- `updateManifestUrl`, `updateNotes` (optional), `blockReason` (if unsupported)
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/collection-hub.scene.md
|
||
|
||
# CollectionHub Scene
|
||
|
||
## UI
|
||
- Tab nav (`DeckEditor`, `CardViewer`, `Cosmetics`)
|
||
- Collection summary strip
|
||
|
||
## Client
|
||
- Load owned cards, deck list, cosmetics.
|
||
|
||
## Server
|
||
- Return collection inventory, deck metadata, validation rules, cosmetic inventory.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`CollectionBootstrapRequest`)
|
||
- `requestId`, `accountId`, `includeInventory`, `includeDecks`, `includeCosmetics`
|
||
|
||
### Server -> Client (`CollectionBootstrapResponse`)
|
||
- `requestId`, `cardInventory`, `deckSummaries`, `cosmeticInventory`, `collectionStats`, `rulesVersion`
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/cosmetics.scene.md
|
||
|
||
# Cosmetics Scene
|
||
|
||
## UI
|
||
- Cosmetic category selector (back/trim/art/model)
|
||
- Preview pane
|
||
- Owned/locked state indicators
|
||
- Equip/apply controls
|
||
|
||
## Client
|
||
- Display and preview cosmetic options; equip selections.
|
||
|
||
## Server
|
||
- Verify ownership/compatibility and persist equipped defaults/overrides.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`CosmeticEquipRequest`)
|
||
- `requestId`, `scope`, `targetId`, `cardBackId`, `trimId`, `artVariantId`, `modelVariantId`
|
||
|
||
### Server -> Client (`CosmeticEquipResponse`)
|
||
- `requestId`, `success`, `equippedState`, `errorCode`
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/custom-play.scene.md
|
||
|
||
# CustomPlay Scene (Unranked Lobby)
|
||
|
||
## UI
|
||
- Custom games list
|
||
- Filter controls (open slots, format/rules tags, region, friends-only)
|
||
- Game row indicators for key rule categories
|
||
- Rules detail tooltip/panel on hover/focus with full ruleset display
|
||
- Create custom game panel:
|
||
- lobby name
|
||
- privacy
|
||
- ruleset configuration
|
||
- deck/archspirit constraints
|
||
- max players/spectators
|
||
- Lobby chat subsection:
|
||
- unranked/custom channels visible while in this scene
|
||
|
||
## Client
|
||
- Fetch and render open custom games with summary rule indicators.
|
||
- Show full ruleset details on hover/focus without requiring join.
|
||
- Allow joining joinable games.
|
||
- Allow creating custom game with configurable rules.
|
||
- Transition to gameplay scene when lobby host starts match.
|
||
|
||
## Server
|
||
- Return browseable custom game lobbies and summarized rule metadata.
|
||
- Validate join permissions and slot availability.
|
||
- Validate and persist custom ruleset configuration on create/update.
|
||
- Publish lobby state changes and match start event.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`CustomLobbyListRequest`)
|
||
- `requestId`, `filters`, `sort`, `page`, `pageSize`
|
||
|
||
### Server -> Client (`CustomLobbyListResponse`)
|
||
- `requestId`, `results`, `totalCount`
|
||
|
||
### Client -> Server (`CustomLobbyRulesRequest`)
|
||
- `requestId`, `customLobbyId`
|
||
|
||
### Server -> Client (`CustomLobbyRulesResponse`)
|
||
- `requestId`, `customLobbyId`, `ruleset`
|
||
|
||
### Client -> Server (`CustomLobbyJoinRequest`)
|
||
- `requestId`, `customLobbyId`, `deckId`, `archspiritId`
|
||
|
||
### Server -> Client (`CustomLobbyJoinResponse`)
|
||
- `requestId`, `success`, `customLobbyState`, `errorCode`
|
||
|
||
### Client -> Server (`CustomLobbyCreateRequest`)
|
||
- `requestId`, `name`, `privacy`, `ruleset`, `formatId`, `deckConstraints`, `archspiritConstraints`, `maxPlayers`, `maxSpectators`
|
||
|
||
### Server -> Client (`CustomLobbyCreateResponse`)
|
||
- `requestId`, `success`, `customLobbyId`, `customLobbyState`, `errorCode`
|
||
|
||
### Server -> Client (`CustomMatchStarting`)
|
||
- `requestId`, `customLobbyId`, `matchId`, `rulesetId`, `gameServerEndpoint`, `matchToken`
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/deck-editor.scene.md
|
||
|
||
# DeckEditor Scene
|
||
|
||
## UI
|
||
- Deck list panel
|
||
- Card search/filter panel
|
||
- Deck composition panel
|
||
- Validation/errors panel
|
||
- Save/duplicate/delete actions
|
||
|
||
## Client
|
||
- Build/edit decks, local mirror validation, save/duplicate/rename/delete.
|
||
|
||
## Server
|
||
- Validate deck against current rules and persist deck revisions.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`DeckValidateRequest`)
|
||
- `requestId`, `deckDraft`, `formatId`
|
||
|
||
### Server -> Client (`DeckValidateResponse`)
|
||
- `requestId`, `isValid`, `errors`, `warnings`
|
||
|
||
### Client -> Server (`DeckSaveRequest`)
|
||
- `requestId`, `deckId`, `deckName`, `deckCards`, `formatId`
|
||
|
||
### Server -> Client (`DeckSaveResponse`)
|
||
- `requestId`, `success`, `deckId`, `deckRevision`, `isValid`, `errors`
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/leaderboard.scene.md
|
||
|
||
# Leaderboard Scene
|
||
|
||
## Status
|
||
Draft placeholder.
|
||
|
||
## Planned Scope
|
||
- Define scene UI blocks
|
||
- Define client interactions
|
||
- Define server contract and payloads
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/login.scene.md
|
||
|
||
# Login Scene
|
||
|
||
## UI
|
||
- Connection status indicator (connecting/retrying/failed)
|
||
- Retry action + diagnostics link (optional)
|
||
- Username/email field
|
||
- Password field
|
||
- Remember device toggle
|
||
- Submit + Forgot Password actions
|
||
- `Create Account` action to open `Register`
|
||
- OAuth provider buttons (Google/Steam/Apple/Microsoft as enabled)
|
||
- Session check/loading indicator
|
||
- OAuth status text + callback verification state
|
||
|
||
## Client
|
||
- Open hub/relay connection in this scene.
|
||
- Send initial hello with client build/platform metadata.
|
||
- Wait for connection acceptance and service availability.
|
||
- Perform session probe after connection is established.
|
||
- Decide path: existing session refresh, password login, or OAuth login.
|
||
- Start OAuth flow and handle OAuth callback exchange in this scene.
|
||
- Route `Forgot Password` to account recovery flow.
|
||
- Route `Create Account` to `Register`.
|
||
- On success transition to `MainMenu`.
|
||
|
||
## Server
|
||
- Validate protocol compatibility and return environment capabilities.
|
||
- Return service status.
|
||
- Validate refresh tokens and return auth policy.
|
||
- Validate credential login.
|
||
- Generate OAuth start URL/state and process OAuth exchange.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`HubHello`)
|
||
- `requestId`, `clientVersion`, `contentVersion`, `platform`, `locale`, `deviceId`, `sessionId`
|
||
|
||
### Server -> Client (`HubWelcome`)
|
||
- `requestId`, `connectionId`
|
||
- `minSupportedClientVersion`, `latestClientVersion`, `latestContentVersion`
|
||
- `serviceStatus`, `apiBaseUrl`, `cdnBaseUrl`
|
||
- `authProvidersEnabled`, `motd` (optional)
|
||
|
||
### Client -> Server (`SessionProbe`)
|
||
- `requestId`, `refreshToken` (optional), `deviceId`
|
||
|
||
### Server -> Client (`SessionProbeResult`)
|
||
- `requestId`, `isAuthenticated`, `accountId`, `displayName`
|
||
- `authMethodsAvailable`, `passwordPolicy`
|
||
|
||
### Client -> Server (`LoginRequest`)
|
||
- `requestId`, `emailOrUsername`, `password`, `deviceId`
|
||
|
||
### Server -> Client (`LoginResponse`)
|
||
- `requestId`, `success`, `accessToken`, `refreshToken`, `expiresAtUtc`, `accountSummary`, `errorCode`
|
||
|
||
### Client -> Server (`OAuthStartRequest`)
|
||
- `requestId`, `provider`, `returnUri`, `deviceId`
|
||
|
||
### Server -> Client (`OAuthStartResponse`)
|
||
- `requestId`, `authorizationUrl`, `state`, `codeVerifier` (if PKCE client-managed)
|
||
|
||
### Client -> Server (`OAuthExchangeRequest`)
|
||
- `requestId`, `provider`, `authorizationCode`, `state`, `codeVerifier`
|
||
|
||
### Server -> Client (`OAuthExchangeResponse`)
|
||
- `requestId`, `success`, `accessToken`, `refreshToken`, `expiresAtUtc`, `accountSummary`, `errorCode`
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/main-menu.scene.md
|
||
|
||
# MainMenu Scene (Primary Interactive Hub)
|
||
|
||
## UI
|
||
- Navigation nodes/buttons to:
|
||
- `Bazaar`, `Leaderboard`, `Settings`, `AccountManagement`, `CollectionHub`, `RankedPlay`, `CustomPlay`
|
||
- Profile summary widget
|
||
- Notifications widget with popup modal support for updates, news, and account alerts
|
||
- Settings/logout actions
|
||
- Chat panel:
|
||
- channel tabs: `System`, `General`, `Friends`
|
||
- friend moderation/actions: `Add Friend`, `Remove Friend`, `Block`
|
||
- lobby-aware sections that appear while inside ranked or custom lobbies
|
||
- Interactive background:
|
||
- dark aura visual treatment
|
||
- rotatable 3D grid layer
|
||
- grid topology can shift between square and hex
|
||
|
||
## Input
|
||
- mouse + touch (multi-touch required)
|
||
- standard camera gestures for movement
|
||
- node selection via left click and middle mouse click
|
||
|
||
## Client
|
||
- Display entry points, key account notifications, and social/chat state.
|
||
- Apply feature flags and queue/lobby presence to determine which nav nodes and chat subsections are visible.
|
||
|
||
## Server
|
||
- Return role/entitlement menu permissions, badge counts, feature flags, chat channel permissions, and presence state.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`MainMenuBootstrapRequest`)
|
||
- `requestId`, `accountId`, `clientVersion`
|
||
|
||
### Server -> Client (`MainMenuBootstrapResponse`)
|
||
- `requestId`, `profileSummary`, `roles`, `featureFlags`, `menuPermissions`, `notificationCounts`, `rankedSummary`, `chatChannels`, `friendSummary`, `presenceState`
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes.md
|
||
|
||
# Scenes Index
|
||
|
||
This file is the canonical client flow map. Scene details live in `context-files/scenes/*.scene.md`.
|
||
|
||
## Core Lifecycle Flow
|
||
1. `ClientLaunch` -> `scenes/client-launch.scene.md`
|
||
2. `Login` -> `scenes/login.scene.md`
|
||
3. `Register` (from Login) -> `scenes/register.scene.md`
|
||
4. `MainMenu` (post-auth hub) -> `scenes/main-menu.scene.md`
|
||
|
||
Flow rules:
|
||
- `ClientLaunch` must complete update check before opening auth flow.
|
||
- `Login` owns initial connection/session probe and transitions to `MainMenu` only after auth success.
|
||
- `Register` returns to `Login` (or direct session bootstrap if server returns tokens).
|
||
|
||
## Main Menu Navigation Map
|
||
Primary destinations:
|
||
1. `RankedPlay` (ranked lobby + matchmaking) -> `scenes/ranked-play.scene.md`
|
||
2. `CustomPlay` (unranked/custom lobby) -> `scenes/custom-play.scene.md`
|
||
3. `Bazaar` -> `scenes/bazaar.scene.md`
|
||
4. `Leaderboard` -> `scenes/leaderboard.scene.md`
|
||
5. `CollectionHub` -> `scenes/collection-hub.scene.md`
|
||
6. `AccountManagement` -> `scenes/account-management.scene.md`
|
||
7. `Settings` -> `scenes/settings.scene.md`
|
||
|
||
Collection subtree:
|
||
1. `DeckEditor` -> `scenes/deck-editor.scene.md`
|
||
2. `CardViewer` -> `scenes/card-viewer.scene.md`
|
||
3. `Cosmetics` -> `scenes/cosmetics.scene.md`
|
||
|
||
## Cross-Scene UI Requirements
|
||
- Persistent quick actions: `Settings` and `Report Bug` in all scenes.
|
||
- Main social/chat panel channels: `System`, `General`, `Friends`.
|
||
- Friend actions available where identity is visible: `Add Friend`, `Remove Friend`, `Block`.
|
||
- Ranked/unranked lobby-specific chat sections appear only while inside those lobbies.
|
||
|
||
## Global Rules
|
||
- Shared/global client rules are in `global.md`.
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/ranked-play.scene.md
|
||
|
||
# RankedPlay Scene
|
||
|
||
## UI
|
||
- Ranked lobby header (season, rank, queue health)
|
||
- Loadout panel:
|
||
- selected deck
|
||
- selected archspirit
|
||
- deck legality status for ranked ruleset
|
||
- Queue actions:
|
||
- `Join Queue`
|
||
- `Leave Queue`
|
||
- Matchmaking status panel:
|
||
- elapsed queue time
|
||
- estimated wait range
|
||
- cancellation state
|
||
- Lobby chat subsection:
|
||
- ranked-only channel visibility while in this scene
|
||
|
||
## Client
|
||
- Load ranked eligibility and current competitive profile.
|
||
- Prompt for deck selection + starting ArchSpirit before queueing.
|
||
- Require valid deck + archspirit selection before enabling `Join Queue`.
|
||
- Submit ranked queue request and transition to matchmaking state.
|
||
- On match found, lock queue interactions and transition to gameplay scene with ranked ruleset payload.
|
||
|
||
## Server
|
||
- Return ranked season/profile data and queue eligibility.
|
||
- Validate selected deck against ranked format/rules.
|
||
- Enqueue/dequeue player for ranked matchmaking.
|
||
- Emit match-found payload with authoritative match seed and ruleset.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`RankedLobbyBootstrapRequest`)
|
||
- `requestId`, `accountId`, `clientVersion`
|
||
|
||
### Server -> Client (`RankedLobbyBootstrapResponse`)
|
||
- `requestId`, `seasonSummary`, `rankedProfile`, `queueEligibility`, `formatId`, `rulesVersion`
|
||
|
||
### Client -> Server (`RankedQueueJoinRequest`)
|
||
- `requestId`, `deckId`, `archspiritId`, `formatId`
|
||
|
||
### Server -> Client (`RankedQueueJoinResponse`)
|
||
- `requestId`, `success`, `queueTicketId`, `estimatedWaitSeconds`, `errorCode`
|
||
|
||
### Client -> Server (`RankedQueueLeaveRequest`)
|
||
- `requestId`, `queueTicketId`
|
||
|
||
### Server -> Client (`RankedQueueLeaveResponse`)
|
||
- `requestId`, `success`, `errorCode`
|
||
|
||
### Server -> Client (`RankedMatchFound`)
|
||
- `requestId`, `queueTicketId`, `matchId`, `rulesetId`, `opponentSummary`, `acceptDeadlineUtc`, `gameServerEndpoint`, `matchToken`
|
||
|
||
## Matchmaking Handling (Design Draft)
|
||
|
||
### Baseline Recommendation
|
||
- Use skill rating (MMR) + rank tier as primary matching factors.
|
||
- Use expanding search windows over time:
|
||
- strict match window at queue start
|
||
- gradually widen MMR/rank constraints each interval
|
||
- Prioritize latency region compatibility.
|
||
- Enforce anti-rematch cooldown (avoid immediate repeated same-opponent pairings when possible).
|
||
|
||
### Queue Lifecycle
|
||
1. Player joins queue with `deckId` + `archspiritId` locked.
|
||
2. Server issues `queueTicketId` and tracks search window state.
|
||
3. On candidate match, server validates both players still eligible/connected.
|
||
4. Server emits `RankedMatchFound` with accept deadline.
|
||
5. If accepted (or auto-accept policy), allocate match server and transition to gameplay.
|
||
6. If declined/timeout/disconnect, apply policy (requeue/penalty) and notify client.
|
||
|
||
## Matchmaking v1 Integration Spec
|
||
|
||
### v1 Decisions (Locked)
|
||
1. **Accept flow:** auto-accept (no ready-check popup) for fastest queue-to-match path.
|
||
2. **Queue type:** solo queue only in v1.
|
||
3. **Deck/ArchSpirit lock:** locked at queue join; changing either requires leaving queue.
|
||
4. **Placement:** first 10 ranked matches per season are placement-calibrated.
|
||
|
||
### v1 Search Window Expansion
|
||
- `0s-30s`: ±75 MMR, same rank tier bucket, same region preferred.
|
||
- `31s-60s`: ±125 MMR, adjacent rank tier allowed, same region strongly preferred.
|
||
- `61s-120s`: ±200 MMR, broader rank band, nearby low-latency regions allowed.
|
||
- `121s+`: ±300 MMR, widest v1 bounds, any allowed region under latency cap.
|
||
|
||
### Region/Latency Policy
|
||
- Preferred region from player profile/ping map.
|
||
- Hard reject match candidates where predicted latency exceeds v1 cap (e.g. 140ms).
|
||
- If no candidate under cap after 180s, notify client with option to keep waiting or cancel.
|
||
|
||
### Anti-Rematch / Pairing Controls
|
||
- Avoid same-opponent rematch within last 2 completed ranked games when alternatives exist.
|
||
- Soft rule only (can be bypassed at high queue times to avoid deadlocks).
|
||
|
||
### Dodge / Disconnect Policy (v1)
|
||
- Since v1 is auto-accept, “dodge” is treated as disconnect/failure to load match.
|
||
- First offense in rolling 24h: warning + immediate requeue allowed.
|
||
- Repeated offenses: escalating queue lockouts (e.g. 2m, 5m, 15m).
|
||
- Server records offense events for moderation review.
|
||
|
||
### v1 Client Integration States
|
||
- `Idle`
|
||
- `ValidatingLoadout`
|
||
- `QueueJoining`
|
||
- `InQueue`
|
||
- `MatchAllocated`
|
||
- `TransitionToGameplay`
|
||
- `QueueError`
|
||
|
||
### v1 Server Event Contract Additions
|
||
|
||
#### Server -> Client (`RankedQueueStatus`)
|
||
- `requestId`
|
||
- `queueTicketId`
|
||
- `elapsedSeconds`
|
||
- `searchWindowTier` (`T1`/`T2`/`T3`/`T4`)
|
||
- `estimatedWaitSeconds`
|
||
- `status` (`searching` | `allocating` | `requeue_required`)
|
||
|
||
#### Server -> Client (`RankedQueuePenalty`)
|
||
- `requestId`
|
||
- `penaltyType` (`warning` | `lockout`)
|
||
- `lockoutSeconds` (optional)
|
||
- `reasonCode`
|
||
|
||
### Telemetry / Audit Hooks (v1)
|
||
- Queue enter/leave events with `queueTicketId`, `deckId`, `archspiritId`.
|
||
- Match candidate evaluations (anonymized opponent id, accept/reject reason).
|
||
- Final match allocation event with `matchId`, region, latency estimate.
|
||
- Disconnect/penalty events with escalation tier.
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/register.scene.md
|
||
|
||
# Register Scene
|
||
|
||
## UI
|
||
- Username input
|
||
- Email input
|
||
- Password input
|
||
- Confirm password input
|
||
- Terms/privacy acceptance controls
|
||
- Submit/Cancel actions + validation messages
|
||
|
||
## Client
|
||
- Submit account fields and required agreements.
|
||
- Validate password/confirm password match before submit.
|
||
- On success:
|
||
- if auth tokens are returned, transition to `MainMenu`
|
||
- otherwise return to `Login` with success message
|
||
|
||
## Server
|
||
- Create account, validate username/email uniqueness, persist agreements.
|
||
|
||
## Data Exchange
|
||
### Client -> Server (`RegisterRequest`)
|
||
- `requestId`, `email`, `username`, `password`, `confirmPassword`, `countryCode`, `dob`, `acceptedPolicies`
|
||
|
||
### Server -> Client (`RegisterResponse`)
|
||
- `requestId`, `success`, `accessToken` (optional), `refreshToken` (optional), `accountSummary` (optional), `requiresEmailVerification`, `errorCode`
|
||
|
||
---
|
||
|
||
## File: Client/context-files/scenes/settings.scene.md
|
||
|
||
# Settings Scene
|
||
|
||
## Status
|
||
Active draft.
|
||
|
||
## UI Blocks
|
||
- Support panel:
|
||
- `Contact Support` action
|
||
- Audio panel:
|
||
- master volume
|
||
- background music volume
|
||
- sound effects volume
|
||
- mute toggles (optional)
|
||
- Display panel:
|
||
- brightness control
|
||
- Additional settings panel (extensible):
|
||
- placeholder for future options (controls, accessibility, language, notifications, etc.)
|
||
|
||
## Client Interactions
|
||
- Load current user settings on scene open.
|
||
- Apply slider/toggle changes immediately in preview when safe.
|
||
- Persist confirmed changes to server.
|
||
- Offer reset-to-default for configurable categories.
|
||
- Open support flow when `Contact Support` is selected.
|
||
|
||
## Server Contract (Draft)
|
||
|
||
### Client -> Server (`SettingsGetRequest`)
|
||
- `requestId`
|
||
- `accountId`
|
||
|
||
### Server -> Client (`SettingsGetResponse`)
|
||
- `requestId`
|
||
- `audio`:
|
||
- `masterVolume`
|
||
- `musicVolume`
|
||
- `sfxVolume`
|
||
- `masterMute` (optional)
|
||
- `musicMute` (optional)
|
||
- `sfxMute` (optional)
|
||
- `display`:
|
||
- `brightness`
|
||
- `support`:
|
||
- `contactMethods`
|
||
- `helpUrl` (optional)
|
||
- `otherSettings` (extensible object)
|
||
|
||
### Client -> Server (`SettingsUpdateRequest`)
|
||
- `requestId`
|
||
- `audio` (optional)
|
||
- `display` (optional)
|
||
- `otherSettings` (optional)
|
||
|
||
### Server -> Client (`SettingsUpdateResponse`)
|
||
- `requestId`
|
||
- `success`
|
||
- `effectiveSettings`
|
||
- `errorCode` (if failed)
|
||
|
||
### Client -> Server (`SupportContactRequest`)
|
||
- `requestId`
|
||
- `category` (optional)
|
||
- `message` (optional)
|
||
|
||
### Server -> Client (`SupportContactResponse`)
|
||
- `requestId`
|
||
- `success`
|
||
- `ticketId` (optional)
|
||
- `redirectUrl` (optional)
|
||
- `errorCode` (if failed)
|
||
|
||
## Notes
|
||
- Keep Settings and Report Bug entry points globally available in all scenes.
|
||
- Keep this scene modular so additional settings can be added without redesign.
|
||
|
||
---
|
||
|
||
## File: client-map.md
|
||
|
||
# Client Handler → Scene Map (Draft)
|
||
|
||
This maps current server handlers (`Server/src/*/Handlers`) to suggested client scenes/features.
|
||
|
||
## Auth / Session Scene
|
||
|
||
> Source: `SOR.Auth/Handlers/AuthGrpcHandler.cs` (gRPC, not websocket message handlers)
|
||
|
||
- `AuthGrpcHandler.Login` → **Login scene**
|
||
- `AuthGrpcHandler.Register` → **Register scene**
|
||
- `AuthGrpcHandler.ValidateToken` → **App boot/session restore**
|
||
- `AuthGrpcHandler.Logout` → **Settings / account menu logout**
|
||
- `Get/Set/Delete/ListAccountProperty` → **Profile/settings persistence**
|
||
- `LoginWithOAuth` → **OAuth login scene** (feature-flagged)
|
||
|
||
## Version Gate / Bootstrap Scene
|
||
|
||
- `version.check` → **Startup version gate / patch-required modal**
|
||
|
||
## Content / Catalog Scene
|
||
|
||
- `content.sync` → **Initial catalog sync + background refresh**
|
||
- `content.sets` → **Card sets browser/filter data**
|
||
- `content.card` → **Card detail view / tooltip inspector**
|
||
|
||
## Collection Scene (Deck Builder)
|
||
|
||
- `collection.get_cards` → **Collection inventory grid**
|
||
- `collection.get_decks` → **Deck list scene**
|
||
- `collection.get_deck` → **Deck detail/editor scene**
|
||
- `collection.create_deck` → **Create deck flow**
|
||
- `collection.clone_deck` → **Duplicate deck action**
|
||
- `collection.rename_deck` → **Rename deck action**
|
||
- `collection.delete_deck` → **Delete deck action**
|
||
- `collection.add_card` → **Deck editor add card**
|
||
- `collection.remove_card` → **Deck editor remove card**
|
||
- `collection.get_starter_decks` → **Starter deck selection scene**
|
||
- `collection.select_starter_deck` → **Onboarding starter deck confirm**
|
||
|
||
## Bazaar / Store Scene
|
||
|
||
- `bazaar.get_store` → **Store home**
|
||
- `bazaar.buy_booster_pack` → **Booster pack purchase flow**
|
||
- `bazaar.buy_prebuilt_deck` → **Prebuilt deck purchase flow**
|
||
- `bazaar.buy_cosmetic` → **Cosmetics purchase flow**
|
||
- `bazaar.get_listings` → **Marketplace listings**
|
||
- `bazaar.get_my_listings` → **My listings management**
|
||
- `bazaar.get_my_balance` → **Wallet/balance view**
|
||
- `bazaar.list_card` → **Create listing flow**
|
||
- `bazaar.cancel_listing` → **Cancel listing action**
|
||
- `bazaar.place_bid` → **Bid flow**
|
||
- `bazaar.buy_listing` → **Instant buy flow**
|
||
- `bazaar.get_transactions` → **Transaction history scene**
|
||
|
||
## Social / Chat Scene
|
||
|
||
### Presence + social graph
|
||
- `chat.get_social` → **Friends/social list pane**
|
||
- `chat.friend_request` → **Add friend action**
|
||
- `chat.friend_respond` → **Accept/decline friend request**
|
||
- `chat.friend_remove` → **Remove friend action**
|
||
- `chat.block` / `chat.unblock` → **Blocklist management**
|
||
- `chat.presence.get` / `chat.presence.set` → **Presence status controls**
|
||
|
||
### Messaging + notifications
|
||
- `chat.get_channels` → **Channel/DM sidebar**
|
||
- `chat.dm_open` → **Open/start DM thread**
|
||
- `chat.get_messages` → **Thread message history scene**
|
||
- `chat.send` → **Send message action**
|
||
- `chat.notifications.get` → **Notifications center**
|
||
- `chat.notifications.read` → **Mark notifications read**
|
||
|
||
## Matchmaking Scene
|
||
|
||
- `matchmaking.join` → **Queue/join matchmaking**
|
||
- `matchmaking.leave` → **Leave queue**
|
||
- `matchmaking.status` → **Queue status panel**
|
||
|
||
## Custom Lobby Scene
|
||
|
||
- `game.custom.create` → **Create private/custom lobby**
|
||
- `game.custom.list` → **Lobby browser**
|
||
- `game.custom.join` → **Join selected custom lobby**
|
||
- `game.custom.leave` → **Leave custom lobby**
|
||
- `game.ready` → **Ready-up toggle in lobby**
|
||
|
||
## In-Match Scene (Battlefield)
|
||
|
||
### Session/state
|
||
- `game.get_state` → **Load/rejoin current match state**
|
||
- `game.transition` → **Phase transition orchestration**
|
||
- `game.end_turn` → **End-turn action**
|
||
- `game.concede` → **Concede action**
|
||
|
||
### Setup + economy
|
||
- `game.place_arch_spirit` → **Placement phase scene**
|
||
- `game.draw` → **Draw action**
|
||
- `game.sacrifice` → **Sacrifice flow / ST economy**
|
||
|
||
### Core tactics
|
||
- `game.move_unit` → **Unit movement interaction**
|
||
- `game.attack` → **Attack targeting/confirm flow**
|
||
- `game.ascend` → **Ascend action**
|
||
|
||
### Cards + abilities
|
||
- `game.play_card` → **Card channeling flow (spirit/terramorpha/repentance/instinct/ruin)**
|
||
- `game.activate_ability` → **Activated ability targeting + resolve**
|
||
|
||
---
|
||
|
||
## Notes
|
||
|
||
- `AuthGrpcHandler` is gRPC-based and should be mapped via your auth transport client, not the websocket message dispatcher.
|
||
- Scene names are suggestions; keep handler names as the source of truth for wiring.
|
||
- For generated client routing, prefix groups map cleanly by namespace (`auth`, `content`, `collection`, `bazaar`, `chat`, `matchmaking`, `game`, `version`).
|
||
|
||
---
|
||
|
||
## File: custom-game-system-plan.md
|
||
|
||
# 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<LobbyPreset> 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<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:**
|
||
- `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<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.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<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`)
|
||
```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.
|
||
|
||
---
|
||
|
||
## File: Delta-updates.md
|
||
|
||
# Delta-updates
|
||
|
||
## Context
|
||
|
||
Current `game.state_delta` is structurally 2-player (viewer + one opponent). In 3+ player sessions this causes partial updates (e.g., tile updates arrive, but a third player's ArchSpirit/unit visual lags until another action).
|
||
|
||
Because we're still in dev with no active production players, this plan is a **direct cutover** of the existing delta system (no v1/v2 dual-run, no compatibility scaffolding).
|
||
|
||
---
|
||
|
||
## Current system constraints (what must change)
|
||
|
||
### Contract constraints (`GameMessages.cs`)
|
||
Current `GameStateDelta` includes single-opponent fields:
|
||
- `OpponentHandCount`, `OpponentDeckCount`
|
||
- `OwnArchSpiritDelta`, `OpponentArchSpiritDelta`
|
||
- `OwnStatsDelta`, `OpponentStatsDelta`
|
||
|
||
These fields cannot represent N-player state.
|
||
|
||
### Differ constraints (`GameStateDiffer.cs`)
|
||
`ComputeDelta(prev, next, viewerAccountId)` chooses one opponent via `FirstOrDefault(...)`, so only one non-viewer player can be represented in several categories.
|
||
|
||
### Push constraints (`GameHandlerBase.cs`)
|
||
P1/P2 receive deltas while seats 3+ receive full state, causing mixed consistency and harder debugging.
|
||
|
||
### Client constraints (`Client/autoloads/Game.gd`)
|
||
Delta apply path assumes only local + one opponent (`get_opponent()` / own vs opponent fields).
|
||
|
||
---
|
||
|
||
## Full cutover target (replace current delta contract)
|
||
|
||
Replace the **existing** `GameStateDelta` payload shape with an account-scoped, multi-entity schema.
|
||
|
||
## New `GameStateDelta` shape (post-cutover)
|
||
|
||
- `StateVersion: int`
|
||
- `ChangedTiles: TileDelta[]?`
|
||
- `UnitsAdded: UnitSnapshot[]?` (must include `ownerAccountId`)
|
||
- `UnitsRemoved: string[]?` (instance IDs)
|
||
- `UnitsChanged: UnitDelta[]?` (instance ID keyed)
|
||
- `ArchSpiritByAccount: Dictionary<string, UnitDeltaOrSnapshot>?`
|
||
- `PlayerStatsByAccount: Dictionary<string, PlayerStatsDelta>?`
|
||
- `PublicCountsByAccount: Dictionary<string, PublicCountsDelta>?`
|
||
- `handCount`, `deckCount`, `discardCount` (optional as needed)
|
||
- `PrivateByViewer: PrivateViewerDelta?`
|
||
- `HandAdded`, `HandRemovedIds`, `DiscardAdded`
|
||
- `MetaDelta: GameMetaDelta?`
|
||
|
||
### Design rules
|
||
- No `own/opponent` naming anywhere in wire payload.
|
||
- All public/player state keyed by `accountId`.
|
||
- Private info strictly isolated under `PrivateByViewer`.
|
||
- Delta remains sparse (null = no change).
|
||
|
||
---
|
||
|
||
## Component-by-component change list
|
||
|
||
## 1) `Server/src/SOR.Game/GameMessages.cs`
|
||
|
||
### Required edits
|
||
1. Replace current `GameStateDelta` record fields with new account-scoped fields.
|
||
2. Add/rename DTOs:
|
||
- `UnitSnapshot` (for new units with owner context)
|
||
- `PublicCountsDelta`
|
||
- `PrivateViewerDelta`
|
||
3. Keep `TileDelta`, `UnitDelta`, `PlayerStatsDelta`, `GameMetaDelta` where reusable.
|
||
|
||
### Acceptance check
|
||
- JSON payload for `game.state_delta` can represent updates for any number of players in one push.
|
||
|
||
---
|
||
|
||
## 2) `Server/src/SOR.Game/GameStateDiffer.cs`
|
||
|
||
### Required edits
|
||
1. Rewrite `ComputeDelta(prev, next, viewerAccountId)` to:
|
||
- Diff all players by `accountId`.
|
||
- Build per-account maps for archspirit/stats/public counts.
|
||
- Build `PrivateByViewer` only from viewer's own hidden zones.
|
||
2. Replace single-opponent logic (`FirstOrDefault`) entirely.
|
||
3. Ensure `UnitsAdded` carries ownership deterministically.
|
||
4. Update spectator computation to use same core diff machinery with no private section.
|
||
|
||
### Acceptance check
|
||
- In 3+ player test fixtures, a single delta includes all changed players' arch/unit/stat transitions.
|
||
|
||
---
|
||
|
||
## 3) `Server/src/SOR.Game/Handlers/GameHandlerBase.cs`
|
||
|
||
### Required edits
|
||
1. Remove split strategy (delta for seats 1/2, full-state for seats 3+).
|
||
2. For normal action updates, send `game.state_delta` to **all session players**.
|
||
3. Build each player's delta from same prev/next snapshots but viewer-specific private section.
|
||
4. Spectators receive public-only delta (same message type, private section omitted/null).
|
||
5. Keep full `game.state_update` for bootstrap/reconnect/missed-version recovery only.
|
||
|
||
### Acceptance check
|
||
- All active participants receive delta path uniformly for same stateVersion progression.
|
||
|
||
---
|
||
|
||
## 4) `Client/origin-client/autoloads/Game.gd`
|
||
|
||
### Required edits
|
||
1. Replace `_apply_delta()` implementation to consume the new `GameStateDelta` shape.
|
||
2. Remove assumptions based on `get_opponent()` for delta application.
|
||
3. Apply updates by account map:
|
||
- locate player in `state.players` by `accountId`
|
||
- apply arch stats/unit updates per-account
|
||
- apply viewer private hand/discard updates only from `PrivateByViewer`
|
||
4. Keep state-version guards and full-sync fallback on gap/malformed payload.
|
||
5. Update helper methods as needed (e.g., utility to get player dict by account id quickly).
|
||
|
||
### Acceptance check
|
||
- Any opponent (not just “first opponent”) placing ArchSpirit appears immediately on all clients after one delta.
|
||
|
||
---
|
||
|
||
## 5) `Client/origin-client/scenes/game/game_screen.gd`
|
||
|
||
### Required edits
|
||
1. Audit for any implicit “single opponent” rendering assumptions tied to delta-fed data.
|
||
2. Ensure ownership/highlight lists are rebuilt from full `state.players` each update (already mostly true).
|
||
3. Verify no UI panel relies on old opponent-only count fields.
|
||
|
||
### Acceptance check
|
||
- 3+ player HUD and board visuals remain consistent after each delta without waiting for secondary actions.
|
||
|
||
---
|
||
|
||
## 6) Tests and fixtures
|
||
|
||
### Server tests
|
||
- Add golden prev/next snapshots for:
|
||
1. 2-player baseline action
|
||
2. 3-player arch placements in sequence
|
||
3. 4-player mixed action turn
|
||
4. spectator-visible transitions
|
||
- Assert delta JSON contains correct account-scoped maps and no hidden-info leaks.
|
||
|
||
### Client tests (or scripted replay harness)
|
||
- Feed ordered deltas and verify convergence.
|
||
- Feed version gaps/out-of-order and verify fallback `request_sync()` behavior.
|
||
|
||
### Acceptance check
|
||
- No repro of delayed ArchSpirit/unit appearance in 3+ session replay.
|
||
|
||
---
|
||
|
||
## Implementation order (cutover)
|
||
|
||
1. Update DTO contract (`GameMessages.cs`).
|
||
2. Update differ generation (`GameStateDiffer.cs`).
|
||
3. Update push fanout (`GameHandlerBase.cs`).
|
||
4. Update client delta apply (`Game.gd`).
|
||
5. Run fixture + replay validation.
|
||
6. Remove obsolete code paths/fields referencing own-vs-opponent deltas.
|
||
|
||
---
|
||
|
||
## Done criteria
|
||
|
||
- `game.state_delta` natively supports N-player + spectators.
|
||
- No own/opponent delta fields remain.
|
||
- No mixed per-seat push strategy in active sessions.
|
||
- 3+ player ArchSpirit/unit updates are immediate and deterministic on all clients.
|
||
|
||
---
|
||
|
||
## File: deploy/database-migrations.md
|
||
|
||
# SOR Database Migrations
|
||
|
||
SOR uses **EF Core 8** with **6 independent DbContexts**, each owning a separate PostgreSQL
|
||
schema. All migrations live in `Server/src/SOR.Database/Migrations/<Schema>/`.
|
||
|
||
---
|
||
|
||
## Prerequisites
|
||
|
||
```bash
|
||
# Install the dotnet-ef global tool (once per machine)
|
||
dotnet tool install --global dotnet-ef
|
||
|
||
# Verify
|
||
dotnet ef --version # must be >= 8.x
|
||
```
|
||
|
||
---
|
||
|
||
## Contexts and Schemas
|
||
|
||
| Context | Schema | Migration folder |
|
||
|------------------------|--------------|-------------------------------------|
|
||
| `SorIdentityDbContext` | `identity` | `Migrations/Identity/` |
|
||
| `CatalogDbContext` | `catalog` | `Migrations/Catalog/` |
|
||
| `CollectionDbContext` | `collection` | `Migrations/Collection/` |
|
||
| `BazaarDbContext` | `bazaar` | `Migrations/Bazaar/` |
|
||
| `ChatDbContext` | `chat` | `Migrations/Chat/` |
|
||
| `GameDbContext` | `game` | `Migrations/Game/` |
|
||
|
||
All contexts share the same PostgreSQL database (`SOR`) but are completely isolated by schema.
|
||
|
||
---
|
||
|
||
## Applying Migrations to a Remote Server
|
||
|
||
Run from `Server/` directory. The `--connection` flag overrides whatever is in appsettings.json
|
||
and is the correct way to target a specific environment.
|
||
|
||
```bash
|
||
cd Server
|
||
|
||
CONN="Host=<HOST>;Port=5432;Database=SOR;Username=<USER>;Password=<PASSWORD>"
|
||
|
||
# Apply all 6 contexts (run in order — schemas are independent, no cross-schema FKs)
|
||
dotnet ef database update --project src/SOR.Database --context SorIdentityDbContext --connection "$CONN" --no-build
|
||
dotnet ef database update --project src/SOR.Database --context CatalogDbContext --connection "$CONN" --no-build
|
||
dotnet ef database update --project src/SOR.Database --context CollectionDbContext --connection "$CONN" --no-build
|
||
dotnet ef database update --project src/SOR.Database --context BazaarDbContext --connection "$CONN" --no-build
|
||
dotnet ef database update --project src/SOR.Database --context ChatDbContext --connection "$CONN" --no-build
|
||
dotnet ef database update --project src/SOR.Database --context GameDbContext --connection "$CONN" --no-build
|
||
```
|
||
|
||
> **Note:** `--no-build` skips rebuilding and uses already-compiled binaries in `bin/`.
|
||
> Omit it (or run `dotnet build` first) if you just changed migration files.
|
||
|
||
### pg-forge-01 (production)
|
||
|
||
```bash
|
||
HOST=172.10.1.127
|
||
USER=SOR-DBA
|
||
# password is stored in sor-app-secrets k8s Secret (Cdn__AccessKey isn't it — see deploy/secrets/)
|
||
```
|
||
|
||
---
|
||
|
||
## Checking Migration Status
|
||
|
||
```bash
|
||
CONN="Host=<HOST>;..."
|
||
|
||
# Lists all migrations; any marked (Pending) need to be applied
|
||
dotnet ef migrations list --project src/SOR.Database --context SorIdentityDbContext --connection "$CONN" --no-build
|
||
dotnet ef migrations list --project src/SOR.Database --context CatalogDbContext --connection "$CONN" --no-build
|
||
dotnet ef migrations list --project src/SOR.Database --context CollectionDbContext --connection "$CONN" --no-build
|
||
dotnet ef migrations list --project src/SOR.Database --context BazaarDbContext --connection "$CONN" --no-build
|
||
dotnet ef migrations list --project src/SOR.Database --context ChatDbContext --connection "$CONN" --no-build
|
||
dotnet ef migrations list --project src/SOR.Database --context GameDbContext --connection "$CONN" --no-build
|
||
```
|
||
|
||
---
|
||
|
||
## Adding a New Migration
|
||
|
||
```bash
|
||
cd Server
|
||
|
||
# 1. Make your model changes in SOR.Database/Entities/ or Contexts/
|
||
|
||
# 2. Add the migration (pick the right context)
|
||
dotnet ef migrations add <MigrationName> \
|
||
--project src/SOR.Database \
|
||
--context <ContextName> \
|
||
--output-dir Migrations/<Schema>
|
||
|
||
# Example:
|
||
dotnet ef migrations add AddCardFoilIndex \
|
||
--project src/SOR.Database \
|
||
--context CollectionDbContext \
|
||
--output-dir Migrations/Collection
|
||
|
||
# 3. Review the generated Up()/Down() in Migrations/<Schema>/<timestamp>_<Name>.cs
|
||
# Make sure it only contains the delta — NOT a full recreation of existing tables.
|
||
|
||
# 4. Apply to target DB
|
||
dotnet ef database update --project src/SOR.Database --context CollectionDbContext --connection "$CONN"
|
||
```
|
||
|
||
> **Design-time factories** (`DesignTimeFactories.cs` in `SOR.Database`) allow the EF tools
|
||
> to instantiate contexts without starting the full ASP.NET Core application.
|
||
> They read the connection string from `ConnectionStrings__Default` env var,
|
||
> falling back to `localhost` for local dev.
|
||
|
||
---
|
||
|
||
## How EF Tracks Applied Migrations
|
||
|
||
Each schema gets its own `__EFMigrationsHistory` table:
|
||
|
||
```
|
||
identity.__EFMigrationsHistory
|
||
catalog.__EFMigrationsHistory
|
||
collection.__EFMigrationsHistory
|
||
bazaar.__EFMigrationsHistory
|
||
chat.__EFMigrationsHistory
|
||
game.__EFMigrationsHistory
|
||
```
|
||
|
||
EF Core compares these tables to the migration files to determine what's pending.
|
||
|
||
---
|
||
|
||
## Known Migration History
|
||
|
||
### pg-forge-01 — last applied (2026-02-27)
|
||
|
||
| Context | Last migration applied |
|
||
|-----------------|-------------------------------------------------|
|
||
| Identity | `20260226111950_AddRankScore` |
|
||
| Catalog | `20260226012910_AddDefinitionVersionAndRetired` |
|
||
| Collection | `20260225231700_AddPlayerCosmetics` |
|
||
| Bazaar | `20260225231658_AddBazaarCosmetics` |
|
||
| Chat | `20260226012908_AddPresenceAndNotifications` |
|
||
| Game | `20260226162145_AddBoardDimensions` |
|
||
|
||
### Notes
|
||
|
||
- `GameDbContext/20260226125446_AddGameRulesAndCustomLobby` is intentionally empty.
|
||
It was regenerated with a stale snapshot that duplicated InitialCreate tables.
|
||
The actual `game_rule_sets` and `custom_lobbies` tables were added in the
|
||
following `AddBoardDimensions` migration.
|
||
|
||
---
|
||
|
||
## File: deploy/secrets/README.md
|
||
|
||
# SOR Kubernetes Secrets
|
||
|
||
These files are **NOT committed to git** (excluded via root `.gitignore`).
|
||
The `*.yaml.template` files in this directory ARE committed — copy them, fill in
|
||
real values, then apply to the cluster.
|
||
|
||
---
|
||
|
||
## Quick Setup
|
||
|
||
### 1. Harbor image pull secret
|
||
```bash
|
||
cp harbor-pull-secret.yaml.template harbor-pull-secret.yaml
|
||
# edit harbor-pull-secret.yaml — fill in your Harbor username and password
|
||
kubectl apply -f harbor-pull-secret.yaml
|
||
```
|
||
|
||
### 2. Application secrets
|
||
```bash
|
||
cp sor-app-secrets.yaml.template sor-app-secrets.yaml
|
||
# edit sor-app-secrets.yaml — fill in Postgres connection string and CDN credentials
|
||
kubectl apply -f sor-app-secrets.yaml
|
||
```
|
||
|
||
### 3. Gitea Actions repository secrets
|
||
In your Gitea repository → Settings → Secrets, add:
|
||
| Name | Value |
|
||
|-------------------|--------------------------------|
|
||
| HARBOR_USERNAME | Your Harbor robot account name |
|
||
| HARBOR_PASSWORD | Your Harbor robot account token |
|
||
|
||
---
|
||
|
||
## Secrets Reference
|
||
|
||
| Secret Name | Key | Used By | Notes |
|
||
|--------------------|----------------------------|-----------------|-------------------------------------------------|
|
||
| sor-app-secrets | ConnectionStrings__Default | host + admin | Postgres connection string |
|
||
| sor-app-secrets | Admin__Email | admin only | Seed SuperAdmin email (default: admin@sor.local) |
|
||
| sor-app-secrets | Admin__Password | admin only | Seed SuperAdmin password (12+ chars required) |
|
||
| sor-app-secrets | Cdn__PublicBaseUrl | host + admin | e.g. https://cdn.aeternalisgames.com |
|
||
| sor-app-secrets | Cdn__EndpointUrl | host + admin | Ceph RadosGW endpoint, e.g. http://172.10.1.60:7480 |
|
||
| sor-app-secrets | Cdn__AccessKey | host + admin | S3 access key ID |
|
||
| sor-app-secrets | Cdn__SecretKey | host + admin | S3 secret access key |
|
||
| sor-app-secrets | Cdn__BucketName | host + admin | S3 bucket name, e.g. sor-assets |
|
||
| redis-credentials | connection-string | host only | **Already exists** in stone-server ns |
|
||
| harbor-credentials | .dockerconfigjson | both pods | Harbor image pull secret |
|
||
|
||
---
|
||
|
||
## Notes
|
||
|
||
- `redis-credentials` is assumed to already exist in the `stone-server` namespace.
|
||
If the key name inside it is different from `connection-string`, update
|
||
`deploy/k8s/deployment-host.yaml` to match.
|
||
|
||
- The Redis connection string format expected by StackExchange.Redis:
|
||
`HOST:PORT,password=PASSWORD,ssl=true,abortConnect=false`
|
||
|
||
- The Postgres connection string format expected by Npgsql:
|
||
`Host=HOST;Port=5432;Database=SOR;Username=USER;Password=PASSWORD;`
|
||
|
||
- For production, consider enabling SSL on the Postgres connection:
|
||
`...;SSL Mode=Require;Trust Server Certificate=true`
|
||
|
||
---
|
||
|
||
## File: gameplay-effects-gap.md
|
||
|
||
# Ability Effects Implementation Gaps
|
||
|
||
Generated from `Effects.cs` (declared effect models) vs `AbilitySystem.ExecuteEffect` (implemented `case` handlers).
|
||
|
||
- Declared effects: **68**
|
||
- Implemented handlers: **66**
|
||
- Missing handlers: **2** (deferred — require additional combat type design)
|
||
|
||
## Deferred effect handlers
|
||
|
||
### 5.1 Stat modification
|
||
- `SetStatModMultiplierEffect` — requires combat multiplier design
|
||
|
||
### 5.7 Zone/card ops
|
||
- `ChannelCardEffect` — requires rules design for ability-triggered card channeling
|
||
|
||
---
|
||
|
||
## File: gameplay-todo.md
|
||
|
||
# Gameplay TODO
|
||
|
||
## Aura transition walkthrough scenario (movement)
|
||
|
||
Goal scenario: "A spirit moves on the battlefield and another spirit enters its aura range."
|
||
|
||
### Current flow in engine
|
||
1. `GameEngine.MoveUnit(...)` validates movement/path/MP.
|
||
2. Unit position is updated on board.
|
||
3. `AbilitySystem.EvaluateAuraTransitions(state, movingUnitId, from, to)` runs.
|
||
4. System checks both:
|
||
- stationary aura units vs moving unit transition
|
||
- moving unit's own aura vs stationary units
|
||
5. If range crossing occurs:
|
||
- outside -> inside => `EnterAuraRange` trigger fires
|
||
- inside -> outside => `LeaveAuraRange` trigger fires
|
||
6. Triggered abilities are evaluated via `FireTrigger(...)` and matching triggered actions execute.
|
||
|
||
### Test case outline
|
||
- Place Aura Spirit A (with AuraRange 1..1 and an `OnEnterAuraRange` trigger).
|
||
- Place Spirit B outside A's range.
|
||
- Move B one tile so Manhattan distance to A becomes 1.
|
||
- Expected:
|
||
- `EnterAuraRange` trigger emitted with `SourceId=A`, `TargetId=B`.
|
||
- Any matching triggered actions on A resolve.
|
||
|
||
### Notes
|
||
- Aura enter/leave also has dedicated helpers for summon/death transitions:
|
||
- `EvaluateAurasOnEnter(...)`
|
||
- `EvaluateAurasOnLeave(...)`
|
||
|
||
---
|
||
|
||
## File: multiplayer-plan.md
|
||
|
||
# Multiplayer Plan: 2–10 Players, FFA / Team / Multi-Team
|
||
|
||
## Overview
|
||
|
||
The existing 1v1 system handles all the hard parts: combat resolution, ability triggers, SP/ST economy, channeling, movement, LoS, aura propagation, and win detection. Multiplayer is primarily an extension of **player-slot management**, **team affiliation**, and **board geometry** — the core rules don't change.
|
||
|
||
---
|
||
|
||
## 1. Game Modes
|
||
|
||
| Mode | Description | Example |
|
||
|---|---|---|
|
||
| **FFA** (Free-for-All) | Every player is their own team. Last ArchSpirit standing wins. | 4-player FFA |
|
||
| **N vs N** | Two teams of equal size. First team to eliminate all opposing ArchSpirits wins. | 3v3, 5v5 |
|
||
| **Multi-Team** | Three or more teams of equal size. Last team standing wins. | 2v2v2, 3v3v3, 2v2v2v2 |
|
||
| **Asymmetric** *(stretch goal)* | Teams of unequal size with handicap modifiers. | 1v2, 1v3 |
|
||
|
||
### Turn Order
|
||
Round-robin across all players in seat order (seat 0 → seat 1 → … → seat N-1 → back to 0).
|
||
|
||
Within a team, each player takes their own individual turn — teammates do not share a turn. This keeps the core turn loop unchanged and preserves all existing trigger semantics (`IsOwnTurn`, `UntilEndOfTurn`, etc.).
|
||
|
||
### Win Conditions
|
||
- **FFA**: A player is eliminated when their ArchSpirit is destroyed. The last player with a living ArchSpirit wins.
|
||
- **Team modes**: A team is eliminated when every member's ArchSpirit has been destroyed. The last surviving team wins.
|
||
- Eliminated players continue to spectate but their units stay removed (no "ghost" turns — eliminated players are skipped in turn order).
|
||
|
||
---
|
||
|
||
## 2. Server Architecture
|
||
|
||
### 2a. `GameConfiguration` — new lobby-time record
|
||
|
||
```csharp
|
||
public sealed record GameConfiguration
|
||
{
|
||
public required string Mode { get; init; } // "FFA" | "Teams" | "MultiTeam"
|
||
public required int PlayerCount { get; init; } // 2–10
|
||
public required int TeamCount { get; init; } // 1 = FFA, 2 = N vs N, N = multi-team
|
||
public required string BoardShape { get; init; } // "Rectangle" | "Cross" | "Hexagonal" | "Decagonal" | ...
|
||
// Board size hint — meaning varies per shape (e.g. radius for radial shapes, rows×cols for rectangle)
|
||
public int BoardParam1 { get; init; } = 8;
|
||
public int BoardParam2 { get; init; } = 8;
|
||
}
|
||
```
|
||
|
||
### 2b. `PlayerSlot` — replaces hardcoded player1/player2
|
||
|
||
Current `GameState` has `Player1` and `Player2` properties. Replace with:
|
||
|
||
```csharp
|
||
public IReadOnlyList<PlayerSlot> Players { get; init; }
|
||
|
||
public sealed class PlayerSlot
|
||
{
|
||
public required string AccountId { get; init; }
|
||
public required int SeatIndex { get; init; } // 0-based turn order
|
||
public required int TeamIndex { get; init; } // same value = same team; FFA = SeatIndex
|
||
public required string TeamColor { get; init; } // hex color for UI ("FF4444", etc.)
|
||
public bool Eliminated { get; set; }
|
||
// Existing per-player state
|
||
public int SP { get; set; }
|
||
public int ST { get; set; }
|
||
public List<CardInstance> Hand { get; init; } = new();
|
||
public List<CardInstance> Deck { get; init; } = new();
|
||
public List<CardInstance> Discard { get; init; } = new();
|
||
}
|
||
```
|
||
|
||
`CurrentTurnSeatIndex` replaces the current binary turn flag. The engine cycles:
|
||
```
|
||
CurrentTurnSeatIndex = (CurrentTurnSeatIndex + 1) % ActivePlayerCount
|
||
// skip eliminated players
|
||
```
|
||
|
||
### 2c. Team helper methods on `GameState`
|
||
|
||
```csharp
|
||
public bool AreAllies(string actorId, string targetId) =>
|
||
Players.First(p => p.AccountId == actorId).TeamIndex
|
||
== Players.First(p => p.AccountId == targetId).TeamIndex;
|
||
|
||
public IEnumerable<PlayerSlot> GetTeam(int teamIndex) =>
|
||
Players.Where(p => p.TeamIndex == teamIndex);
|
||
|
||
public bool IsTeamEliminated(int teamIndex) =>
|
||
GetTeam(teamIndex).All(p => p.Eliminated);
|
||
```
|
||
|
||
### 2d. Win detection change
|
||
|
||
Replace the current "player1 ArchSpirit destroyed → player2 wins" check with:
|
||
|
||
```csharp
|
||
private void CheckVictory(GameState state)
|
||
{
|
||
var survivingTeams = state.Players
|
||
.Where(p => !p.Eliminated)
|
||
.Select(p => p.TeamIndex)
|
||
.Distinct()
|
||
.ToList();
|
||
|
||
if (survivingTeams.Count == 1)
|
||
{
|
||
var winners = state.GetTeam(survivingTeams[0]).Select(p => p.AccountId).ToList();
|
||
EndGame(state, winners);
|
||
}
|
||
}
|
||
```
|
||
|
||
### 2e. Ability system — team-awareness
|
||
|
||
The ability `Ownership` values already cover the needed semantics:
|
||
- `Owner` / `Ally` = same team (update `Own()` to compare `TeamIndex` instead of `AccountId`)
|
||
- `Enemy` = any unit on a different team
|
||
- `Any`, `ExactSelf`, `Random` = unchanged
|
||
|
||
No new ownership values needed for team play.
|
||
|
||
---
|
||
|
||
## 3. Board Geometry System
|
||
|
||
### 3a. Design principle
|
||
|
||
The board is currently a rectangle described by `(rows, cols)`. Extend to a **tile mask** model: a board is a set of `Coord` positions that are valid, plus per-player **starting zones** (a sub-set of tiles designated as the home area for each player slot).
|
||
|
||
```csharp
|
||
public sealed class BoardLayout
|
||
{
|
||
public required string ShapeName { get; init; }
|
||
public required HashSet<Coord> ValidTiles { get; init; }
|
||
public required List<HashSet<Coord>> StartingZones { get; init; } // index = SeatIndex
|
||
}
|
||
```
|
||
|
||
The existing `Grid` class only needs to know which `Coord` values are navigable — it already operates on individual tile lookups, so making the tile mask sparse is a small change.
|
||
|
||
### 3b. Shape library — one generator per shape
|
||
|
||
Each generator takes `(playerCount, sizeHint)` and returns a `BoardLayout`.
|
||
|
||
#### Rectangle (current — 2 players)
|
||
```
|
||
rows = sizeHint, cols = sizeHint
|
||
Starting zones: top 2 rows for P0, bottom 2 rows for P1
|
||
```
|
||
|
||
#### Cross / Plus (4 players)
|
||
```
|
||
Three overlapping rectangles forming a plus sign.
|
||
Starting zones: each arm tip.
|
||
```
|
||
```
|
||
[P1]
|
||
[P3][ ][P2]
|
||
[P0]
|
||
```
|
||
|
||
#### Triangular (3 players)
|
||
```
|
||
Equilateral hexagonal triangle, 3 corners.
|
||
Starting zones: corner clusters.
|
||
```
|
||
|
||
#### Hexagonal Ring (6 players)
|
||
```
|
||
Hexagon of hexagonal tiles; 6 equidistant perimeter clusters as starting zones.
|
||
```
|
||
|
||
#### Decagonal (10 players)
|
||
```
|
||
Large circular arrangement, ~10 radial segments.
|
||
Starting zones: one segment per player, evenly distributed around perimeter.
|
||
```
|
||
|
||
#### Radial Star (5, 8 players)
|
||
```
|
||
Spokes radiating from a shared central arena.
|
||
Each player controls one spoke; central tiles are neutral/contested.
|
||
```
|
||
|
||
### 3c. Automatic shape selection by player count
|
||
|
||
| Player count | Recommended shapes |
|
||
|---|---|
|
||
| 2 | Rectangle (8×12), Rectangle (10×10) |
|
||
| 3 | Triangular, T-shape |
|
||
| 4 | Cross, Rectangle (12×12 with 4 quadrant starting zones) |
|
||
| 5 | Radial Star |
|
||
| 6 | Hexagonal Ring, 6-arm Star |
|
||
| 7–8 | Radial Star (8-spoke) |
|
||
| 9–10 | Decagonal Ring |
|
||
|
||
The host can override this selection in the lobby.
|
||
|
||
### 3d. Starting-zone enforcement
|
||
|
||
When a player channels a Spirit onto the battlefield, valid placement tiles are restricted to that player's starting zone (same as current 1v1 behavior, but the zone is derived from `BoardLayout.StartingZones[SeatIndex]` instead of a hardcoded row range).
|
||
|
||
---
|
||
|
||
## 4. Lobby & Matchmaking Changes
|
||
|
||
### 4a. Room creation
|
||
|
||
Extend `CreateRoomRequest` / `RoomDto`:
|
||
```csharp
|
||
public record CreateRoomRequest(
|
||
string Mode, // "FFA" | "Teams" | "MultiTeam"
|
||
int PlayerCount, // 2–10
|
||
int TeamCount, // 1 for FFA, 2+ for team modes
|
||
string BoardShape // "" = auto-select by player count
|
||
);
|
||
```
|
||
|
||
### 4b. Team assignment in lobby
|
||
|
||
For team modes, the room UI shows players grouped by team color. The room host can drag players between teams before starting. For FFA, no team UI is shown.
|
||
|
||
### 4c. Deck selection
|
||
|
||
Each player selects their own deck (same as now). No shared/team decks in v1.
|
||
|
||
---
|
||
|
||
## 5. Client Changes
|
||
|
||
### 5a. Player info panel
|
||
|
||
Currently two side panels (my stats / opponent stats). Replace with a **player ring** that dynamically generates one entry per player, grouped by team color.
|
||
|
||
```
|
||
[P0 - Blue | SP:3 ST:2 | HP:■■■□] [P1 - Blue | SP:2 ST:1 | HP:■■□□]
|
||
vs
|
||
[P2 - Red | SP:4 ST:3 | HP:■■■■] [P3 - Red | SP:1 ST:2 | HP:■■■□]
|
||
```
|
||
|
||
For FFA, each player's color is unique. For team modes, team members share a color.
|
||
|
||
### 5b. Turn indicator
|
||
|
||
The current "your turn / opponent's turn" banner extends to show the active seat's player name and team color.
|
||
|
||
### 5c. Camera / map view
|
||
|
||
- The camera must center and zoom to fit whatever board shape is in use
|
||
- For non-rectangular boards, the tile placer should mask the valid tile set
|
||
- Fog of war remains per-player (each player only sees tiles in their own LoS/range)
|
||
|
||
### 5d. Targeting highlights
|
||
|
||
Team-aware: ally units highlighted in blue, enemy units in red, self in white — consistent with `TeamIndex` comparisons.
|
||
|
||
### 5e. Turn-order display
|
||
|
||
A compact strip at the top of the screen shows all players in seat order with a pointer to the current active player (inspired by board game UX). Eliminated players are greyed out.
|
||
|
||
---
|
||
|
||
## 6. Protocol Changes
|
||
|
||
### 6a. New events
|
||
|
||
| Event | Payload |
|
||
|---|---|
|
||
| `player_eliminated` | `{ playerId, seatIndex, teamIndex }` |
|
||
| `team_eliminated` | `{ teamIndex }` |
|
||
| `game_won` | `{ winnerTeamIndex, winnerPlayerIds[] }` (replaces `game_over` for team modes) |
|
||
| `turn_changed` | `{ newSeatIndex, playerId }` (replaces current binary turn flag) |
|
||
|
||
### 6b. `game_state` snapshot changes
|
||
|
||
- `current_turn_player_id` field replaces `is_your_turn` boolean
|
||
- New `players` array with full `PlayerSlot` data for all N players
|
||
- New `board_shape` field with the layout name for client-side rendering
|
||
|
||
---
|
||
|
||
## 7. Phased Implementation
|
||
|
||
### Phase 1 — 2-player team-aware foundation (low risk)
|
||
- Refactor `PlayerSlot` list; keep backward compat for existing 1v1 by auto-assigning two slots with different team indices
|
||
- Update `Own()` helper to use `TeamIndex`
|
||
- Add `CheckVictory` team logic
|
||
- All existing 1v1 games use `FFA` mode with 2 players — no behavioral change
|
||
|
||
### Phase 2 — Multi-player FFA (3–6 players)
|
||
- Round-robin turn engine
|
||
- Eliminated-player skip logic
|
||
- Cross and Radial board shapes
|
||
- Client player ring + turn-order strip
|
||
- Lobby room with N-slot capacity
|
||
|
||
### Phase 3 — Team modes
|
||
- N vs N lobby team assignment UI
|
||
- Multi-team (2v2v2 etc.) win condition
|
||
- Team color system in client
|
||
|
||
### Phase 4 — Board shape library
|
||
- Hexagonal Ring, Decagonal, Triangular generators
|
||
- Auto-selection by player count
|
||
- Admin tool for previewing/testing board layouts
|
||
|
||
### Phase 5 — Polish
|
||
- Asymmetric team sizes with SP/ST handicap
|
||
- Spectator mode for eliminated players
|
||
- Ranked matchmaking with multi-player ELO
|
||
|
||
---
|
||
|
||
## 8. Critical Files
|
||
|
||
| File | Change |
|
||
|---|---|
|
||
| `SOR.Game/GameState.cs` | Replace Player1/Player2 with `IReadOnlyList<PlayerSlot>` |
|
||
| `SOR.Game/GameEngine.cs` | Round-robin turn logic, elimination detection, team win check |
|
||
| `SOR.Game/Grid/GridFactory.cs` *(new)* | Board shape generators for each layout |
|
||
| `SOR.Game/Grid/BoardLayout.cs` *(new)* | `ValidTiles` + `StartingZones[]` model |
|
||
| `SOR.Game/Abilities/AbilitySystem.cs` | `Own()` uses `TeamIndex` comparison |
|
||
| `SOR.Content/Lobby/` | Room creation with mode/team config |
|
||
| `Client/scenes/game/game_screen.gd` | Dynamic player panel, camera fit, turn strip |
|
||
| `Client/scenes/free_play/lobby_room_screen.gd` | Team assignment UI, seat slots |
|
||
| `Client/autoloads/GameProtocol.gd` | New events: `player_eliminated`, `team_eliminated`, `turn_changed` |
|
||
|
||
---
|
||
|
||
## Notes
|
||
|
||
- **Rules don't change.** Combat, abilities, SP/ST, channeling, LoS — all preserved exactly as-is.
|
||
- **The tile coordinate system stays.** `Coord(row, col)` continues to work; non-rectangular boards simply have sparse valid-tile sets.
|
||
- **Backward compatibility.** Existing 1v1 games just use two `PlayerSlot` entries with different `TeamIndex` values; no migration of saved games needed.
|
||
- **Board shapes are data.** A generator function produces a `BoardLayout` record from `(playerCount, sizeHint)` — no hardcoded map files.
|
||
|
||
---
|
||
|
||
## File: OVERALL.md
|
||
|
||
# TODO
|
||
|
||
- [ ] SOR: Design and implement version tagging/release flow (move away from `:latest`; use SemVer + Gitea Action for tagged image builds/promotions).
|
||
|
||
- [ ] Custom Games backlog:
|
||
- [ ] Admin: Custom lobby oversight — admin page listing active/recent custom lobbies, with ability to cancel a lobby or kick a player.
|
||
- [ ] Lobby chat — in-lobby text chat between host and guest before game start.
|
||
- [ ] Friend/direct invite — invite specific player by name/ID to a lobby, bypassing browser.
|
||
- [ ] Public preset sharing — presets are currently owner-scoped; public browsable presets deferred.
|
||
- [ ] Replay system — recording and replay of completed games (related to spectating infrastructure).
|
||
- [ ] Vote "concede" option — add third option to preset-load vote to concede/exit lobby if vote stalls.
|
||
- [ ] Lobby update while waiting — host rule changes after guest joins (without preset vote); requires push + guest acknowledgement flow in Full state.
|
||
|
||
- [ ] Platform/engine backlog (not only Custom Games):
|
||
- [ ] Board templates polish — improve template UX/workflows after initial board-template ship (builder/list/integration now live).
|
||
- [ ] Hex tile shape — `TileShape` enum stub (Square/Hex) can be stored, but engine, client renderer, and pathfinding are square-only. Hex remains UI-disabled.
|
||
|
||
- [ ] Product/UI/Platform backlog:
|
||
- [ ] IAM/OIDC integration follow-up: configure and validate Keycloak clients + RBAC mappings for Harbor, Ceph, and MinIO using new groups (`*-admin`, `*-readonly`).
|
||
- [ ] UI/UX OAuth config update (Google first).
|
||
- [ ] Boot logo change.
|
||
- [ ] App icon change.
|
||
- [ ] Refactor each scene: split UI building out of `.gd` into node-based scene structure for easier UI changes.
|
||
- [ ] Game website.
|
||
- [ ] Tutorial in game + how-to guide on website.
|
||
- [ ] Legal docs: TOS, Privacy Policy, EULA, Cookie Policy, plus any additional required docs (track in `Shared/legal.md`).
|
||
|
||
- [ ] Account management:
|
||
- [ ] Link OAuth to existing account.
|
||
- [ ] Reset password flow.
|
||
- [ ] Full account metrics for leaderboard (including ranking).
|
||
|
||
- [ ] Spending panel:
|
||
- [ ] Uncensor toggle (censored by default).
|
||
- [ ] Full tracker on USD / Origin Points spent and what it was spent on.
|
||
- [ ] Download spending report.
|
||
|
||
- [ ] Spending controls panel:
|
||
- [ ] Set monthly spending cap (money and/or Origin Points).
|
||
- [ ] Cap is lock-enforced once set.
|
||
- [ ] Cap can only be changed once per month.
|
||
- [ ] Warning prompts required before setting/changing cap.
|
||
- [ ] Show next eligible cap-change date/time.
|
||
|
||
- [ ] Legal links panel:
|
||
- [ ] TOS, EULA, and other required legal docs links.
|
||
|
||
- [ ] Bazaar / economy:
|
||
- [ ] Player marketplace:
|
||
- [ ] Search/browse listed cards.
|
||
- [ ] Listing details: card identity (definition + variant), seller, price (Origin Points), listed-at timestamp, listing status.
|
||
- [ ] Actions: buy listing, cancel own listing, create listing from owned inventory.
|
||
- [ ] Filters/sort: card name/type/rarity/affinity, min/max price, newest, price asc, price desc.
|
||
- [ ] Buy Origin Points (USD purchase flow).
|
||
- [ ] Payment method display + confirmation modal.
|
||
- [ ] Show SKU pricing/details in USD and Origin Points (where applicable).
|
||
- [ ] Sacrifice / disenchant:
|
||
- [ ] Select cards from owned inventory.
|
||
- [ ] Preview Origin Points return before confirm.
|
||
- [ ] Explicit irreversible warning.
|
||
- [ ] Confirm flow: remove/flag cards from inventory and credit Origin Points.
|
||
- [ ] Ledger/history (player view):
|
||
- [ ] Transaction timeline for marketplace buys/sells, store purchases, sacrifices, refunds/reversals.
|
||
- [ ] Receipt details with transaction id.
|
||
|
||
- [ ] Audit / chain-of-custody requirements (critical):
|
||
- [ ] Immutable ledger entry for every economy event including: `transactionId`, `eventType`, `accountId`(s), asset refs (`cardInstanceId`, `skuId`, etc.), balance before/after, timestamp, and request correlation (`requestId`).
|
||
- [ ] Full custody trail per card instance: minted/acquired → listed → sold/transferred → sacrificed/destroyed.
|
||
- [ ] USD purchases store payment provider reference id(s) and receipt linkage.
|
||
- [ ] Admin/internal investigation queries for suspicious activity patterns.
|
||
|
||
- [ ] Fraud / abuse signals (planned):
|
||
- [ ] Repeated rapid buy/sell loops between same accounts.
|
||
- [ ] Outlier pricing patterns.
|
||
- [ ] High-frequency sacrifices after suspicious acquisitions.
|
||
- [ ] Chargeback/refund correlation with asset transfers.
|
||
- [ ] Multi-account linkage risk indicators.
|
||
|
||
- [ ] Collection:
|
||
- [ ] Add cosmetics.
|
||
- [ ] Enable toggle to apply cosmetics to cards/decks.
|
||
- [ ] Cosmetics panel UI:
|
||
- [ ] Category selector (back/trim/art/model).
|
||
- [ ] Preview pane.
|
||
- [ ] Owned/locked state indicators.
|
||
- [ ] Equip/apply controls.
|
||
|
||
- [ ] Custom Games additions:
|
||
- [ ] Filter controls (open slots, format/rules tags, region, friends-only).
|
||
- [ ] Rules detail tooltip/panel on hover/focus with full ruleset display.
|
||
|
||
- [ ] Leaderboard:
|
||
- [ ] Track additional properties for a richer leaderboard.
|
||
|
||
- [ ] Login / register:
|
||
- [ ] OAuth buttons for login/register.
|
||
- [ ] Forgot password flow.
|
||
- [ ] Register: add TOS/Privacy acceptance.
|
||
|
||
- [ ] Ranked:
|
||
- [ ] Ranked game viewer: enable spectate for ranked games.
|
||
- [ ] Anti-rematch / pairing controls:
|
||
- [ ] Avoid same-opponent rematch within last 2 completed ranked games when alternatives exist.
|
||
- [ ] Soft rule only; allow bypass at high queue times.
|
||
|
||
- [ ] Settings:
|
||
- [ ] Add message support / bug report entry.
|
||
|
||
- [ ] Gameplay:
|
||
- [ ] Full timing windows and reaction timing.
|
||
- [ ] Mulligan rules.
|
||
|
||
- [ ] Ability system backlog (post Phase 3):
|
||
- [ ] Tile-bound deferred marker memory + tile equality references (e.g., "mark this tile; next unit entering gets X").
|
||
- [ ] ChooseOne/modal branch execution hardening as a trusted runtime-authoring path (not just schema presence).
|
||
- [ ] Exact player-chosen reposition destination flows from legal tiles (validation + UX clarity).
|
||
- [ ] Channel-cost modification keyed to destination tile state/affinity (e.g., cheaper channel onto Marsh).
|
||
|
||
- [ ] Networking/privacy hardening:
|
||
- [ ] Delta identity decoupling: replace client-visible `accountId` usage in game wire payloads with session-scoped `playerRef` identifiers.
|
||
- [ ] Server identity map: maintain authoritative `sessionId + playerRef -> accountId` mapping with strict invariants on join/reconnect/resume.
|
||
- [ ] Logging/telemetry split: keep internal accountId linkage in server logs only; expose `playerRef` (and display name) in client-visible/debug payloads.
|
||
|
||
---
|
||
|
||
## Considerations for Later
|
||
|
||
These features are intentionally deferred — they require significant design work or depend on
|
||
other foundational systems not yet in place.
|
||
|
||
- **Fog of War**: Restrict each player's board visibility to tiles/units within a defined sight
|
||
range. Requires a server-side visibility model (per-player tile sets), partial state
|
||
serialisation in game messages, and client-side fog overlay rendering. Non-trivial for
|
||
multiplayer without leaking hidden state.
|
||
|
||
- **Asymmetric team sizes**: Allow lobbies where teams have different player counts (e.g. 3v1,
|
||
2v1v1). Currently `teamCount` divides seats evenly. Requires a seat-to-team mapping override,
|
||
balancing rules, matchmaking weight adjustments, and UI to expose the configuration.
|
||
|
||
- **Ranked multiplayer tuning**: Continue balancing/validating multi-player rating behavior and anti-manipulation safeguards as live data grows.
|
||
|
||
---
|
||
|
||
## File: .plan.md
|
||
|
||
# Ranked Gameplay UI — Implementation Plan
|
||
|
||
## Overview
|
||
Three layers of work:
|
||
1. **`Game.gd` autoload** — stores game state, handles server pushes, exposes helpers
|
||
2. **Matchmaking screen** — queue join/wait/cancel, deck selection, navigates to game on match found
|
||
3. **GameScreen** — 3D board + 2D HUD overlay, all game actions wired
|
||
|
||
---
|
||
|
||
## Files to Create / Modify
|
||
|
||
### New files (client)
|
||
| File | Purpose |
|
||
|------|---------|
|
||
| `autoloads/Game.gd` | Game state autoload |
|
||
| `scenes/matchmaking/MatchmakingScreen.tscn + .gd` | Queue waiting screen |
|
||
| `scenes/game/GameScreen.tscn + .gd` | Full 3D game scene |
|
||
|
||
### Modified files
|
||
| File | Change |
|
||
|------|--------|
|
||
| `scenes/main/main_screen.gd` | Wire MatchBtn → MatchmakingScreen |
|
||
| `project.godot` | Register Game autoload |
|
||
|
||
---
|
||
|
||
## 1. Game.gd Autoload
|
||
|
||
Signals: `match_found(session_id, opponent_name, opponent_rank)`, `state_updated(state)`, `game_over(winner_id, win_condition)`
|
||
|
||
State stored: `session_id`, `state` (full GameStateDto dict), `my_account_id`
|
||
|
||
On `Network.message_received`:
|
||
- `matchmaking.match_found` → store session_id, emit `match_found`
|
||
- `game.state_update.push` → store state, emit `state_updated`
|
||
- `game.over.push` → emit `game_over`
|
||
|
||
Public helpers: `get_my_player()`, `get_opponent()`, `is_my_turn()`, `get_board_tiles()`, `get_hand()`, `get_phase()`
|
||
|
||
---
|
||
|
||
## 2. MatchmakingScreen
|
||
|
||
Flow:
|
||
1. On `_ready`: call `collection.get_decks` to fetch player's decks
|
||
2. Show deck list for selection (or auto-pick if only one)
|
||
3. On deck selected → call `matchmaking.join` → show "Searching…" spinner with elapsed timer
|
||
4. Cancel button → `matchmaking.leave` → back to MainScreen
|
||
5. On `Game.match_found` signal → navigate to `GameScreen.tscn`
|
||
|
||
Also handles: already-in-queue case (calls `matchmaking.status` to restore state)
|
||
|
||
---
|
||
|
||
## 3. GameScreen Architecture
|
||
|
||
### 3D Scene structure
|
||
```
|
||
GameScreen (Node3D)
|
||
├── WorldEnvironment — skybox (ProceduralSky)
|
||
├── DirectionalLight3D
|
||
├── CameraRig (Node3D) — pivot at board center (0,0,0)
|
||
│ └── Camera3D — at (0, 10, 9), looking down at 48°
|
||
├── BoardRoot (Node3D)
|
||
│ ├── TilesRoot — 64 StaticBody3D + BoxMesh tiles
|
||
│ ├── UnitsRoot — dynamic unit placeholder meshes
|
||
│ └── HighlightsRoot — thin overlay planes (highlights)
|
||
└── HUD (CanvasLayer, layer=10)
|
||
```
|
||
|
||
### Tile mesh
|
||
- `BoxMesh` size `(1, 0.5, 1)` at position `(x - 3.5, 0.25, y - 3.5)` for an 8×8 board
|
||
- Material color = affinity color (24-entry dict)
|
||
- `StaticBody3D` + `BoxShape3D` for input detection via raycast
|
||
|
||
### Unit placeholders
|
||
| Card type | Mesh | Size | Color |
|
||
|-----------|------|------|-------|
|
||
| Spirit | SphereMesh | r=0.3 | team-colored (blue/red) |
|
||
| ArchSpirit | CylinderMesh | r=0.25, h=0.8 | team-colored, bright |
|
||
| SpiritToken | SphereMesh | r=0.2 | muted team color |
|
||
| Ruin | BoxMesh | 0.25×1.0×0.25 | dark grey |
|
||
|
||
Units sit on top of tiles at `y = 0.5 + half_height`.
|
||
|
||
### Highlight overlays (HighlightsRoot children)
|
||
| Highlight | Color | Use |
|
||
|-----------|-------|-----|
|
||
| `green_fill` | `(0.2, 0.9, 0.2, 0.35)` | Valid play tile / movement range |
|
||
| `red_outline` | `(1.0, 0.25, 0.25, 0.5)` | Attack range / enemy unit target |
|
||
| `blue_fill` | `(0.2, 0.5, 1.0, 0.35)` | Ability target |
|
||
| `yellow_fill` | `(1.0, 0.85, 0.1, 0.45)` | Selected unit's tile |
|
||
|
||
Each highlight is a flat `BoxMesh (1, 0.02, 1)` at `y = 0.5 + 0.01`.
|
||
|
||
### Camera controls
|
||
- **Orbit** (left-mouse drag / single touch drag): rotate CameraRig Y-axis; clamp pitch
|
||
- **Zoom** (scroll wheel / pinch): translate Camera3D along its -Z axis; clamp distance 4–20
|
||
- **Pan** (middle-mouse drag / two-finger slide): translate CameraRig in XZ plane
|
||
|
||
### HUD layout (all 2D CanvasLayer)
|
||
```
|
||
TopBar (HBoxContainer, top of screen)
|
||
PhaseLabel | TurnLabel | [Opponent: 5 cards | deck:30 | DISCARD]
|
||
|
||
HandArea (bottom, 200px tall)
|
||
ScrollContainer → HBoxContainer of GameCardWidgets
|
||
— hover: card scales up + moves up 30px (z_index = 10)
|
||
— selected: bright border; card click = select, tile click = play
|
||
|
||
RightPanel (right side, 180px wide)
|
||
SP: {n} | ST: {n}
|
||
Deck: {n} | [View Discard]
|
||
[Draw Card] [End Turn] [Concede]
|
||
|
||
ContextPopup (center popup, shows on 0.5s hold on tile)
|
||
Tile: ({x},{y}) | Affinity: {aff}
|
||
Occupant: {name} | HP: {hp}/{max} | DEF: {def}/{max}
|
||
[card abilities listed if unit present]
|
||
|
||
DiscardViewer (full overlay, shown on discard click)
|
||
ScrollContainer of card name rows
|
||
[Close]
|
||
```
|
||
|
||
### GameCardWidget (built programmatically, no .tscn)
|
||
- Sized ~100×155px (smaller than collection widget for hand use)
|
||
- Shows: card art placeholder (colored rect by affinity), name, SP cost, type icon, key stat (Damage or HP)
|
||
- Built directly from `CardInstanceDto` dict (no definition lookup needed — server already merged)
|
||
|
||
### Selection state machine
|
||
```gdscript
|
||
enum Mode { NONE, CARD_FROM_HAND, UNIT_SELECTED, PLACEMENT }
|
||
var _sel_mode : Mode = Mode.NONE
|
||
var _sel_card_id : String = "" # hand card instance ID
|
||
var _sel_unit_id : String = "" # field unit instance ID
|
||
```
|
||
|
||
**CARD_FROM_HAND**: Raycast click on a green-highlighted tile → send `game.play_card`
|
||
**UNIT_SELECTED**: Raycast click on green tile → `game.move_unit`; red-highlighted enemy unit → `game.attack`
|
||
**PLACEMENT**: Highlighted valid placement tiles → click → `game.place_arch_spirit`
|
||
|
||
### Phase-aware action bar
|
||
| Phase | Available actions |
|
||
|-------|-----------------|
|
||
| Placement | Place ArchSpirit button highlighted |
|
||
| Draw | Auto-draw on load (calls `game.draw`), or "Draw Card" button |
|
||
| Main | Full bar: play cards, move, attack, sacrifice, ascend, transition, end turn |
|
||
| GameOver | "Return to Main Menu" only |
|
||
|
||
### Hold timer (context popup)
|
||
- `Timer` (0.5s, one-shot) started on `BUTTON_LEFT` pressed on a tile
|
||
- Cancelled on mouse move or release
|
||
- On timeout: show ContextPopup with tile + occupant data
|
||
|
||
### Opponent discard viewer
|
||
- Opponent's `Discard` array is always visible in `GameStateDto`
|
||
- Clicking "View Discard" opens a scrollable list of card names + types
|
||
|
||
---
|
||
|
||
## 4. Wiring MainScreen
|
||
|
||
`main_screen.gd`: add `@onready var match_btn : Button = %MatchBtn`
|
||
On pressed → `get_tree().change_scene_to_file("res://scenes/matchmaking/MatchmakingScreen.tscn")`
|
||
|
||
---
|
||
|
||
## Coord ↔ 3D mapping
|
||
|
||
```gdscript
|
||
func coord_to_world(x: int, y: int) -> Vector3:
|
||
return Vector3(x - 3.5, 0.0, y - 3.5) # tiles centered at origin
|
||
|
||
func world_to_coord(pos: Vector3) -> Vector2i:
|
||
return Vector2i(roundi(pos.x + 3.5), roundi(pos.z + 3.5))
|
||
```
|
||
|
||
---
|
||
|
||
## Implementation Order
|
||
1. `Game.gd` + `project.godot`
|
||
2. `MatchmakingScreen`
|
||
3. Wire `MatchBtn` in `main_screen.gd`
|
||
4. `GameScreen` — board, camera, units
|
||
5. `GameScreen` — HUD, hand, action bar
|
||
6. `GameScreen` — selection state, highlights, all game actions
|
||
7. `GameScreen` — context popup, discard viewer, game-over handling
|
||
|
||
---
|
||
|
||
## File: README.md
|
||
|
||
# SOR
|
||
|
||
## Resources
|
||
|
||
In addition to this gitea repository, the application's servers and webclient are deployed using containers using ArgoCD.
|
||
- https://argo.aeternalisgames.com/
|
||
|
||
## Installation Instructions
|
||
|
||
### Visual Studio Code
|
||
|
||
Download any version of Visual Studio Code, from here:
|
||
- https://code.visualstudio.com/download
|
||
|
||
### Godot Version 4.5.x
|
||
|
||
Download a version of Godot 4.5.x, preferrably Godot 4.5.2-stable, from here:
|
||
- https://godotengine.org/download/archive/4.5.2-stable/
|
||
|
||
The Godot executable doesn't require an installation. Just unzip the godot folder and run the 'Godot_v4.5.2-stable_win64' executable.
|
||
|
||
## Clone Instructions
|
||
|
||
Only HTTPS clone to VSCode is supported at the moment.
|
||
- SSH Clone doesn't work since the repository root doesn't have a .git folder.
|
||
|
||
On the "Code" page for SOR, click the "Code" button and then click "Open with VS Code".
|
||
- Your browser may ask if you want to launch VS Code. Do so.
|
||
- VS Code will utilize your browser to authenticate. Do so.
|
||
|
||
# The Client
|
||
|
||
The Client is a GUI created in Godot.
|
||
|
||
## Modifying the Client in Godot
|
||
|
||
Once you've cloned the repository, Open Godot.
|
||
|
||
Then, select "Import".
|
||
|
||
Open the project.godot file in the Client/origin-client/ folder.
|
||
|
||
## Building the Web Client
|
||
|
||
When you update the 'main' branch of the SOR Repository, a gitea action will automatically start, building the Godot Web Client.
|
||
|
||
## Deploying the Web Client
|
||
|
||
After the Web Client is built, you need to restart (not sync) the Deployment object of the sor-webclient application in ArgoCD.
|
||
|
||

|
||
---
|
||
|
||
## File: Server/architecture.md
|
||
|
||
# SOR Server — Programming Architecture
|
||
|
||
This document defines the strict, repeatable architecture every service in the SOR backend follows.
|
||
It is the canonical source of truth for how code is organized, how services communicate, and how
|
||
patterns are applied consistently across the codebase.
|
||
|
||
**Language**: C# 12 (.NET 8)
|
||
**Build system**: MSBuild via the .sln solution file
|
||
**Repo layout**: Monorepo — all services and shared code live in one repository
|
||
|
||
---
|
||
|
||
## Table of Contents
|
||
|
||
1. [Why C# / .NET 8](#1-why-c--net-8)
|
||
2. [Repository Structure](#2-repository-structure)
|
||
3. [Service Project Layout (3-Layer Pattern)](#3-service-project-layout)
|
||
4. [Shared Library — SOR.Shared](#4-shared-library--sorshared)
|
||
5. [Protobuf Contracts — SOR.Shared.Proto](#5-protobuf-contracts--sorsharedproto)
|
||
6. [Multi-Service Runner — SOR.Host](#6-multi-service-runner--sorhost)
|
||
7. [Dependency Injection](#7-dependency-injection)
|
||
8. [Configuration System](#8-configuration-system)
|
||
9. [gRPC Handlers](#9-grpc-handlers)
|
||
10. [NATS Integration](#10-nats-integration)
|
||
11. [Redis Integration](#11-redis-integration)
|
||
12. [Database — EF Core + PostgreSQL](#12-database--ef-core--postgresql)
|
||
13. [Logging — Serilog](#13-logging--serilog)
|
||
14. [Error Handling](#14-error-handling)
|
||
15. [Health Checks](#15-health-checks)
|
||
16. [Testing Patterns](#16-testing-patterns)
|
||
17. [Naming Conventions](#17-naming-conventions)
|
||
18. [Hard Rules](#18-hard-rules)
|
||
|
||
---
|
||
|
||
## 1. Why C# / .NET 8
|
||
|
||
C# is a statically typed, compiled language in the same family as Java and Kotlin, but with
|
||
a cleaner modern syntax and exceptional first-class support for async/await, which is critical
|
||
for a server that handles thousands of concurrent connections.
|
||
|
||
**.NET 8** is the current long-term support (LTS) release. It includes:
|
||
- Native AOT compilation (faster startup, smaller containers — optional, enabled per service)
|
||
- `System.Threading.Channels` — lock-free async queues (used in Gateway for message dispatch)
|
||
- Top-level programs — less boilerplate in `Program.cs`
|
||
- Source generators — compile-time code generation for Protobuf and serialization
|
||
|
||
**ASP.NET Core** is the web framework built into .NET. It hosts HTTP endpoints, gRPC endpoints,
|
||
and WebSocket connections in the same process with a unified middleware pipeline. No external
|
||
web framework is needed.
|
||
|
||
---
|
||
|
||
## 2. Repository Structure
|
||
|
||
```
|
||
SOR/
|
||
└── Server/
|
||
├── SOR.sln # Visual Studio solution — lists all projects
|
||
├── Directory.Build.props # MSBuild properties shared across ALL projects
|
||
├── Directory.Packages.props # Central NuGet package version management
|
||
│
|
||
├── src/
|
||
│ ├── SOR.Host/ # Multi-service runner (the deployable binary)
|
||
│ ├── SOR.Shared/ # Shared utilities, base classes, interfaces
|
||
│ ├── SOR.Shared.Proto/ # Protobuf .proto files + generated C# code
|
||
│ │
|
||
│ ├── SOR.Gateway/ # Gateway service module
|
||
│ ├── SOR.Auth/ # Auth service module
|
||
│ ├── SOR.Game/ # Game service module
|
||
│ ├── SOR.Chat/ # Chat service module
|
||
│ ├── SOR.Collection/ # Collection service module
|
||
│ ├── SOR.Bazaar/ # Bazaar service module
|
||
│ ├── SOR.Admin/ # Admin service module
|
||
│ ├── SOR.Leaderboard/ # Leaderboard service module
|
||
│ └── SOR.Content/ # Content service module
|
||
│
|
||
└── tests/
|
||
├── SOR.Auth.Tests/
|
||
├── SOR.Game.Tests/
|
||
├── SOR.Chat.Tests/
|
||
├── SOR.Collection.Tests/
|
||
├── SOR.Bazaar.Tests/
|
||
├── SOR.Leaderboard.Tests/
|
||
└── SOR.Content.Tests/
|
||
```
|
||
|
||
### Directory.Build.props
|
||
|
||
This file applies MSBuild properties to every project without repeating them. It lives at the
|
||
`Server/` level and is automatically picked up by all `.csproj` files underneath it.
|
||
|
||
```xml
|
||
<!-- Server/Directory.Build.props -->
|
||
<Project>
|
||
<PropertyGroup>
|
||
<!-- Target .NET 8 in every project -->
|
||
<TargetFramework>net8.0</TargetFramework>
|
||
|
||
<!-- Enforce nullable reference types: the compiler will warn when a variable
|
||
that can be null is used without a null check. This prevents NullReferenceException
|
||
at runtime by catching issues at compile time. -->
|
||
<Nullable>enable</Nullable>
|
||
|
||
<!-- Enable all C# language features for the current version -->
|
||
<LangVersion>latest</LangVersion>
|
||
|
||
<!-- Treat compiler warnings as errors — keeps code quality high -->
|
||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||
|
||
<!-- Implicit using statements: automatically imports the most common
|
||
namespaces (System, System.Linq, System.Collections.Generic, etc.)
|
||
so every file doesn't need a wall of `using` directives at the top -->
|
||
<ImplicitUsings>enable</ImplicitUsings>
|
||
</PropertyGroup>
|
||
</Project>
|
||
```
|
||
|
||
### Directory.Packages.props
|
||
|
||
Central package version management. All NuGet package versions are declared here once.
|
||
Individual `.csproj` files reference package names without version numbers — they inherit
|
||
from here. This prevents version drift across projects.
|
||
|
||
```xml
|
||
<!-- Server/Directory.Packages.props -->
|
||
<Project>
|
||
<PropertyGroup>
|
||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||
</PropertyGroup>
|
||
|
||
<ItemGroup>
|
||
<!-- gRPC server implementation for ASP.NET Core -->
|
||
<PackageVersion Include="Grpc.AspNetCore" Version="2.62.0" />
|
||
|
||
<!-- Official NATS client for .NET -->
|
||
<PackageVersion Include="NATS.Net" Version="2.3.0" />
|
||
|
||
<!-- StackExchange.Redis — battle-tested Redis client for .NET -->
|
||
<PackageVersion Include="StackExchange.Redis" Version="2.7.33" />
|
||
|
||
<!-- Entity Framework Core — the ORM (Object-Relational Mapper) that lets
|
||
us work with database rows as C# objects instead of raw SQL -->
|
||
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
|
||
|
||
<!-- PostgreSQL driver for EF Core (Npgsql) -->
|
||
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
|
||
|
||
<!-- EF Core design-time tools (migrations, scaffolding) -->
|
||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0" />
|
||
|
||
<!-- Serilog: structured logging library -->
|
||
<PackageVersion Include="Serilog.AspNetCore" Version="8.0.0" />
|
||
<PackageVersion Include="Serilog.Sinks.Console" Version="5.0.0" />
|
||
<PackageVersion Include="Serilog.Sinks.Seq" Version="7.0.0" />
|
||
|
||
<!-- xUnit: the testing framework -->
|
||
<PackageVersion Include="xunit" Version="2.6.6" />
|
||
<PackageVersion Include="xunit.runner.visualstudio" Version="2.5.7" />
|
||
|
||
<!-- Moq: mock objects for unit tests -->
|
||
<PackageVersion Include="Moq" Version="4.20.70" />
|
||
|
||
<!-- FluentAssertions: readable assertion syntax in tests -->
|
||
<PackageVersion Include="FluentAssertions" Version="6.12.0" />
|
||
|
||
<!-- Microsoft test host for integration tests -->
|
||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.0" />
|
||
</ItemGroup>
|
||
</Project>
|
||
```
|
||
|
||
---
|
||
|
||
## 3. Service Project Layout
|
||
|
||
Every service follows the identical three-layer structure. No exceptions.
|
||
|
||
```
|
||
src/SOR.Auth/
|
||
├── SOR.Auth.csproj
|
||
├── ServiceRegistration.cs # The ONE public entry point for this module
|
||
│
|
||
├── Handlers/ # Layer 1 — receives external calls (gRPC, NATS)
|
||
│ └── AuthGrpcHandler.cs # Implements the gRPC service contract
|
||
│
|
||
├── Services/ # Layer 2 — all business logic lives here
|
||
│ ├── IAuthService.cs # Interface (used for testing / substitution)
|
||
│ └── AuthService.cs # Implementation
|
||
│
|
||
├── Repositories/ # Layer 3 — all database access lives here
|
||
│ ├── IAuthRepository.cs # Interface
|
||
│ └── AuthRepository.cs # Implementation using EF Core
|
||
│
|
||
├── Models/ # Domain objects used inside this service
|
||
│ ├── User.cs
|
||
│ └── SessionToken.cs
|
||
│
|
||
└── Data/ # EF Core database context for this service
|
||
├── AuthDbContext.cs
|
||
└── Migrations/ # Auto-generated by EF Core; tracks schema changes
|
||
```
|
||
|
||
### The Three Layers
|
||
|
||
**Layer 1 — Handlers** receive the incoming request from outside. They are thin:
|
||
- Deserialize the incoming message
|
||
- Call the appropriate Service method
|
||
- Serialize and return the response
|
||
- No business logic here
|
||
|
||
**Layer 2 — Services** contain all business logic:
|
||
- Validation
|
||
- Orchestrating calls to repositories and other services
|
||
- Applying rules
|
||
- Never talk directly to the database — always go through repositories
|
||
|
||
**Layer 3 — Repositories** contain all database access:
|
||
- Query the database using EF Core
|
||
- Return domain model objects (not raw database rows)
|
||
- No business logic here
|
||
|
||
### Why this separation matters
|
||
|
||
Each layer can be tested independently. A service test mocks the repository so no database
|
||
is needed. A handler test mocks the service so no business logic runs. This makes tests fast,
|
||
reliable, and easy to write.
|
||
|
||
### ServiceRegistration.cs — the module's public contract
|
||
|
||
Every service module exposes exactly ONE public method: a static extension method called
|
||
`Add{ServiceName}Service`. This is how SOR.Host enables a service. Nothing else in the
|
||
module is public unless it must be.
|
||
|
||
```csharp
|
||
// src/SOR.Auth/ServiceRegistration.cs
|
||
|
||
// 'namespace' groups related code together and prevents naming collisions.
|
||
// Convention: namespace matches folder path from solution root.
|
||
namespace SOR.Auth;
|
||
|
||
// 'static class' means this class can never be instantiated — it only holds
|
||
// static methods. Extension method containers are always static classes.
|
||
public static class ServiceRegistration
|
||
{
|
||
// This is an extension method on IServiceCollection. The 'this' keyword
|
||
// on the first parameter is what makes it an extension method — it can
|
||
// be called as if it were a method on IServiceCollection itself:
|
||
// builder.Services.AddAuthService(builder.Configuration)
|
||
//
|
||
// IServiceCollection is the .NET dependency injection container that tracks
|
||
// everything the app needs. You register things into it during startup, and
|
||
// the framework injects them wherever they're needed at runtime.
|
||
public static IServiceCollection AddAuthService(
|
||
this IServiceCollection services,
|
||
IConfiguration configuration)
|
||
{
|
||
// Bind the "Auth" section of appsettings.json to a typed options class.
|
||
// IOptions<AuthOptions> can then be injected anywhere in this service.
|
||
services.Configure<AuthOptions>(configuration.GetSection("Auth"));
|
||
|
||
// Register the database context scoped to each request.
|
||
// "Scoped" means one instance per request — all code within a single
|
||
// request shares the same DbContext instance.
|
||
services.AddDbContext<AuthDbContext>(options =>
|
||
options.UseNpgsql(configuration.GetConnectionString("Auth")));
|
||
|
||
// Register the repository and service.
|
||
// AddScoped<interface, implementation>: whenever something asks for
|
||
// IAuthRepository, the DI container creates an AuthRepository.
|
||
services.AddScoped<IAuthRepository, AuthRepository>();
|
||
services.AddScoped<IAuthService, AuthService>();
|
||
|
||
// Register the gRPC handler. MapGrpcService (called later in Host)
|
||
// routes incoming gRPC calls to this handler class.
|
||
services.AddGrpc();
|
||
|
||
return services;
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 4. Shared Library — SOR.Shared
|
||
|
||
`SOR.Shared` is the one library every other project references. It contains code that would
|
||
otherwise be duplicated across services. Strict rule: **add to SOR.Shared only when two or more
|
||
services need the same code**. Do not preemptively add things here.
|
||
|
||
```
|
||
src/SOR.Shared/
|
||
├── SOR.Shared.csproj
|
||
│
|
||
├── Interfaces/
|
||
│ └── ISorService.cs # Marker interface every service implements
|
||
│
|
||
├── Redis/
|
||
│ ├── RedisConnectionFactory.cs # Builds and caches the Redis connection
|
||
│ └── RedisKeys.cs # All Redis key name constants in one place
|
||
│
|
||
├── Nats/
|
||
│ ├── NatsConnectionFactory.cs # Builds the NATS connection
|
||
│ └── NatsSubjects.cs # All NATS subject name constants in one place
|
||
│
|
||
├── Models/
|
||
│ └── ServiceResult.cs # Standardized operation result wrapper
|
||
│
|
||
├── Exceptions/
|
||
│ └── SorException.cs # Base exception with error codes
|
||
│
|
||
└── Extensions/
|
||
└── StringExtensions.cs # Utility methods on string, Guid, etc.
|
||
```
|
||
|
||
### ServiceResult — the standard return type
|
||
|
||
Business logic methods return `ServiceResult<T>` instead of throwing exceptions for
|
||
expected failures (user not found, invalid password, etc.). Exceptions are reserved for
|
||
truly unexpected failures (database down, out of memory).
|
||
|
||
```csharp
|
||
// src/SOR.Shared/Models/ServiceResult.cs
|
||
namespace SOR.Shared.Models;
|
||
|
||
// A 'record' is an immutable data structure in C#. It generates equality checks,
|
||
// ToString(), and other utilities automatically based on its properties.
|
||
// The <T> makes it generic — T is replaced with the actual type at the call site,
|
||
// e.g., ServiceResult<User> or ServiceResult<string>.
|
||
public record ServiceResult<T>
|
||
{
|
||
// 'required' means this property must be set when constructing the record.
|
||
// The '?' after 'T' makes the type nullable — Value can be null.
|
||
public required bool Success { get; init; }
|
||
public T? Value { get; init; }
|
||
public string? ErrorCode { get; init; }
|
||
public string? ErrorMessage { get; init; }
|
||
|
||
// Static factory methods — create results without calling 'new' directly.
|
||
// 'static' means these belong to the type, not an instance.
|
||
public static ServiceResult<T> Ok(T value) =>
|
||
new() { Success = true, Value = value };
|
||
|
||
public static ServiceResult<T> Fail(string errorCode, string message) =>
|
||
new() { Success = false, ErrorCode = errorCode, ErrorMessage = message };
|
||
}
|
||
```
|
||
|
||
### RedisKeys — all key names in one place
|
||
|
||
Every Redis key used across all services is defined as a constant here. This prevents
|
||
typos, name collisions between services, and makes key naming auditable at a glance.
|
||
|
||
```csharp
|
||
// src/SOR.Shared/Redis/RedisKeys.cs
|
||
namespace SOR.Shared.Redis;
|
||
|
||
public static class RedisKeys
|
||
{
|
||
// String.Format-style method: call Session("abc123") → "session:abc123"
|
||
// The 'static' modifier means no instance is needed to call these.
|
||
public static string Session(string token) => $"session:{token}";
|
||
public static string ActiveGame(string gameId) => $"game:active:{gameId}";
|
||
public static string LeaderboardRanked() => "leaderboard:ranked";
|
||
public static string FeatureFlag(string flag) => $"config:flag:{flag}";
|
||
public static string ClientPushChannel(string userId) => $"push:{userId}";
|
||
}
|
||
```
|
||
|
||
### NatsSubjects — all NATS subject names in one place
|
||
|
||
Same principle as RedisKeys. Centralizing subject names means a rename touches one file.
|
||
|
||
```csharp
|
||
// src/SOR.Shared/Nats/NatsSubjects.cs
|
||
namespace SOR.Shared.Nats;
|
||
|
||
public static class NatsSubjects
|
||
{
|
||
public const string GameEnded = "sor.game.ended";
|
||
public const string PurchaseCompleted = "sor.bazaar.purchase.completed";
|
||
public const string CardGranted = "sor.collection.card.granted";
|
||
public const string MatchRated = "sor.game.match.rated";
|
||
public const string PlayerBanned = "sor.admin.player.banned";
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 5. Protobuf Contracts — SOR.Shared.Proto
|
||
|
||
gRPC uses Protobuf (`.proto` files) as its interface definition language. The `.proto` files
|
||
define the message types and service methods. The `dotnet-grpc` tooling generates C# code
|
||
from them automatically on build — you never edit the generated files manually.
|
||
|
||
```
|
||
src/SOR.Shared.Proto/
|
||
├── SOR.Shared.Proto.csproj
|
||
│
|
||
└── Protos/
|
||
├── auth.proto # Auth service contract
|
||
├── game.proto # Game service contract
|
||
├── chat.proto # Chat service contract
|
||
├── collection.proto # Collection service contract
|
||
├── bazaar.proto # Bazaar service contract
|
||
├── leaderboard.proto # Leaderboard service contract
|
||
└── content.proto # Content service contract
|
||
```
|
||
|
||
### Example: auth.proto
|
||
|
||
```protobuf
|
||
// src/SOR.Shared.Proto/Protos/auth.proto
|
||
|
||
// proto3 is the current version of the Protobuf language.
|
||
syntax = "proto3";
|
||
|
||
// The C# namespace the generated code will live in.
|
||
option csharp_namespace = "SOR.Shared.Proto";
|
||
|
||
// The package prevents naming collisions with other .proto files.
|
||
package sor.auth;
|
||
|
||
// A 'message' is a structured data type — equivalent to a C# class with properties.
|
||
// Each field has a type, a name, and a field number (used in binary encoding — never change these).
|
||
message LoginRequest {
|
||
string email = 1;
|
||
string password = 2;
|
||
}
|
||
|
||
message LoginResponse {
|
||
bool success = 1;
|
||
string session_token = 2; // Only set on success
|
||
string error_code = 3; // Only set on failure
|
||
}
|
||
|
||
message ValidateTokenRequest {
|
||
string session_token = 1;
|
||
}
|
||
|
||
message ValidateTokenResponse {
|
||
bool valid = 1;
|
||
string user_id = 2;
|
||
string display_name = 3;
|
||
}
|
||
|
||
// A 'service' defines the RPC methods. The generated C# code creates a
|
||
// base class (AuthService.AuthServiceBase) that the handler inherits from.
|
||
service AuthService {
|
||
rpc Login(LoginRequest) returns (LoginResponse);
|
||
rpc ValidateToken(ValidateTokenRequest) returns (ValidateTokenResponse);
|
||
}
|
||
```
|
||
|
||
### SOR.Shared.Proto.csproj
|
||
|
||
```xml
|
||
<Project Sdk="Microsoft.NET.Sdk">
|
||
<PropertyGroup>
|
||
<AssemblyName>SOR.Shared.Proto</AssemblyName>
|
||
</PropertyGroup>
|
||
|
||
<ItemGroup>
|
||
<PackageReference Include="Grpc.AspNetCore" />
|
||
</ItemGroup>
|
||
|
||
<ItemGroup>
|
||
<!-- GrpcServices="Both" generates both client and server code from each .proto file.
|
||
Services that handle calls use the Server base class.
|
||
Services that call other services use the Client stub. -->
|
||
<Protobuf Include="Protos/*.proto" GrpcServices="Both" />
|
||
</ItemGroup>
|
||
</Project>
|
||
```
|
||
|
||
---
|
||
|
||
## 6. Multi-Service Runner — SOR.Host
|
||
|
||
`SOR.Host` is the deployable binary. It is the only executable project in the solution.
|
||
It reads the `ENABLED_SERVICES` environment variable and starts only the listed services.
|
||
|
||
This is how we run N services per box: set `ENABLED_SERVICES=auth,chat,collection` on a
|
||
VM and that VM runs exactly those three services in a single .NET process.
|
||
|
||
**Why a single process?** Within one process, services share memory for config, the DI
|
||
container, and connection pools. There is zero network overhead between co-located services
|
||
since gRPC calls between them go through localhost. Deploying fewer processes also means
|
||
fewer Kubernetes pods to manage on smaller infrastructure.
|
||
|
||
```csharp
|
||
// src/SOR.Host/Program.cs
|
||
|
||
// 'using' imports a namespace so its types can be used without the full namespace prefix.
|
||
// Normally you'd need to write 'SOR.Auth.ServiceRegistration.AddAuthService(...)' —
|
||
// the using directive means you can just call 'AddAuthService(...)'.
|
||
using SOR.Auth;
|
||
using SOR.Chat;
|
||
using SOR.Collection;
|
||
using SOR.Bazaar;
|
||
using SOR.Admin;
|
||
using SOR.Leaderboard;
|
||
using SOR.Content;
|
||
using SOR.Gateway;
|
||
using Serilog;
|
||
|
||
// Read which services this instance should run.
|
||
// Environment.GetEnvironmentVariable returns null if the variable isn't set,
|
||
// so ?? "all" is a fallback: if unset, run everything (useful for development).
|
||
var rawServices = Environment.GetEnvironmentVariable("ENABLED_SERVICES") ?? "all";
|
||
|
||
// Split "auth,chat,collection" into ["auth", "chat", "collection"].
|
||
// ToHashSet() for O(1) Contains() lookups.
|
||
var enabledServices = rawServices
|
||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||
|
||
bool IsEnabled(string name) =>
|
||
enabledServices.Contains("all") || enabledServices.Contains(name);
|
||
|
||
// WebApplication.CreateBuilder sets up the ASP.NET Core application builder.
|
||
// args are the command-line arguments passed at startup.
|
||
var builder = WebApplication.CreateBuilder(args);
|
||
|
||
// --- Logging ---
|
||
// Replace the default logger with Serilog (see §13 for details).
|
||
builder.Host.UseSerilog((context, config) =>
|
||
config.ReadFrom.Configuration(context.Configuration));
|
||
|
||
// --- Shared infrastructure: registered once, used by all enabled services ---
|
||
|
||
// AddStackExchangeRedisCache registers IConnectionMultiplexer (the Redis client)
|
||
// as a singleton — one shared connection for the whole process lifetime.
|
||
builder.Services.AddSingleton<IConnectionMultiplexer>(
|
||
ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("Redis")!));
|
||
|
||
// NATS connection registered as singleton.
|
||
builder.Services.AddNatsClient(opts =>
|
||
opts with { Url = builder.Configuration["Nats:Url"]! });
|
||
|
||
// --- Service registrations ---
|
||
// Each service registers its own DbContext, repositories, services, and handlers.
|
||
// Only services listed in ENABLED_SERVICES are registered.
|
||
|
||
if (IsEnabled("auth")) builder.Services.AddAuthService(builder.Configuration);
|
||
if (IsEnabled("chat")) builder.Services.AddChatService(builder.Configuration);
|
||
if (IsEnabled("collection")) builder.Services.AddCollectionService(builder.Configuration);
|
||
if (IsEnabled("bazaar")) builder.Services.AddBazaarService(builder.Configuration);
|
||
if (IsEnabled("admin")) builder.Services.AddAdminService(builder.Configuration);
|
||
if (IsEnabled("leaderboard")) builder.Services.AddLeaderboardService(builder.Configuration);
|
||
if (IsEnabled("content")) builder.Services.AddContentService(builder.Configuration);
|
||
if (IsEnabled("gateway")) builder.Services.AddGatewayService(builder.Configuration);
|
||
|
||
// Build the application from the configured builder.
|
||
var app = builder.Build();
|
||
|
||
// --- Middleware pipeline ---
|
||
// Middleware runs in the order it's added. Each piece can intercept a request,
|
||
// do something, and pass it to the next piece.
|
||
app.UseRouting();
|
||
app.UseAuthentication();
|
||
app.UseAuthorization();
|
||
|
||
// --- Route gRPC handlers ---
|
||
// MapGrpcService connects the URL route to the handler class.
|
||
// The handler class is only registered if the service is enabled.
|
||
if (IsEnabled("auth")) app.MapGrpcService<SOR.Auth.Handlers.AuthGrpcHandler>();
|
||
if (IsEnabled("chat")) app.MapGrpcService<SOR.Chat.Handlers.ChatGrpcHandler>();
|
||
if (IsEnabled("collection")) app.MapGrpcService<SOR.Collection.Handlers.CollectionGrpcHandler>();
|
||
if (IsEnabled("bazaar")) app.MapGrpcService<SOR.Bazaar.Handlers.BazaarGrpcHandler>();
|
||
if (IsEnabled("leaderboard")) app.MapGrpcService<SOR.Leaderboard.Handlers.LeaderboardGrpcHandler>();
|
||
if (IsEnabled("content")) app.MapGrpcService<SOR.Content.Handlers.ContentGrpcHandler>();
|
||
|
||
// Health check endpoint for Kubernetes liveness/readiness probes.
|
||
app.MapHealthChecks("/health");
|
||
|
||
// Start the application. This call blocks until the process is stopped.
|
||
await app.RunAsync();
|
||
```
|
||
|
||
### Deployment examples
|
||
|
||
```yaml
|
||
# Kubernetes deployment: Auth + Collection + Bazaar on one pod
|
||
env:
|
||
- name: ENABLED_SERVICES
|
||
value: "auth,collection,bazaar"
|
||
|
||
# Kubernetes deployment: Chat + Leaderboard on another pod
|
||
env:
|
||
- name: ENABLED_SERVICES
|
||
value: "chat,leaderboard"
|
||
|
||
# Development: run everything
|
||
env:
|
||
- name: ENABLED_SERVICES
|
||
value: "all"
|
||
```
|
||
|
||
---
|
||
|
||
## 7. Dependency Injection
|
||
|
||
.NET has a built-in dependency injection (DI) container. Understanding it is essential to
|
||
reading and writing code in this codebase.
|
||
|
||
### The concept
|
||
|
||
Instead of a class creating its own dependencies (`new AuthRepository()`), you declare what
|
||
you need in the constructor and the DI container creates and injects the right instance.
|
||
|
||
```csharp
|
||
// Without DI — bad: AuthService is tightly coupled to AuthRepository.
|
||
// You can't swap the repository for a mock in tests.
|
||
public class AuthService
|
||
{
|
||
private readonly AuthRepository _repo = new AuthRepository(); // hard dependency
|
||
}
|
||
|
||
// With DI — good: AuthService depends on the interface, not the implementation.
|
||
// In tests, you inject a mock. In production, you inject the real repository.
|
||
public class AuthService : IAuthService
|
||
{
|
||
private readonly IAuthRepository _repo;
|
||
|
||
// The DI container sees that AuthService needs IAuthRepository,
|
||
// looks up what was registered for that interface, creates it,
|
||
// and passes it here automatically.
|
||
public AuthService(IAuthRepository repo)
|
||
{
|
||
_repo = repo;
|
||
}
|
||
}
|
||
```
|
||
|
||
### Service lifetimes
|
||
|
||
When you register something in the DI container, you specify its lifetime:
|
||
|
||
| Lifetime | Meaning | Use for |
|
||
|---|---|---|
|
||
| `AddSingleton` | One instance for the entire process lifetime | Redis connection, NATS connection, config |
|
||
| `AddScoped` | One instance per request (HTTP request or gRPC call) | DbContext, repositories, services |
|
||
| `AddTransient` | New instance every time it's requested | Rarely used; lightweight stateless utilities |
|
||
|
||
**Rule**: DbContexts and repositories must always be `AddScoped`. Redis and NATS connections
|
||
must always be `AddSingleton`. Business logic services (`AddScoped` — they depend on scoped repositories).
|
||
|
||
### Injecting things
|
||
|
||
Once registered, anything can be injected into any constructor:
|
||
|
||
```csharp
|
||
// The DI container automatically provides all three of these.
|
||
// No 'new' calls anywhere in business logic.
|
||
public class AuthService : IAuthService
|
||
{
|
||
private readonly IAuthRepository _repo;
|
||
private readonly IConnectionMultiplexer _redis;
|
||
private readonly IOptions<AuthOptions> _options;
|
||
|
||
public AuthService(
|
||
IAuthRepository repo,
|
||
IConnectionMultiplexer redis,
|
||
IOptions<AuthOptions> options)
|
||
{
|
||
_repo = repo;
|
||
_redis = redis;
|
||
_options = options;
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 8. Configuration System
|
||
|
||
Configuration follows the standard .NET layered approach:
|
||
|
||
1. `appsettings.json` — base config checked into source control (no secrets)
|
||
2. `appsettings.{Environment}.json` — environment overrides (Development, Staging, Production)
|
||
3. Environment variables — override anything from the above files (used in Docker/K8s)
|
||
|
||
### appsettings.json structure
|
||
|
||
```json
|
||
{
|
||
"ConnectionStrings": {
|
||
"Auth": "Host=postgres;Database=sor_auth;Username=sor;Password=",
|
||
"Chat": "Host=postgres;Database=sor_chat;Username=sor;Password=",
|
||
"Redis": "redis:6379",
|
||
"ChatColdStorage": "server=mysql;database=sor_chat_archive;user=sor;password="
|
||
},
|
||
"Nats": {
|
||
"Url": "nats://nats:4222"
|
||
},
|
||
"Auth": {
|
||
"SessionTtlMinutes": 1440,
|
||
"MaxSessionsPerUser": 5
|
||
},
|
||
"Serilog": {
|
||
"MinimumLevel": "Information",
|
||
"WriteTo": [
|
||
{ "Name": "Console" }
|
||
]
|
||
}
|
||
}
|
||
```
|
||
|
||
### Strongly typed options classes
|
||
|
||
Instead of calling `configuration["Auth:SessionTtlMinutes"]` everywhere (string-based, no
|
||
validation, no autocomplete), bind config sections to a typed class:
|
||
|
||
```csharp
|
||
// src/SOR.Auth/AuthOptions.cs
|
||
namespace SOR.Auth;
|
||
|
||
// This class mirrors the structure of the "Auth" section in appsettings.json.
|
||
// Properties must match the key names exactly (case-insensitive by default).
|
||
public class AuthOptions
|
||
{
|
||
// DataAnnotations attributes validate the values at startup.
|
||
// If SessionTtlMinutes is 0, the app will throw before serving any requests.
|
||
[Range(1, int.MaxValue)]
|
||
public int SessionTtlMinutes { get; set; } = 1440;
|
||
|
||
[Range(1, 100)]
|
||
public int MaxSessionsPerUser { get; set; } = 5;
|
||
}
|
||
```
|
||
|
||
Registered in ServiceRegistration.cs:
|
||
```csharp
|
||
services.Configure<AuthOptions>(configuration.GetSection("Auth"));
|
||
```
|
||
|
||
Injected and used:
|
||
```csharp
|
||
public class AuthService : IAuthService
|
||
{
|
||
private readonly AuthOptions _options;
|
||
|
||
// IOptions<T> is the DI wrapper around a config section.
|
||
// Calling .Value gives you the typed AuthOptions instance.
|
||
public AuthService(IOptions<AuthOptions> options)
|
||
{
|
||
_options = options.Value;
|
||
}
|
||
|
||
public TimeSpan GetSessionTtl() =>
|
||
TimeSpan.FromMinutes(_options.SessionTtlMinutes);
|
||
}
|
||
```
|
||
|
||
### Environment variable overrides
|
||
|
||
.NET automatically maps environment variables with double underscores to nested config keys:
|
||
|
||
```bash
|
||
# Sets ConnectionStrings:Auth
|
||
ConnectionStrings__Auth="Host=prod-postgres;Database=sor_auth;Username=sor;Password=secret"
|
||
|
||
# Sets Auth:SessionTtlMinutes
|
||
Auth__SessionTtlMinutes=2880
|
||
```
|
||
|
||
In Kubernetes, secrets are injected as environment variables. The code never knows whether
|
||
config came from a file or an environment variable.
|
||
|
||
---
|
||
|
||
## 9. gRPC Handlers
|
||
|
||
A gRPC handler is the Layer 1 entry point for a service. It inherits from the base class
|
||
generated by the Protobuf tooling and delegates all logic to the service layer.
|
||
|
||
```csharp
|
||
// src/SOR.Auth/Handlers/AuthGrpcHandler.cs
|
||
namespace SOR.Auth.Handlers;
|
||
|
||
// The generated base class is AuthService.AuthServiceBase (from auth.proto).
|
||
// It contains abstract or virtual methods for each rpc defined in the proto file.
|
||
// We override those methods to provide our implementation.
|
||
//
|
||
// [GrpcService] is not needed here — gRPC in ASP.NET Core finds the handler
|
||
// automatically when it's registered via MapGrpcService<T> in Program.cs.
|
||
public sealed class AuthGrpcHandler : AuthService.AuthServiceBase
|
||
{
|
||
private readonly IAuthService _authService;
|
||
private readonly ILogger<AuthGrpcHandler> _logger;
|
||
|
||
// Constructor injection — the DI container provides these.
|
||
public AuthGrpcHandler(IAuthService authService, ILogger<AuthGrpcHandler> logger)
|
||
{
|
||
_authService = authService;
|
||
_logger = logger;
|
||
}
|
||
|
||
// Override the Login method defined in auth.proto.
|
||
//
|
||
// 'override' means we're replacing the base class's implementation.
|
||
// Task<T> is the C# async return type — 'async' + 'await' let us write
|
||
// async code that looks sequential without blocking threads.
|
||
// ServerCallContext carries metadata about the gRPC call (deadline, peer address, etc.).
|
||
public override async Task<LoginResponse> Login(
|
||
LoginRequest request,
|
||
ServerCallContext context)
|
||
{
|
||
// Validate inputs before calling business logic.
|
||
// Return early with an error response — no exception needed for expected failures.
|
||
if (string.IsNullOrWhiteSpace(request.Email) ||
|
||
string.IsNullOrWhiteSpace(request.Password))
|
||
{
|
||
return new LoginResponse
|
||
{
|
||
Success = false,
|
||
ErrorCode = "INVALID_INPUT"
|
||
};
|
||
}
|
||
|
||
// Delegate to the service layer. The handler never touches the database directly.
|
||
var result = await _authService.LoginAsync(request.Email, request.Password);
|
||
|
||
// Map ServiceResult<T> to the Protobuf response message.
|
||
if (!result.Success)
|
||
{
|
||
_logger.LogWarning("Login failed for {Email}: {ErrorCode}", request.Email, result.ErrorCode);
|
||
return new LoginResponse
|
||
{
|
||
Success = false,
|
||
ErrorCode = result.ErrorCode ?? "UNKNOWN_ERROR"
|
||
};
|
||
}
|
||
|
||
return new LoginResponse
|
||
{
|
||
Success = true,
|
||
SessionToken = result.Value!
|
||
};
|
||
}
|
||
|
||
public override async Task<ValidateTokenResponse> ValidateToken(
|
||
ValidateTokenRequest request,
|
||
ServerCallContext context)
|
||
{
|
||
var result = await _authService.ValidateTokenAsync(request.SessionToken);
|
||
|
||
if (!result.Success)
|
||
return new ValidateTokenResponse { Valid = false };
|
||
|
||
return new ValidateTokenResponse
|
||
{
|
||
Valid = true,
|
||
UserId = result.Value!.UserId,
|
||
DisplayName = result.Value.DisplayName
|
||
};
|
||
}
|
||
}
|
||
```
|
||
|
||
### Calling another service via gRPC (client side)
|
||
|
||
When a service needs to call another service synchronously, it uses the generated gRPC client stub.
|
||
|
||
```csharp
|
||
// In ServiceRegistration.cs for a service that needs to call Auth:
|
||
services.AddGrpcClient<AuthService.AuthServiceClient>(options =>
|
||
{
|
||
// The address of the Auth service — a Kubernetes service DNS name.
|
||
options.Address = new Uri(configuration["Services:Auth"]!);
|
||
});
|
||
|
||
// In a handler or service that calls Auth:
|
||
public class GatewayAuthValidator
|
||
{
|
||
private readonly AuthService.AuthServiceClient _authClient;
|
||
|
||
public GatewayAuthValidator(AuthService.AuthServiceClient authClient)
|
||
{
|
||
_authClient = authClient;
|
||
}
|
||
|
||
public async Task<bool> ValidateAsync(string token)
|
||
{
|
||
var response = await _authClient.ValidateTokenAsync(
|
||
new ValidateTokenRequest { SessionToken = token });
|
||
return response.Valid;
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 10. NATS Integration
|
||
|
||
NATS is used for async fan-out events. One service publishes; zero or more services subscribe.
|
||
Publishers and subscribers have no knowledge of each other.
|
||
|
||
### Publishing an event
|
||
|
||
```csharp
|
||
// src/SOR.Game/Services/GameService.cs (excerpt)
|
||
|
||
// INatsClient is the official NATS client interface — inject it from DI.
|
||
public class GameService : IGameService
|
||
{
|
||
private readonly INatsClient _nats;
|
||
|
||
public GameService(INatsClient nats) { _nats = nats; }
|
||
|
||
public async Task RecordMatchResultAsync(MatchResult result)
|
||
{
|
||
// ... persist result ...
|
||
|
||
// Publish an event to NATS. Any service subscribed to this subject
|
||
// will receive it independently. Game service doesn't care who listens.
|
||
//
|
||
// PublishAsync<T> serializes T to JSON (or Protobuf if configured) automatically.
|
||
await _nats.PublishAsync(NatsSubjects.GameEnded, new GameEndedEvent
|
||
{
|
||
GameId = result.GameId,
|
||
WinnerId = result.WinnerId,
|
||
LoserId = result.LoserId,
|
||
EndedAt = DateTimeOffset.UtcNow
|
||
});
|
||
}
|
||
}
|
||
```
|
||
|
||
### Subscribing to events
|
||
|
||
NATS subscribers are registered as `IHostedService` background workers — they run for the
|
||
entire lifetime of the process and receive events as they arrive.
|
||
|
||
```csharp
|
||
// src/SOR.Leaderboard/Subscribers/GameEndedSubscriber.cs
|
||
namespace SOR.Leaderboard.Subscribers;
|
||
|
||
// IHostedService is the .NET interface for background services.
|
||
// The framework starts it on app startup and stops it on shutdown.
|
||
public sealed class GameEndedSubscriber : IHostedService
|
||
{
|
||
private readonly INatsClient _nats;
|
||
private readonly IServiceScopeFactory _scopeFactory;
|
||
private readonly ILogger<GameEndedSubscriber> _logger;
|
||
|
||
// IServiceScopeFactory is needed because this is a Singleton (runs forever),
|
||
// but it needs to create Scoped services (like repositories) per message.
|
||
// Creating a scope per message ensures DbContext is not shared across messages.
|
||
public GameEndedSubscriber(
|
||
INatsClient nats,
|
||
IServiceScopeFactory scopeFactory,
|
||
ILogger<GameEndedSubscriber> logger)
|
||
{
|
||
_nats = nats;
|
||
_scopeFactory = scopeFactory;
|
||
_logger = logger;
|
||
}
|
||
|
||
// CancellationToken signals when the application is shutting down.
|
||
// We pass it through so async operations can cancel cleanly.
|
||
public async Task StartAsync(CancellationToken cancellationToken)
|
||
{
|
||
// SubscribeAsync returns an IAsyncEnumerable — an async stream of messages.
|
||
// 'await foreach' processes each message as it arrives without blocking.
|
||
await foreach (var msg in _nats.SubscribeAsync<GameEndedEvent>(
|
||
NatsSubjects.GameEnded, cancellationToken: cancellationToken))
|
||
{
|
||
if (msg.Data is null) continue;
|
||
|
||
try
|
||
{
|
||
// Create a fresh DI scope for each message so EF Core DbContext
|
||
// is properly disposed after handling each event.
|
||
await using var scope = _scopeFactory.CreateAsyncScope();
|
||
var service = scope.ServiceProvider.GetRequiredService<ILeaderboardService>();
|
||
await service.ProcessGameResultAsync(msg.Data);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
// Log and continue — a bad message must not crash the subscriber.
|
||
_logger.LogError(ex, "Failed to process GameEnded event {GameId}", msg.Data?.GameId);
|
||
}
|
||
}
|
||
}
|
||
|
||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||
}
|
||
```
|
||
|
||
Register the subscriber in ServiceRegistration.cs:
|
||
```csharp
|
||
// IHostedService registrations use AddHostedService<T>.
|
||
services.AddHostedService<GameEndedSubscriber>();
|
||
```
|
||
|
||
---
|
||
|
||
## 11. Redis Integration
|
||
|
||
Redis is used for session storage, client push delivery, live game state, leaderboard Sorted
|
||
Sets, and runtime feature flags.
|
||
|
||
### Registering the connection
|
||
|
||
Registered once in `Program.cs` as a Singleton — the connection multiplexer manages an
|
||
internal connection pool and is safe to share across the entire process.
|
||
|
||
```csharp
|
||
// Program.cs (already shown in §6)
|
||
builder.Services.AddSingleton<IConnectionMultiplexer>(
|
||
ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("Redis")!));
|
||
```
|
||
|
||
### Using Redis in a service
|
||
|
||
```csharp
|
||
// src/SOR.Auth/Services/AuthService.cs (excerpt)
|
||
public class AuthService : IAuthService
|
||
{
|
||
private readonly IDatabase _redis;
|
||
private readonly AuthOptions _options;
|
||
|
||
// IConnectionMultiplexer.GetDatabase() returns a lightweight IDatabase handle.
|
||
// It is safe to call GetDatabase() on every request — it does not create new connections.
|
||
public AuthService(IConnectionMultiplexer redis, IOptions<AuthOptions> options)
|
||
{
|
||
_redis = redis.GetDatabase();
|
||
_options = options.Value;
|
||
}
|
||
|
||
public async Task<string> CreateSessionAsync(string userId, string displayName)
|
||
{
|
||
// Guid.NewGuid() generates a cryptographically random 128-bit identifier.
|
||
// ToString("N") formats it as a 32-character hex string with no dashes.
|
||
var token = Guid.NewGuid().ToString("N");
|
||
var ttl = TimeSpan.FromMinutes(_options.SessionTtlMinutes);
|
||
|
||
// Serialize session data to JSON.
|
||
// System.Text.Json is the built-in .NET JSON library — fast and allocation-efficient.
|
||
var sessionJson = JsonSerializer.Serialize(new
|
||
{
|
||
UserId = userId,
|
||
DisplayName = displayName,
|
||
CreatedAt = DateTimeOffset.UtcNow
|
||
});
|
||
|
||
// SET key value EX seconds — sets the key and its TTL atomically.
|
||
// RedisKeys.Session(token) returns the namespaced key string "session:{token}".
|
||
await _redis.StringSetAsync(
|
||
RedisKeys.Session(token),
|
||
sessionJson,
|
||
expiry: ttl);
|
||
|
||
return token;
|
||
}
|
||
|
||
public async Task RevokeSessionAsync(string token)
|
||
{
|
||
// DEL key — removes the key. If the key doesn't exist, this is a no-op.
|
||
await _redis.KeyDeleteAsync(RedisKeys.Session(token));
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 12. Database — EF Core + PostgreSQL
|
||
|
||
Entity Framework Core (EF Core) is the ORM. It lets you define your database schema as C#
|
||
classes and query the database using LINQ (Language Integrated Query) instead of raw SQL.
|
||
EF Core translates LINQ queries into optimized SQL at runtime.
|
||
|
||
### DbContext
|
||
|
||
Each service has its own DbContext. A DbContext represents a database connection session and
|
||
tracks all changes to entities loaded through it.
|
||
|
||
```csharp
|
||
// src/SOR.Auth/Data/AuthDbContext.cs
|
||
namespace SOR.Auth.Data;
|
||
|
||
// DbContext is the EF Core base class. We inherit from it and add our DbSets.
|
||
public class AuthDbContext : DbContext
|
||
{
|
||
// Constructor: passes options to the base class.
|
||
// Options include the connection string — provided by DI from config.
|
||
public AuthDbContext(DbContextOptions<AuthDbContext> options) : base(options) { }
|
||
|
||
// DbSet<T> represents a database table. Querying _users runs a SELECT;
|
||
// adding to it and calling SaveChanges() runs an INSERT.
|
||
public DbSet<UserEntity> Users => Set<UserEntity>();
|
||
public DbSet<OAuthLinkEntity> OAuthLinks => Set<OAuthLinkEntity>();
|
||
|
||
// OnModelCreating configures the schema (table names, indexes, constraints).
|
||
// This runs once when EF Core builds its internal model of the schema.
|
||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||
{
|
||
// Configure the Users table.
|
||
modelBuilder.Entity<UserEntity>(entity =>
|
||
{
|
||
// Explicit table name (default would be "Users" — being explicit is safer).
|
||
entity.ToTable("users", schema: "auth");
|
||
|
||
// Primary key. EF Core auto-detects properties named "Id" but being
|
||
// explicit documents intent.
|
||
entity.HasKey(u => u.Id);
|
||
|
||
// Index for fast email lookups. IsUnique enforces the DB constraint.
|
||
entity.HasIndex(u => u.Email).IsUnique();
|
||
|
||
// Column type: varchar with a max length (enforced at DB level).
|
||
entity.Property(u => u.Email).HasMaxLength(256).IsRequired();
|
||
entity.Property(u => u.DisplayName).HasMaxLength(64).IsRequired();
|
||
});
|
||
}
|
||
}
|
||
```
|
||
|
||
### Entity classes
|
||
|
||
Entities are plain C# classes that map to database rows. They live in the service's `Data/`
|
||
or `Models/` folder. They are the internal database representation — not the API response.
|
||
|
||
```csharp
|
||
// src/SOR.Auth/Models/UserEntity.cs
|
||
namespace SOR.Auth.Models;
|
||
|
||
public class UserEntity
|
||
{
|
||
public Guid Id { get; set; }
|
||
public required string Email { get; set; }
|
||
public required string DisplayName { get; set; }
|
||
public required string PasswordHash { get; set; }
|
||
public DateTimeOffset CreatedAt { get; set; }
|
||
public bool IsBanned { get; set; }
|
||
}
|
||
```
|
||
|
||
### Repository implementation
|
||
|
||
```csharp
|
||
// src/SOR.Auth/Repositories/AuthRepository.cs
|
||
namespace SOR.Auth.Repositories;
|
||
|
||
public class AuthRepository : IAuthRepository
|
||
{
|
||
private readonly AuthDbContext _db;
|
||
|
||
public AuthRepository(AuthDbContext db)
|
||
{
|
||
_db = db;
|
||
}
|
||
|
||
// FirstOrDefaultAsync returns the first matching row, or null if none.
|
||
// The lambda expression 'u => u.Email == email' is the WHERE clause.
|
||
// 'await' pauses this method until the database responds, without blocking the thread.
|
||
public async Task<UserEntity?> FindByEmailAsync(string email, CancellationToken ct = default)
|
||
{
|
||
return await _db.Users
|
||
.FirstOrDefaultAsync(u => u.Email == email, ct);
|
||
}
|
||
|
||
public async Task<UserEntity> CreateAsync(UserEntity user, CancellationToken ct = default)
|
||
{
|
||
// Add the entity to the change tracker.
|
||
_db.Users.Add(user);
|
||
|
||
// SaveChangesAsync flushes all pending changes to the database in one transaction.
|
||
await _db.SaveChangesAsync(ct);
|
||
|
||
return user;
|
||
}
|
||
}
|
||
```
|
||
|
||
### Migrations
|
||
|
||
Migrations are auto-generated files that track schema changes over time. When you change an
|
||
entity class (add a column, change a type), you generate a new migration and apply it.
|
||
|
||
```bash
|
||
# Generate a migration (run from Server/ directory).
|
||
# <ServiceName>Initial is just a descriptive name for the migration.
|
||
dotnet ef migrations add AuthInitial \
|
||
--project src/SOR.Auth \
|
||
--startup-project src/SOR.Host \
|
||
--context AuthDbContext
|
||
|
||
# Apply all pending migrations to the database.
|
||
dotnet ef database update \
|
||
--project src/SOR.Auth \
|
||
--startup-project src/SOR.Host \
|
||
--context AuthDbContext
|
||
```
|
||
|
||
In production, migrations are applied automatically on startup:
|
||
|
||
```csharp
|
||
// ServiceRegistration.cs — after the DbContext is registered:
|
||
services.AddHostedService<DatabaseMigratorHostedService<AuthDbContext>>();
|
||
```
|
||
|
||
---
|
||
|
||
## 13. Logging — Serilog
|
||
|
||
All logging uses Serilog with structured log output. Every log entry is a structured event,
|
||
not just a string — this allows log aggregators (Seq, Grafana Loki, etc.) to query and filter
|
||
on field values.
|
||
|
||
### Log levels
|
||
|
||
| Level | When to use |
|
||
|---|---|
|
||
| `LogTrace` | Extremely verbose — step-by-step flow. Disabled in production. |
|
||
| `LogDebug` | Developer details — query parameters, intermediate values. Disabled in production. |
|
||
| `LogInformation` | Normal operational events — service started, login succeeded, game created. |
|
||
| `LogWarning` | Something unexpected but recoverable — login failed, retrying a DB query. |
|
||
| `LogError` | An operation failed — unhandled exception, external call failed. |
|
||
| `LogCritical` | System is broken — database unreachable on startup, OOM. |
|
||
|
||
### Usage
|
||
|
||
```csharp
|
||
// Always inject ILogger<T> where T is the class using it.
|
||
// The T type name appears in log output so you know where the log came from.
|
||
private readonly ILogger<AuthService> _logger;
|
||
|
||
// Structured logging: use message templates with {Property} placeholders.
|
||
// Serilog captures the actual value as a named property — not just a string.
|
||
// This means you can search logs for "UserId = abc123" later.
|
||
_logger.LogInformation("User {UserId} logged in from {IpAddress}", userId, ipAddress);
|
||
|
||
// Log exceptions: pass the exception as the first argument.
|
||
// Serilog captures the full stack trace as a structured field.
|
||
try { ... }
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "Login failed for {Email}", email);
|
||
throw; // Re-throw after logging if the caller needs to handle it.
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 14. Error Handling
|
||
|
||
### Expected failures: ServiceResult
|
||
|
||
Expected failures (user not found, invalid password, deck too large) are returned as
|
||
`ServiceResult.Fail(...)`. No exception is thrown. The caller checks `result.Success` and
|
||
maps to an appropriate response.
|
||
|
||
```csharp
|
||
public async Task<ServiceResult<string>> LoginAsync(string email, string password)
|
||
{
|
||
var user = await _repo.FindByEmailAsync(email);
|
||
|
||
// Expected failure — return a result, don't throw.
|
||
if (user is null)
|
||
return ServiceResult<string>.Fail("USER_NOT_FOUND", "Invalid credentials.");
|
||
|
||
if (!PasswordHasher.Verify(password, user.PasswordHash))
|
||
return ServiceResult<string>.Fail("INVALID_PASSWORD", "Invalid credentials.");
|
||
|
||
if (user.IsBanned)
|
||
return ServiceResult<string>.Fail("ACCOUNT_BANNED", "This account has been banned.");
|
||
|
||
var token = await CreateSessionAsync(user.Id.ToString(), user.DisplayName);
|
||
return ServiceResult<string>.Ok(token);
|
||
}
|
||
```
|
||
|
||
### Unexpected failures: exceptions
|
||
|
||
Unexpected failures (DB connection lost, OOM, null where impossible) are allowed to throw.
|
||
A global exception handler in ASP.NET Core catches them, logs them, and returns a generic
|
||
5xx response to the caller.
|
||
|
||
```csharp
|
||
// Program.cs — catch-all for unhandled exceptions in the middleware pipeline.
|
||
app.UseExceptionHandler(exceptionHandlerApp =>
|
||
exceptionHandlerApp.Run(async context =>
|
||
{
|
||
var feature = context.Features.Get<IExceptionHandlerFeature>();
|
||
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
|
||
logger.LogError(feature?.Error, "Unhandled exception on {Path}", context.Request.Path);
|
||
context.Response.StatusCode = 500;
|
||
}));
|
||
```
|
||
|
||
### Never swallow exceptions silently
|
||
|
||
```csharp
|
||
// BAD: The exception disappears. The caller thinks nothing went wrong.
|
||
try { await _repo.SaveAsync(entity); }
|
||
catch (Exception) { }
|
||
|
||
// GOOD: Log and re-throw, or return a failure result.
|
||
try { await _repo.SaveAsync(entity); }
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "Failed to save entity {Id}", entity.Id);
|
||
throw;
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 15. Health Checks
|
||
|
||
Every running instance exposes `/health` for Kubernetes liveness and readiness probes.
|
||
Health checks verify that the service's critical dependencies (database, Redis) are reachable.
|
||
|
||
```csharp
|
||
// ServiceRegistration.cs — register health checks alongside services.
|
||
services.AddHealthChecks()
|
||
.AddNpgSql(configuration.GetConnectionString("Auth")!, name: "auth-db")
|
||
.AddRedis(configuration.GetConnectionString("Redis")!, name: "redis");
|
||
|
||
// Program.cs — expose the endpoint (already shown in §6).
|
||
app.MapHealthChecks("/health");
|
||
```
|
||
|
||
---
|
||
|
||
## 16. Testing Patterns
|
||
|
||
### Unit tests
|
||
|
||
Unit tests test a single class in isolation. All dependencies are replaced with mocks.
|
||
No database, no Redis, no network — tests run in milliseconds.
|
||
|
||
```csharp
|
||
// tests/SOR.Auth.Tests/AuthServiceTests.cs
|
||
namespace SOR.Auth.Tests;
|
||
|
||
// [Fact] marks a test method. xUnit discovers and runs all methods marked with [Fact].
|
||
public class AuthServiceTests
|
||
{
|
||
// Moq: create a mock implementation of the interface.
|
||
// The mock records calls made to it and can be configured to return specific values.
|
||
private readonly Mock<IAuthRepository> _repoMock = new();
|
||
private readonly Mock<IConnectionMultiplexer> _redisMock = new();
|
||
private readonly IAuthService _sut; // "sut" = System Under Test — common convention.
|
||
|
||
public AuthServiceTests()
|
||
{
|
||
var options = Options.Create(new AuthOptions { SessionTtlMinutes = 60 });
|
||
_sut = new AuthService(_repoMock.Object, _redisMock.Object, options);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Login_WithValidCredentials_ReturnsSuccessResult()
|
||
{
|
||
// Arrange: configure the mock to return a specific user when queried.
|
||
_repoMock
|
||
.Setup(r => r.FindByEmailAsync("test@example.com", default))
|
||
.ReturnsAsync(new UserEntity
|
||
{
|
||
Id = Guid.NewGuid(),
|
||
Email = "test@example.com",
|
||
DisplayName = "TestUser",
|
||
PasswordHash = PasswordHasher.Hash("correct-password"),
|
||
CreatedAt = DateTimeOffset.UtcNow
|
||
});
|
||
|
||
// Act: call the method being tested.
|
||
var result = await _sut.LoginAsync("test@example.com", "correct-password");
|
||
|
||
// Assert: verify the result. FluentAssertions provides readable assertions.
|
||
result.Success.Should().BeTrue();
|
||
result.Value.Should().NotBeNullOrEmpty();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Login_WithWrongPassword_ReturnsFailResult()
|
||
{
|
||
_repoMock
|
||
.Setup(r => r.FindByEmailAsync("test@example.com", default))
|
||
.ReturnsAsync(new UserEntity
|
||
{
|
||
Id = Guid.NewGuid(),
|
||
Email = "test@example.com",
|
||
DisplayName = "TestUser",
|
||
PasswordHash = PasswordHasher.Hash("correct-password"),
|
||
CreatedAt = DateTimeOffset.UtcNow
|
||
});
|
||
|
||
var result = await _sut.LoginAsync("test@example.com", "wrong-password");
|
||
|
||
result.Success.Should().BeFalse();
|
||
result.ErrorCode.Should().Be("INVALID_PASSWORD");
|
||
}
|
||
}
|
||
```
|
||
|
||
### Integration tests
|
||
|
||
Integration tests spin up a real application with a real database (test-specific). Used to test
|
||
the full stack — handler → service → repository → database — without mocks.
|
||
|
||
```csharp
|
||
// tests/SOR.Auth.Tests/AuthIntegrationTests.cs
|
||
|
||
// WebApplicationFactory<T> starts the real app in-memory for testing.
|
||
// T is the entry point — usually Program.cs is referenced via a partial class.
|
||
public class AuthIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
|
||
{
|
||
private readonly WebApplicationFactory<Program> _factory;
|
||
|
||
public AuthIntegrationTests(WebApplicationFactory<Program> factory)
|
||
{
|
||
_factory = factory.WithWebHostBuilder(builder =>
|
||
{
|
||
builder.ConfigureAppConfiguration((_, config) =>
|
||
{
|
||
// Override connection strings to point at a test database.
|
||
config.AddInMemoryCollection(new Dictionary<string, string?>
|
||
{
|
||
["ConnectionStrings:Auth"] = "Host=localhost;Database=sor_auth_test;...",
|
||
["ENABLED_SERVICES"] = "auth"
|
||
});
|
||
});
|
||
});
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Login_ValidUser_ReturnsToken()
|
||
{
|
||
// Use the generated gRPC client against the in-memory server.
|
||
var client = new AuthService.AuthServiceClient(
|
||
GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions
|
||
{
|
||
HttpClient = _factory.CreateClient()
|
||
}));
|
||
|
||
var response = await client.LoginAsync(new LoginRequest
|
||
{
|
||
Email = "seed@example.com",
|
||
Password = "testpassword"
|
||
});
|
||
|
||
response.Success.Should().BeTrue();
|
||
response.SessionToken.Should().NotBeEmpty();
|
||
}
|
||
}
|
||
```
|
||
|
||
### Test file naming conventions
|
||
|
||
| File | What it tests |
|
||
|---|---|
|
||
| `{Class}Tests.cs` | Unit tests for a single class |
|
||
| `{Service}IntegrationTests.cs` | Integration tests for a full service stack |
|
||
| `{Handler}HandlerTests.cs` | Tests for a gRPC handler (mock the service layer) |
|
||
|
||
---
|
||
|
||
## 17. Naming Conventions
|
||
|
||
C# uses different casing conventions for different kinds of identifiers. These are enforced
|
||
by the compiler for some cases and by team convention for others.
|
||
|
||
| Kind | Convention | Example |
|
||
|---|---|---|
|
||
| Namespace | PascalCase | `SOR.Auth.Services` |
|
||
| Class / Interface / Record | PascalCase | `AuthService`, `IAuthRepository` |
|
||
| Method | PascalCase | `LoginAsync`, `FindByEmailAsync` |
|
||
| Property | PascalCase | `SessionTtlMinutes`, `ErrorCode` |
|
||
| Constant (`const`) | PascalCase | `NatsSubjects.GameEnded` |
|
||
| Private field | `_camelCase` | `_repo`, `_logger` |
|
||
| Local variable | camelCase | `sessionToken`, `userId` |
|
||
| Parameter | camelCase | `email`, `password` |
|
||
| Interface | `I` prefix | `IAuthService`, `IAuthRepository` |
|
||
| Async method | `Async` suffix | `LoginAsync`, `SaveChangesAsync` |
|
||
| Generic type parameter | `T` prefix | `ServiceResult<T>`, `DbSet<TEntity>` |
|
||
|
||
### File naming
|
||
|
||
- One class per file.
|
||
- File name must match class name exactly: `AuthService.cs` contains `class AuthService`.
|
||
- Interface files: `IAuthService.cs` contains `interface IAuthService`.
|
||
|
||
### Project naming
|
||
|
||
All projects in the solution are prefixed with `SOR.`:
|
||
- `SOR.Host` — multi-service runner
|
||
- `SOR.Shared` — shared library
|
||
- `SOR.Auth` — Auth service module
|
||
- `SOR.Auth.Tests` — tests for Auth
|
||
|
||
---
|
||
|
||
## 18. Hard Rules
|
||
|
||
These rules are non-negotiable. Every code review checks for violations.
|
||
|
||
1. **No cross-service database access.** Each service's DbContext connects to its own schema.
|
||
Service A never queries Service B's schema. Inter-service data goes through gRPC or NATS.
|
||
|
||
2. **No business logic in handlers.** Handlers receive, validate inputs, call the service,
|
||
and return. All business logic lives in the service layer.
|
||
|
||
3. **No database access in services.** Services call repositories. They never instantiate
|
||
DbContext directly or run SQL.
|
||
|
||
4. **No `new` for injected dependencies.** If something is registered in the DI container,
|
||
it is injected through the constructor — never created with `new` inside a class.
|
||
|
||
5. **All async methods must be awaited.** Never call an async method and discard the `Task`.
|
||
This hides exceptions and can cause subtle race conditions.
|
||
|
||
6. **All Redis key names go through `RedisKeys`.** No inline string literals like `"session:" + token`.
|
||
|
||
7. **All NATS subject names go through `NatsSubjects`.** No inline string literals.
|
||
|
||
8. **No shared mutable state between services.** Services share DI infrastructure (Redis,
|
||
NATS connections) but never share in-memory objects or static mutable state.
|
||
|
||
9. **Every service module exposes exactly one public entry point: `Add{Name}Service`.** All
|
||
other types in the module are `internal` unless explicitly needed by other assemblies.
|
||
|
||
10. **No catching `Exception` without re-throwing or returning a result.** Swallowing exceptions
|
||
silently is forbidden.
|
||
|
||
11. **Log at the correct level.** Never log expected failures at `Error`. Never flood `Information`
|
||
with per-message trace data in production.
|
||
|
||
12. **Entities are internal to their service.** `UserEntity` from SOR.Auth is never referenced
|
||
in SOR.Gateway. Share data through Protobuf messages or strongly-typed C# DTOs in SOR.Shared.
|
||
|
||
---
|
||
|
||
## File: Server/docs/SOR.Ai-Architecture-Plan.md
|
||
|
||
# SOR.Ai — AI Player Architecture Plan
|
||
|
||
## Overview
|
||
|
||
`SOR.Ai` is a new server-side project that provides AI-controlled players for free-play (custom lobby) games.
|
||
Players can spin up a lobby, add 1–N AI opponents, choose difficulty, and play immediately — no wait queue needed.
|
||
|
||
The AI integrates as **"just another player"** from the perspective of all existing infrastructure: it holds a
|
||
virtual account, joins lobbies via the existing `CustomLobby` system, and submits game actions through the same
|
||
`IMessageHandler` pipeline that human clients use. No changes to `GameEngine`, protocol contracts, or client code
|
||
are required.
|
||
|
||
---
|
||
|
||
## Table of Contents
|
||
|
||
1. [Project Structure](#1-project-structure)
|
||
2. [Integration Points](#2-integration-points)
|
||
3. [AI Account Model](#3-ai-account-model)
|
||
4. [Game Flow — How AI Joins & Plays](#4-game-flow)
|
||
5. [Decision Engine Architecture](#5-decision-engine-architecture)
|
||
6. [Difficulty System](#6-difficulty-system)
|
||
7. [Training & Improvement Strategy](#7-training--improvement-strategy)
|
||
8. [Deck Composition for AI](#8-deck-composition-for-ai)
|
||
9. [Multi-Player & Team AI](#9-multi-player--team-ai)
|
||
10. [New Message Types](#10-new-message-types)
|
||
11. [Database Schema Additions](#11-database-schema-additions)
|
||
12. [Implementation Phases](#12-implementation-phases)
|
||
|
||
---
|
||
|
||
## 1. Project Structure
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
├── SOR.Ai.csproj
|
||
├── ServiceRegistration.cs — DI wiring, registers all AI services
|
||
│
|
||
├── Core/
|
||
│ ├── AiPlayer.cs — Runtime state for one AI-controlled seat
|
||
│ ├── AiPlayerSession.cs — Binds an AiPlayer to a GameSession
|
||
│ ├── AiPlayerSessionManager.cs — Manages all active AI sessions (keyed by sessionId)
|
||
│ └── AiTurnContext.cs — Snapshot of GameState from an AI's perspective
|
||
│
|
||
├── Engine/
|
||
│ ├── IAiDecisionEngine.cs — Interface: next action given AiTurnContext
|
||
│ ├── HeuristicDecisionEngine.cs — Rule-based engine (Difficulty 1–5)
|
||
│ ├── MonteCarloEngine.cs — MCTS-based engine (Difficulty 6–8)
|
||
│ ├── NeuralDecisionEngine.cs — ML model wrapper (Difficulty 9–10, future)
|
||
│ └── RandomDecisionEngine.cs — Purely random (used for sanity testing / Novice)
|
||
│
|
||
├── Heuristics/
|
||
│ ├── ScoringFunctions.cs — Board evaluation: material, position, affinity control
|
||
│ ├── ActionCandidateGenerator.cs — Enumerate all legal moves from a GameState
|
||
│ ├── ThreatDetector.cs — Identifies units threatening ArchSpirit
|
||
│ ├── ResourceOptimizer.cs — SP/ST/MP expenditure strategies
|
||
│ └── AffinityController.cs — Tile control and Terramorpha placement logic
|
||
│
|
||
├── MCTS/
|
||
│ ├── MctsTree.cs — Monte Carlo Tree Search node + expansion
|
||
│ ├── MctsSimulator.cs — Random playout from a given GameState
|
||
│ └── MctsEvaluator.cs — Leaf-node evaluation function
|
||
│
|
||
├── Training/
|
||
│ ├── SelfPlayOrchestrator.cs — Runs batches of AI-vs-AI games for data generation
|
||
│ ├── GameReplayExporter.cs — Converts GameActionLog rows → training samples
|
||
│ ├── FeatureExtractor.cs — Converts GameState → numeric feature vector
|
||
│ └── TrainingDataWriter.cs — Writes JSONL / Parquet training files
|
||
│
|
||
├── Lobby/
|
||
│ ├── AiLobbyService.cs — Handles "add AI to lobby" requests
|
||
│ └── AiSlotAssigner.cs — Assigns AI accounts to open seats
|
||
│
|
||
└── Handlers/
|
||
├── GameAddAiHandler.cs — Handles "game.ai.add" message from host
|
||
├── GameRemoveAiHandler.cs — Handles "game.ai.remove" message from host
|
||
└── GameAiConfigureHandler.cs — Handles "game.ai.configure" (difficulty, strategy)
|
||
```
|
||
|
||
**Project file** (`SOR.Ai.csproj`):
|
||
|
||
```xml
|
||
<Project Sdk="Microsoft.NET.Sdk">
|
||
<PropertyGroup>
|
||
<TargetFramework>net8.0</TargetFramework>
|
||
</PropertyGroup>
|
||
|
||
<ItemGroup>
|
||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||
</ItemGroup>
|
||
|
||
<ItemGroup>
|
||
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
|
||
<ProjectReference Include="..\SOR.Game\SOR.Game.csproj" />
|
||
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
|
||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||
</ItemGroup>
|
||
</Project>
|
||
```
|
||
|
||
---
|
||
|
||
## 2. Integration Points
|
||
|
||
### 2.1 How AI Submits Game Actions
|
||
|
||
The AI does **not** open a WebSocket. Instead, `AiPlayerSessionManager` — a hosted background service —
|
||
calls game handler methods **directly** (bypassing the transport layer):
|
||
|
||
```csharp
|
||
// Conceptual: AI calling GameDrawHandler directly
|
||
var fakeConn = new AiAuthenticatedConnection(aiAccountId, sessionId);
|
||
var fakeMsg = new AiClientMessage("game.draw", seq: 0, payload: Array.Empty<byte>());
|
||
await drawHandler.HandleAsync(fakeMsg, fakeConn, ct);
|
||
```
|
||
|
||
`AiAuthenticatedConnection` implements `IAuthenticatedConnection` with the AI's virtual account ID.
|
||
`AiClientMessage` implements `IClientMessage` with the given message type and payload.
|
||
|
||
This means **the AI goes through the full handler pipeline** — transaction locking, state persistence,
|
||
push to human players — with no special-casing anywhere in the existing code.
|
||
|
||
### 2.2 Receiving State Updates
|
||
|
||
Rather than subscribing to Redis push channels, `AiPlayerSessionManager` reacts to its own action
|
||
completing. After the human player's turn ends (`game.end_turn` message is processed and the game's
|
||
`ActivePlayerAccountId` flips to an AI account), the `GameEndTurnHandler` raises an internal
|
||
`AiTurnStartedEvent` via NATS or an in-process `IEventBus`. `AiPlayerSessionManager` subscribes and
|
||
schedules the AI's turn.
|
||
|
||
```
|
||
Human: game.end_turn
|
||
→ GameEndTurnHandler runs, advances turn to AI seat
|
||
→ Publishes AiTurnStartedEvent { SessionId, AiAccountId }
|
||
→ AiPlayerSessionManager.OnAiTurnStarted fires
|
||
→ Loads GameState from session
|
||
→ AiDecisionEngine.ComputeTurn(state, difficulty, aiAccountId)
|
||
→ Submits sequence of game actions with configurable delay
|
||
→ Calls game.end_turn on behalf of AI
|
||
```
|
||
|
||
### 2.3 Turn Delay (Human Feel)
|
||
|
||
Raw AI decisions are instant. A delay is introduced to make the AI feel natural:
|
||
|
||
- **Simulated think time**: 800ms–3s before each discrete action (drawn from a configured range per difficulty)
|
||
- **Action pacing**: individual actions (play card, move, attack) are submitted 400ms–1.2s apart
|
||
- **These are configurable via `AiDifficultyProfile`** (see §6)
|
||
|
||
---
|
||
|
||
## 3. AI Account Model
|
||
|
||
Each AI "player" is backed by a real `Account` row in the database. A seed migration creates a set of
|
||
canonical AI accounts that are reused across games.
|
||
|
||
### 3.1 AI Account DB Record
|
||
|
||
| Field | Value |
|
||
|---|---|
|
||
| `Id` | deterministic GUID per difficulty tier (e.g. `ai-novice-001`) |
|
||
| `Username` | "Novice AI", "Challenger AI", "Grandmaster AI", etc. |
|
||
| `IsAi` | `true` (new boolean column on Account entity) |
|
||
| `AiDifficulty` | 1–10 |
|
||
| `AiStrategy` | "Aggressive", "Control", "Balanced", "Ramp" |
|
||
| `AvatarUrl` | art asset per strategy archetype |
|
||
|
||
`IsAi = true` accounts:
|
||
- Cannot be ranked-matched against (MatchmakerService excludes them)
|
||
- Are not shown in leaderboards
|
||
- Have their own pre-built decks (see §8)
|
||
- Have ELO tracked separately in `AiEloRecord` table (used for tuning, not displayed)
|
||
|
||
### 3.2 Pre-Built AI Accounts
|
||
|
||
A seed creates accounts for every combination of `(difficulty 1–10) × (strategy archetype)`:
|
||
|
||
```
|
||
ai-novice-aggressive Difficulty 1, Aggressive
|
||
ai-novice-control Difficulty 1, Control
|
||
ai-easy-balanced Difficulty 2, Balanced
|
||
...
|
||
ai-grandmaster-control Difficulty 10, Control
|
||
```
|
||
|
||
When a host adds an AI to a lobby, the client specifies `{ difficulty, strategy }`. The server
|
||
looks up the matching pre-seeded account and inserts it into the `CustomLobby.AdditionalPlayersJson`
|
||
(or `GuestAccountId` for the second seat in a 1v1).
|
||
|
||
---
|
||
|
||
## 4. Game Flow
|
||
|
||
### 4.1 Host Adds AI to a Custom Lobby
|
||
|
||
```
|
||
Host (client)
|
||
→ sends: game.ai.add { lobbyId, difficulty: 3, strategy: "Balanced" }
|
||
|
||
GameAddAiHandler
|
||
→ Validates: only host can add AI
|
||
→ Validates: lobby must be Open or not Full
|
||
→ AiSlotAssigner.Assign(lobbyId, difficulty, strategy)
|
||
→ Looks up matching AI account (e.g. ai-easy-balanced)
|
||
→ Inserts AI account into AdditionalPlayersJson or GuestAccountId
|
||
→ AI seat is marked IsAiControlled = true in lobby data
|
||
→ Pushes CustomLobbyUpdatedPush to all lobby members
|
||
→ AI seat appears in lobby as a named player with AI badge
|
||
```
|
||
|
||
Multiple AIs are supported by calling `game.ai.add` repeatedly (up to `MaxPlayers - 1`).
|
||
|
||
### 4.2 Lobby Ready → Game Start
|
||
|
||
When the host marks ready and the game starts (existing `GameLobbyReadyHandler`):
|
||
|
||
1. `GameSession` is created with AI accounts in their seats (no change to existing code).
|
||
2. `AiPlayerSessionManager.OnGameSessionCreated` is called.
|
||
3. Manager creates an `AiPlayerSession` for each AI seat in that session.
|
||
4. AI seats automatically send `game.ready` after a short delay so the game can begin even if AI is the only non-human.
|
||
|
||
### 4.3 AI Turn Execution
|
||
|
||
```
|
||
AiPlayerSession.ExecuteTurnAsync(state, difficulty, strategy, ct):
|
||
|
||
1. AiTurnContext ctx = BuildContext(state, aiAccountId)
|
||
2. AiAction[] actions = decisionEngine.ComputeTurn(ctx)
|
||
// actions is an ordered list of: draw, play_card, move, attack, end_turn, etc.
|
||
3. For each action in actions:
|
||
a. await Task.Delay(ThinkTime(difficulty)) // simulated delay
|
||
b. Serialize action to IClientMessage payload
|
||
c. Call appropriate handler directly
|
||
d. If handler returns error (e.g. game state changed mid-turn), re-evaluate
|
||
4. Finally: call GameEndTurnHandler
|
||
```
|
||
|
||
### 4.4 AI in Multi-Player / FFA
|
||
|
||
Each AI account is managed as a separate `AiPlayerSession`. Sessions are independent.
|
||
When it is AI-seat-3's turn, only AI-seat-3's session fires. Team play AIs do not coordinate
|
||
(in Phase 1); coordinated team AI is a future enhancement.
|
||
|
||
---
|
||
|
||
## 5. Decision Engine Architecture
|
||
|
||
### 5.1 Interface
|
||
|
||
```csharp
|
||
public interface IAiDecisionEngine
|
||
{
|
||
/// <summary>
|
||
/// Compute the full sequence of actions the AI will take this turn.
|
||
/// Returns actions in submission order; the caller is responsible for delays and submission.
|
||
/// </summary>
|
||
IReadOnlyList<AiAction> ComputeTurn(AiTurnContext ctx);
|
||
}
|
||
|
||
public abstract record AiAction;
|
||
public record AiDrawAction : AiAction;
|
||
public record AiPlayCardAction(string CardInstanceId, Coord TargetTile,
|
||
IReadOnlyList<string> CardTargets) : AiAction;
|
||
public record AiMoveAction(string UnitInstanceId, Coord TargetPosition) : AiAction;
|
||
public record AiAttackAction(string AttackerInstanceId, string TargetInstanceId) : AiAction;
|
||
public record AiActivateAbilityAction(string SourceId, int AbilityIndex,
|
||
IReadOnlyList<AiAbilityTarget> Targets) : AiAction;
|
||
public record AiSacrificeAction(string UnitInstanceId) : AiAction;
|
||
public record AiAscendAction(string IncomingArchSpiritInstanceId) : AiAction;
|
||
public record AiEndTurnAction : AiAction;
|
||
```
|
||
|
||
### 5.2 HeuristicDecisionEngine (Difficulty 1–5)
|
||
|
||
Pure rule-based. Fast (< 50ms per turn). No lookahead.
|
||
|
||
**Turn planning algorithm:**
|
||
|
||
```
|
||
1. Draw Phase
|
||
→ Always draw (nothing to decide)
|
||
|
||
2. Main Phase — Iterative Greedy Loop:
|
||
a. Score current board state (ScoringFunctions.Evaluate)
|
||
b. Generate all candidate actions (ActionCandidateGenerator.All)
|
||
c. Score each candidate: simulate action → score new state
|
||
d. Pick highest-scoring candidate above threshold
|
||
e. Repeat until no candidate improves score OR SP/ST exhausted
|
||
f. Apply DifficultyFilter: randomly skip/replace N% of optimal moves
|
||
|
||
3. End Turn
|
||
```
|
||
|
||
**Board Evaluation (ScoringFunctions.Evaluate):**
|
||
|
||
```
|
||
Score = Σ weights × features
|
||
|
||
Material:
|
||
+ (unit Damage × 2 + unit MaxHealth) per own unit on field
|
||
- (unit Damage × 2 + unit MaxHealth) per opponent unit on field
|
||
+ ArchSpirit HP ratio × 500
|
||
|
||
Affinity Control:
|
||
+ tiles of own ArchSpirit affinity within channeling range × 3
|
||
|
||
Threat:
|
||
- units that can reach own ArchSpirit next turn × 30
|
||
|
||
Resource Efficiency:
|
||
+ (SP remaining / SpCap) × -10 // penalize hoarding too much SP
|
||
+ SacrificeTokens × 5
|
||
|
||
Positional:
|
||
+ units adjacent to opponent ArchSpirit × 15
|
||
+ units in center board zone × 2
|
||
```
|
||
|
||
Weights are stored in `AiDifficultyProfile` and tuned per difficulty tier (see §6).
|
||
|
||
**ActionCandidateGenerator.All(ctx) → List<CandidateAction>:**
|
||
|
||
```
|
||
Channeling candidates:
|
||
foreach card in hand where player.CurrentSp >= card.SpCost:
|
||
foreach tile where ChannelingRange.Contains(tile) && affinity matches:
|
||
yield PlayCardAction(card, tile)
|
||
|
||
Movement candidates:
|
||
foreach unit on field where unit.CanMove && unit.CurrentMp > 0:
|
||
foreach reachable tile (pathfinding):
|
||
yield MoveAction(unit, tile)
|
||
|
||
Attack candidates:
|
||
foreach unit on field where unit.CanAttack:
|
||
foreach enemy in attack range:
|
||
yield AttackAction(unit, enemy)
|
||
|
||
Ability candidates:
|
||
foreach unit on field where unit.CanUseAbility:
|
||
foreach ability where conditions met:
|
||
foreach valid target combination:
|
||
yield ActivateAbilityAction(unit, abilityIdx, targets)
|
||
|
||
Sacrifice candidates:
|
||
foreach unit on field where unit can be sacrificed:
|
||
yield SacrificeAction(unit)
|
||
|
||
Ascend candidates:
|
||
if player has next-tier ArchSpirit in hand && can ascend:
|
||
yield AscendAction(archSpirit)
|
||
```
|
||
|
||
### 5.3 MonteCarloEngine (Difficulty 6–8)
|
||
|
||
Uses **Monte Carlo Tree Search (MCTS)** with random playouts. Can look N turns ahead.
|
||
|
||
```
|
||
Root = current GameState for this AI
|
||
Iterations = f(difficulty, remainingBudgetMs)
|
||
|
||
repeat Iterations:
|
||
1. Selection: traverse tree using UCB1 formula
|
||
UCB1 = (wins/visits) + C × sqrt(ln(parent.visits) / node.visits)
|
||
2. Expansion: if node not fully expanded, add one new child (one candidate action)
|
||
3. Simulation: random playout from child state until game over or N turns deep
|
||
(uses RandomDecisionEngine for all players including opponents)
|
||
4. Backpropagation: update win/loss counts up the tree
|
||
|
||
Best action = child of root with highest visit count (most-explored = most-trusted)
|
||
```
|
||
|
||
**Time budgets per difficulty:**
|
||
- Difficulty 6: 500ms think budget, 3-turn depth
|
||
- Difficulty 7: 1.5s think budget, 5-turn depth
|
||
- Difficulty 8: 4s think budget, 7-turn depth
|
||
|
||
For multi-action turns (play card + move + attack), MCTS treats the full sequence as a plan and
|
||
builds the tree over **turn sequences** (not individual actions). This is done by treating
|
||
"all actions until end_turn" as one composite node.
|
||
|
||
### 5.4 NeuralDecisionEngine (Difficulty 9–10, Phase 3)
|
||
|
||
Wraps a trained neural network model. Architecture TBD (likely a feedforward net or lightweight
|
||
transformer on flattened board + hand state). The model predicts:
|
||
|
||
- **Policy head**: probability distribution over candidate actions
|
||
- **Value head**: estimated win probability from current state
|
||
|
||
The engine selects the highest-policy action that doesn't reduce value below a threshold.
|
||
|
||
Model inference is performed via **ONNX Runtime** (`Microsoft.ML.OnnxRuntime`), allowing models
|
||
trained in Python (PyTorch / TensorFlow) to run in-process in the .NET server.
|
||
|
||
---
|
||
|
||
## 6. Difficulty System
|
||
|
||
### 6.1 Difficulty Tiers
|
||
|
||
| Tier | Name | Engine | Mistake Rate | Think Budget |
|
||
|---|---|---|---|---|
|
||
| 1 | Novice | Random | 100% random | none |
|
||
| 2 | Apprentice | Heuristic | 60% mistakes | 50ms |
|
||
| 3 | Journeyman | Heuristic | 40% mistakes | 50ms |
|
||
| 4 | Adept | Heuristic | 25% mistakes | 50ms |
|
||
| 5 | Expert | Heuristic | 10% mistakes | 50ms |
|
||
| 6 | Master | MCTS | 5% mistakes | 500ms |
|
||
| 7 | Grandmaster | MCTS | 2% mistakes | 1.5s |
|
||
| 8 | Champion | MCTS | 0% | 4s |
|
||
| 9 | Legend | Neural | 0% | 200ms inference |
|
||
| 10 | Mythic | Neural | 0%, beam search | 500ms inference |
|
||
|
||
### 6.2 AiDifficultyProfile
|
||
|
||
```csharp
|
||
public record AiDifficultyProfile
|
||
{
|
||
public int Difficulty { get; init; } // 1–10
|
||
public string DisplayName { get; init; }
|
||
public string EngineType { get; init; } // "Random" | "Heuristic" | "MCTS" | "Neural"
|
||
|
||
// Mistake injection
|
||
public float MistakeRate { get; init; } // 0.0–1.0: probability of replacing optimal with random action
|
||
public float SuboptimalRate { get; init; } // 0.0–1.0: probability of picking 2nd-best instead of best
|
||
|
||
// MCTS params (if applicable)
|
||
public int MctsTimeBudgetMs { get; init; }
|
||
public int MctsMaxDepth { get; init; }
|
||
|
||
// Simulated delays (humanization)
|
||
public int MinThinkTimeMs { get; init; } // before first action each turn
|
||
public int MaxThinkTimeMs { get; init; }
|
||
public int MinActionDelayMs { get; init; } // between subsequent actions
|
||
public int MaxActionDelayMs { get; init; }
|
||
|
||
// Scoring weight overrides (heuristic engine)
|
||
public float MaterialWeight { get; init; }
|
||
public float AffinityControlWeight { get; init; }
|
||
public float ThreatWeight { get; init; }
|
||
public float PositionalWeight { get; init; }
|
||
public float ResourceWeight { get; init; }
|
||
}
|
||
```
|
||
|
||
Profiles are defined as a static table in `AiDifficultyProfiles.cs` (in-code constants, not DB-stored),
|
||
making them easy to tune without migrations.
|
||
|
||
### 6.3 Strategy Archetypes
|
||
|
||
Strategy affects **which actions the AI prioritizes**, not how good it is:
|
||
|
||
| Strategy | Description | Playstyle |
|
||
|---|---|---|
|
||
| `Aggressive` | Rush opponent ArchSpirit; maximize attack pressure | Front-row units, direct damage |
|
||
| `Control` | Protect own ArchSpirit; build affinity control | Back-row units, Terramorpha spam |
|
||
| `Balanced` | Mix of attack and defense | General-purpose |
|
||
| `Ramp` | Maximize SP/ST accumulation for high-cost plays | Sacrifice-heavy, late-game cards |
|
||
| `Swarm` | Channel many low-cost Spirits; overwhelm by count | Cheap spirits, wide field |
|
||
|
||
Strategy is encoded as **scoring function weight adjustments** layered on top of the difficulty
|
||
profile. An `Aggressive` AI at difficulty 5 and a `Control` AI at difficulty 5 make equally
|
||
"good" moves — but in different directions.
|
||
|
||
```csharp
|
||
// Example: Aggressive adjusts weights
|
||
profile = profile with {
|
||
MaterialWeight = profile.MaterialWeight * 1.3f,
|
||
ThreatWeight = profile.ThreatWeight * 0.5f, // less concerned about own ArchSpirit
|
||
};
|
||
```
|
||
|
||
---
|
||
|
||
## 7. Training & Improvement Strategy
|
||
|
||
### 7.1 Training Data Sources
|
||
|
||
Training data is generated from three sources, in order of quality:
|
||
|
||
**Source 1: Human Game Replays**
|
||
- All completed `GameSession` rows have a full `ActionLog` (sequence of actions + states)
|
||
- `GameReplayExporter` converts each log to a sequence of `(state, action, outcome)` triples
|
||
- Outcome = did this player win? (1 = win, 0 = loss)
|
||
- Only high-quality games are used: both players above rank 1200, game went > 10 turns
|
||
|
||
**Source 2: AI Self-Play**
|
||
- `SelfPlayOrchestrator` runs `AiVsAiGameSession` batches (no network, no DB needed — pure `GameEngine` calls)
|
||
- MCTS AI (difficulty 7+) plays against itself 10,000+ games per training run
|
||
- Self-play generates diverse board states including rare positions humans rarely reach
|
||
- Runs as a background job, controlled by admin API: `POST /admin/ai/self-play/start { numGames, difficulty }`
|
||
|
||
**Source 3: Bootstrapped Heuristic Rollouts**
|
||
- For cold-start (before any data exists), heuristic AI at difficulty 5 generates initial training set
|
||
- Lower quality but quick to generate; replaced by better sources over time
|
||
|
||
### 7.2 Feature Extraction
|
||
|
||
`FeatureExtractor.Extract(GameState state, string aiAccountId) → float[]`
|
||
|
||
The feature vector is a fixed-size array encoding the full game state:
|
||
|
||
```
|
||
Board Features (9×9 grid):
|
||
[0..80] Tile affinity type (one-hot per tile, 6 values each → 486 floats)
|
||
[486..566] Tile occupant: own/enemy/empty (3 values per tile → 81×3 = 243)
|
||
[729..809] Occupant unit type index (normalized)
|
||
[810..890] Occupant HP ratio
|
||
[891..971] Occupant Damage (normalized)
|
||
|
||
Own Player State:
|
||
[972] CurrentSp / SpCap
|
||
[973] CurrentSt / 10
|
||
[974] Hand size / HandSizeCap
|
||
[975] Deck size / MaxDeckSize
|
||
[976] Own ArchSpirit HP ratio
|
||
[977] Own ArchSpirit tier / 3
|
||
[978] Field unit count / 10
|
||
[979] TurnNumber / 30
|
||
|
||
Opponent State (same fields, offset by constant):
|
||
[980..987] (same structure)
|
||
|
||
Global:
|
||
[988] ActivePlayerIsAi (1.0 if AI is active player, 0.0 otherwise)
|
||
[989] GameMode FFA=0, Teams=0.5, MultiTeam=1.0
|
||
|
||
Total: ~990 floats
|
||
```
|
||
|
||
### 7.3 Model Architecture (implemented)
|
||
|
||
A **value network MLP** in `tools/train_neural.py`:
|
||
|
||
```
|
||
Input: 1024 floats (FeatureExtractor vector)
|
||
Dense: 1024 -> 512 + LayerNorm + ReLU + Dropout(0.2)
|
||
Dense: 512 -> 256 + LayerNorm + ReLU + Dropout(0.2)
|
||
Dense: 256 -> 128 + LayerNorm + ReLU
|
||
Output: 128 -> 1 + Tanh => score in [-1, 1]
|
||
```
|
||
|
||
- **+1.0** = acting player won; **-1.0** = acting player lost
|
||
- Loss: MSELoss on outcome. Optimizer: AdamW + cosine LR annealing, gradient clip 1.0
|
||
- Best checkpoint (lowest val loss) restored before ONNX export
|
||
- ~920k parameters
|
||
|
||
**ONNX contract** (must match `NeuralModelRegistry` constants `InputName`/`OutputName`):
|
||
|
||
| Property | Value |
|
||
|----------|-------|
|
||
| Input tensor name | `features` |
|
||
| Input shape | `[1, 1024]` float32 |
|
||
| Output tensor name | `score` |
|
||
| Output shape | `[1, 1]` float32 |
|
||
| Output range | `[-1, 1]` via tanh |
|
||
|
||
---
|
||
|
||
### 7.4 How to Train the AI
|
||
|
||
See `tools/README.md` for the complete step-by-step workflow. Summary below.
|
||
|
||
#### Step 1 - Generate self-play data
|
||
|
||
In the admin portal, go to **AI -> Calibration** and click **Run All Pairs**.
|
||
This triggers in-process AI vs AI games (no network, no delays) across all difficulty pairs.
|
||
The resulting `GameSession` rows are the training data source.
|
||
|
||
Alternatively run a specific difficulty pair to generate targeted data faster:
|
||
```
|
||
POST /admin/ai/calibration/run-pair { difficultyA: 7, difficultyB: 8, gameCount: 200 }
|
||
```
|
||
|
||
#### Step 2 - Export training data
|
||
|
||
In the admin portal, go to **AI -> Calibration** and click **Export Training Data**.
|
||
Enter an output path on the server, e.g. `/var/sor/training/data.jsonl`.
|
||
|
||
`GameReplayExporter` replays each completed session action-by-action and writes one
|
||
JSON line per action:
|
||
|
||
```json
|
||
{
|
||
GameSessionId: 3fa85f64...,
|
||
TurnNumber: 5,
|
||
ActorAccountId: ...,
|
||
Features: [0.0, 1.0, ...],
|
||
ActionType: AiPlayCardAction,
|
||
ActionJson: {},
|
||
Outcome: 1.0
|
||
}
|
||
```
|
||
|
||
`Outcome` is `+1.0` if the acting player won, `-1.0` if they lost.
|
||
|
||
#### Step 3 - Train the model
|
||
|
||
Install dependencies (Python 3.11+):
|
||
|
||
```bash
|
||
pip install -r tools/requirements.txt
|
||
```
|
||
|
||
Run training:
|
||
|
||
```bash
|
||
python tools/train_neural.py --data /var/sor/training/data.jsonl --out /var/sor/models/model.onnx --epochs 50 --batch-size 512 --lr 1e-3
|
||
```
|
||
|
||
Key options:
|
||
|
||
| Flag | Default | Description |
|
||
|------|---------|-------------|
|
||
| `--epochs` | 50 | Training epochs |
|
||
| `--batch-size` | 512 | Mini-batch size |
|
||
| `--lr` | 0.001 | AdamW learning rate |
|
||
| `--val-split` | 0.1 | Validation fraction |
|
||
| `--dropout` | 0.2 | Dropout probability |
|
||
| `--cpu` | off | Force CPU (ignores CUDA) |
|
||
|
||
The script prints per-epoch train/val loss, marks best checkpoint with `*`, restores
|
||
best weights before export, and runs a quick onnxruntime validation of the exported file.
|
||
|
||
#### Step 4 - Deploy
|
||
|
||
```
|
||
1. Copy model.onnx to the path configured in appsettings: Ai:NeuralModelPath
|
||
2. Admin -> AI -> Neural Model -> Hot-swap Model
|
||
```
|
||
|
||
No restart required. The old ONNX InferenceSession is disposed atomically.
|
||
Tiers 9-10 use the new model for all subsequent decisions.
|
||
If no model file exists, tiers 9-10 fall back to heuristic scoring transparently.
|
||
|
||
#### Iterative improvement
|
||
|
||
1. **Cold start**: run heuristic self-play (D5) to generate initial data; train first model.
|
||
2. **Deploy** model and enable D9-D10 in calibration runs.
|
||
3. **D9/D10 self-play** generates higher-quality data than heuristic rollouts.
|
||
4. **Append** new export to JSONL; retrain with more epochs.
|
||
5. **Monitor** admin calibration win-rates after each deployment; adjust difficulty profiles if needed.
|
||
|
||
---
|
||
|
||
### 7.5 Difficulty Calibration
|
||
|
||
After each self-play / training cycle, run **calibration games** against human players:
|
||
|
||
- Pull a random sample of 100 recent ranked games (human ELO distribution)
|
||
- Run AI at each difficulty tier against a simulated human from a comparable rank
|
||
- Measure AI win rate: target ~40–60% win rate for each difficulty tier against the matching rank band
|
||
|
||
Calibration thresholds (target AI win rate vs human ELO band):
|
||
|
||
| Difficulty | Target ELO range | Target AI win% |
|
||
|---|---|---|
|
||
| 1 | Unranked (any) | 10–25% |
|
||
| 2 | 800–1000 | 30–45% |
|
||
| 3 | 1000–1100 | 35–50% |
|
||
| 4 | 1100–1200 | 40–55% |
|
||
| 5 | 1200–1350 | 45–55% |
|
||
| 6 | 1350–1500 | 45–55% |
|
||
| 7 | 1500–1700 | 45–55% |
|
||
| 8 | 1700–1900 | 45–55% |
|
||
| 9 | 1900–2100 | 45–55% |
|
||
| 10 | 2100+ | 45–55% |
|
||
|
||
If win rate drifts outside target, adjust `MistakeRate` / MCTS budget / scoring weights accordingly.
|
||
Calibration runs are automated via `AiCalibrationJob` (admin-triggered).
|
||
|
||
---
|
||
|
||
## 8. Deck Composition for AI
|
||
|
||
### 8.1 AI Deck Creation
|
||
|
||
AI players need pre-built decks. These are not in the player collection system; they are seeded
|
||
directly in the `Deck` table with `AccountId` = the AI's virtual account.
|
||
|
||
Each AI account gets **one deck per viable ArchSpirit + affinity combination**, covering major
|
||
strategic archetypes:
|
||
|
||
```
|
||
ai-novice-balanced:
|
||
ArchSpirit: "Ignis Pup" (Fire, Tier 1)
|
||
Deck: 30-card fire-affinity mix of Spirits and Repentance cards
|
||
(Simple, no complex ability chains)
|
||
|
||
ai-master-control:
|
||
ArchSpirit: "Hydra Sentinel" (Water, Tier 1)
|
||
Deck: 30-card water-control deck with Terramorpha + defensive Spirits
|
||
(Uses advanced affinity tile locking)
|
||
|
||
ai-grandmaster-aggressive:
|
||
ArchSpirit: "Blazing Warchief" (Fire, Tier 1)
|
||
Deck: 30-card aggro deck, cheap Spirits, rush down opponent
|
||
```
|
||
|
||
Deck seeds are defined as code constants in `AiDeckDefinitions.cs` and applied via a DB seed
|
||
migration. AI decks bypass normal deck validation requirements (IsValid flag forced true).
|
||
|
||
### 8.2 Deck Matching to Strategy
|
||
|
||
`AiSlotAssigner` picks the AI account whose strategy matches the host's request. For the first
|
||
implementation, one deck per strategy tier is sufficient. Future iterations may allow AI to
|
||
choose a deck based on opponent's ArchSpirit (counter-deck logic).
|
||
|
||
---
|
||
|
||
## 9. Multi-Player & Team AI
|
||
|
||
### 9.1 FFA (Free-For-All)
|
||
|
||
Each AI seat is independently managed by a separate `AiPlayerSession`. The AI evaluates all
|
||
opponents as threats; scoring functions weight all enemy ArchSpirits equally (no preferred target
|
||
in base version; future: target weakest).
|
||
|
||
### 9.2 Team Mode
|
||
|
||
In team games, AI evaluates friendly units as **protected** (does not attack them) and enemy
|
||
units as **threats**. The AI is not aware of teammate's planned actions — it plays optimistically.
|
||
|
||
Future Phase 2: implement `TeamAiCoordinator` that shares intention signals between team-AI
|
||
sessions (e.g. "I will attack this unit, don't duplicate effort").
|
||
|
||
---
|
||
|
||
## 10. New Message Types
|
||
|
||
Add to `GameMessages.cs`:
|
||
|
||
```csharp
|
||
// Host → Server: add an AI player to a custom lobby
|
||
public record GameAddAiRequest(string LobbyId, int Difficulty, string Strategy);
|
||
public record GameAddAiResponse(string AiAccountId, string AiDisplayName, int SeatIndex);
|
||
|
||
// Host → Server: remove an AI player from a custom lobby
|
||
public record GameRemoveAiRequest(string LobbyId, string AiAccountId);
|
||
public record GameRemoveAiResponse(bool Success);
|
||
|
||
// Host → Server: change AI difficulty or strategy before game starts
|
||
public record GameConfigureAiRequest(string LobbyId, string AiAccountId,
|
||
int? Difficulty, string? Strategy);
|
||
public record GameConfigureAiResponse(bool Success);
|
||
|
||
// Push → all lobby members: lobby AI slots changed
|
||
public record CustomLobbyAiSlotsChangedPush(string LobbyId,
|
||
IReadOnlyList<AiSlotInfo> CurrentAiSlots);
|
||
|
||
public record AiSlotInfo(string AccountId, string DisplayName,
|
||
int Difficulty, string Strategy, int SeatIndex);
|
||
```
|
||
|
||
Message type strings:
|
||
- `"game.ai.add"` → `GameAddAiHandler`
|
||
- `"game.ai.remove"` → `GameRemoveAiHandler`
|
||
- `"game.ai.configure"` → `GameAiConfigureHandler`
|
||
|
||
---
|
||
|
||
## 11. Database Schema Additions
|
||
|
||
### 11.1 Account.IsAi Column
|
||
|
||
```sql
|
||
ALTER TABLE accounts ADD COLUMN is_ai BOOLEAN NOT NULL DEFAULT FALSE;
|
||
ALTER TABLE accounts ADD COLUMN ai_difficulty INT NULL;
|
||
ALTER TABLE accounts ADD COLUMN ai_strategy TEXT NULL;
|
||
```
|
||
|
||
`Account` entity:
|
||
```csharp
|
||
public bool IsAi { get; set; }
|
||
public int? AiDifficulty { get; set; }
|
||
public string? AiStrategy { get; set; }
|
||
```
|
||
|
||
### 11.2 AiEloRecord Table
|
||
|
||
Tracks AI performance separately from ranked ELO (not shown to players):
|
||
|
||
```sql
|
||
CREATE TABLE ai_elo_records (
|
||
id UUID PRIMARY KEY,
|
||
ai_account_id UUID NOT NULL REFERENCES accounts(id),
|
||
elo_score INT NOT NULL DEFAULT 1200,
|
||
wins INT NOT NULL DEFAULT 0,
|
||
losses INT NOT NULL DEFAULT 0,
|
||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||
);
|
||
```
|
||
|
||
### 11.3 CustomLobby AI Slot Tracking
|
||
|
||
Add to `CustomLobby`:
|
||
|
||
```sql
|
||
ALTER TABLE custom_lobbies ADD COLUMN ai_slots_json JSONB NULL;
|
||
```
|
||
|
||
`AiSlotsJson` is an array of:
|
||
```json
|
||
[
|
||
{ "accountId": "ai-easy-balanced", "seatIndex": 2, "difficulty": 3, "strategy": "Balanced" }
|
||
]
|
||
```
|
||
|
||
---
|
||
|
||
## 12. Implementation Phases
|
||
|
||
Phases are deliberately narrow so each can be handed off as a single focused coding session.
|
||
Each phase lists **exact files to create or modify**, the **DI wiring required**, and a
|
||
**"done" definition** — a concrete test you can run to confirm the phase is complete before
|
||
moving on.
|
||
|
||
Phases are grouped into tracks:
|
||
- **Track A (1.x)** — Project scaffold, database, and lobby plumbing. No AI logic yet.
|
||
- **Track B (2.x)** — Turn execution pipeline. Random AI first, then heuristic.
|
||
- **Track C (3.x)** — Competitive MCTS AI + training data collection.
|
||
- **Track D (4.x)** — Neural AI + offline training pipeline.
|
||
- **Track E (5.x)** — Polish, adaptive difficulty, ecosystem features.
|
||
|
||
---
|
||
|
||
### Phase 1.1 — Project Scaffold
|
||
|
||
**Goal**: `SOR.Ai` compiles, is wired into `SOR.Host`, and registers its own empty
|
||
`ServiceRegistration`. Nothing runs yet — this is pure plumbing.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
├── SOR.Ai.csproj
|
||
└── ServiceRegistration.cs
|
||
```
|
||
|
||
**`SOR.Ai.csproj`** — follow the same pattern as all other class libraries:
|
||
- `Sdk="Microsoft.NET.Sdk"`, `<TargetFramework>net8.0</TargetFramework>`
|
||
- `<FrameworkReference Include="Microsoft.AspNetCore.App" />`
|
||
- Project references: `SOR.Database`, `SOR.Game`, `SOR.Networking.Abstractions`, `SOR.Shared`
|
||
|
||
**`ServiceRegistration.cs`:**
|
||
```csharp
|
||
namespace SOR.Ai;
|
||
|
||
public static class ServiceRegistration
|
||
{
|
||
public static IServiceCollection AddAiService(
|
||
this IServiceCollection services,
|
||
IConfiguration configuration)
|
||
{
|
||
// phases will add registrations here
|
||
return services;
|
||
}
|
||
}
|
||
```
|
||
|
||
**Files to modify:**
|
||
|
||
- `Server/SOR.slnx` — add `SOR.Ai` project entry
|
||
- `Server/src/SOR.Host/SOR.Host.csproj` — add `<ProjectReference>` to `SOR.Ai`
|
||
- `Server/src/SOR.Host/Program.cs` — call `builder.Services.AddAiService(builder.Configuration)`
|
||
immediately after `AddGameService`, guarded by the same `ENABLED_SERVICES` check pattern
|
||
|
||
**Done when**: `dotnet build Server/SOR.slnx` produces zero errors and zero warnings.
|
||
|
||
---
|
||
|
||
### Phase 1.2 — AI Transport Abstractions
|
||
|
||
**Goal**: Define `AiAuthenticatedConnection` and `AiClientMessage` — the two types that let AI
|
||
code call game handlers directly without a WebSocket. These are the foundation everything else
|
||
builds on.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Transport/
|
||
├── AiAuthenticatedConnection.cs
|
||
└── AiClientMessage.cs
|
||
```
|
||
|
||
**`AiAuthenticatedConnection`** implements `IAuthenticatedConnection` (from
|
||
`SOR.Networking.Abstractions`). It holds:
|
||
- `string UserId` — the AI's virtual account ID (passed in constructor)
|
||
- `Guid SessionId` — the game session it belongs to
|
||
- All other members of the interface no-op or throw `NotSupportedException`
|
||
|
||
**`AiClientMessage`** implements `IClientMessage`. It holds:
|
||
- `string Type` — the message type string (e.g. `"game.draw"`)
|
||
- `int Seq` — always 0 (no reply routing needed for AI)
|
||
- `ReadOnlyMemory<byte> Payload` — pre-serialized JSON payload bytes
|
||
|
||
The payload is serialized by the caller using `JsonSerializer.SerializeToUtf8Bytes(request)`,
|
||
matching exactly how `SOR.Gateway` deserializes incoming WebSocket frames.
|
||
|
||
**No DI registration needed** — these are `new`-able value types, instantiated per action.
|
||
|
||
**Done when**: Both types compile and the `IAuthenticatedConnection` / `IClientMessage` contracts
|
||
are fully satisfied (no NotImplementedExceptions that handlers would hit during normal turn flow).
|
||
|
||
---
|
||
|
||
### Phase 1.3 — Database: AI Account Schema
|
||
|
||
**Goal**: Add the `IsAi`, `AiDifficulty`, and `AiStrategy` columns to the `Account` entity and
|
||
produce a migration. No seed data yet — that comes in 1.4.
|
||
|
||
**Files to modify:**
|
||
|
||
- `Server/src/SOR.Database/Entities/Identity/Account.cs`
|
||
— add three properties:
|
||
```csharp
|
||
public bool IsAi { get; set; }
|
||
public int? AiDifficulty { get; set; }
|
||
public string? AiStrategy { get; set; }
|
||
```
|
||
|
||
- `Server/src/SOR.Database/Contexts/SorIdentityDbContext.cs`
|
||
— add `.HasDefaultValue(false)` config for `IsAi` in `OnModelCreating`
|
||
|
||
- `Server/src/SOR.Database/Entities/Game/CustomLobby.cs`
|
||
— add `public string? AiSlotsJson { get; set; }` (JSONB column, nullable)
|
||
|
||
- `Server/src/SOR.Matchmaking/MatchmakerService.cs`
|
||
— add `.Where(e => !e.Account.IsAi)` (or equivalent join filter) so AI accounts
|
||
are never entered into the ranked queue
|
||
|
||
**Migration**: run `dotnet ef migrations add AddAiAccountFields` targeting
|
||
`SorIdentityDbContext` and a separate migration targeting `GameDbContext` for
|
||
`CustomLobby.AiSlotsJson`. Follow the existing migration project structure.
|
||
|
||
**Done when**: migrations apply cleanly against a local dev DB and the Matchmaking
|
||
service query is confirmed to exclude `IsAi = true` accounts via a unit or integration test.
|
||
|
||
---
|
||
|
||
### Phase 1.4 — AI Account Seeds
|
||
|
||
**Goal**: Seed one AI `Account` row per `(difficulty, strategy)` combination into the DB.
|
||
These accounts are the "virtual players" that will join lobbies. Decks come in Phase 1.5.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Seeding/
|
||
└── AiAccountSeeder.cs
|
||
```
|
||
|
||
**`AiAccountSeeder`** is a static helper called from `ServiceRegistration.AddAiService`:
|
||
```csharp
|
||
// Called at startup: ensures AI accounts exist, idempotent (upsert by deterministic ID)
|
||
internal static async Task SeedAsync(SorIdentityDbContext identityDb, CancellationToken ct)
|
||
```
|
||
|
||
It uses a deterministic GUID-from-name strategy for each account ID so re-running is safe.
|
||
For each combination of difficulties 1–10 and strategies `["Aggressive", "Control",
|
||
"Balanced", "Ramp", "Swarm"]`, it upserts an Account row with:
|
||
- `IsAi = true`
|
||
- `AiDifficulty` / `AiStrategy` set
|
||
- `Username` = e.g. `"Balanced AI (Adept)"` (human-readable display name)
|
||
- `RankScore = 0`, `OriginPoints = 0` (AI accounts don't earn currency)
|
||
- `IsEmailVerified = true`, `PasswordHash = ""` (never logs in)
|
||
|
||
**DI wiring** (in `ServiceRegistration.cs`):
|
||
```csharp
|
||
// Register as IHostedService so it runs once at startup before traffic is accepted
|
||
services.AddHostedService<AiSeedStartupService>();
|
||
```
|
||
|
||
`AiSeedStartupService` is a one-shot `IHostedService` that calls `AiAccountSeeder.SeedAsync`
|
||
then exits — same pattern as the existing `GameStartupCleanupService`.
|
||
|
||
**Done when**: after server start, a DB query for `WHERE is_ai = true` returns exactly
|
||
`10 difficulties × 5 strategies = 50` rows.
|
||
|
||
---
|
||
|
||
### Phase 1.5 — AI Deck Seeds
|
||
|
||
**Goal**: Create one pre-built `Deck` (with `DeckCard` rows) for each AI account. Decks are
|
||
seeded from code-defined constants; they do not go through normal collection ownership.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Seeding/
|
||
├── AiDeckDefinitions.cs — static list of deck blueprints (by strategy archetype)
|
||
└── AiDeckSeeder.cs — upserts Deck + DeckCard rows for each AI account
|
||
```
|
||
|
||
**`AiDeckDefinitions.cs`** defines a `record AiDeckBlueprint(string Strategy, string ArchSpiritName, string[] CardNames)`.
|
||
One blueprint per strategy archetype:
|
||
- `Balanced` — one ArchSpirit, mixed Spirit/Repentance cards
|
||
- `Aggressive` — cheap Spirits, attack-range units, Repentance damage spells
|
||
- `Control` — Terramorpha + high-defense Spirits, few attacks
|
||
- `Ramp` — Sacrifice-heavy Spirits, high-cost powerful late-game cards
|
||
- `Swarm` — max-count low-SP Spirits, wide board presence
|
||
|
||
Blueprints reference cards by name. `AiDeckSeeder` resolves names to `CardDefinitionId` at
|
||
seed time (query `CardDefinitions WHERE Name = ?`). If a card doesn't exist in the catalog
|
||
(environment without full card data), the seeder logs a warning and skips, allowing partial
|
||
decks to still work.
|
||
|
||
**`AiDeckSeeder`** upserts one `Deck` row per AI account with:
|
||
- `AccountId` = AI account ID
|
||
- `IsValid = true` (forced — bypasses deck-construction validation)
|
||
- Cards from matching blueprint
|
||
|
||
**DI wiring**: called inside `AiSeedStartupService` after `AiAccountSeeder.SeedAsync` completes,
|
||
so both run atomically at startup.
|
||
|
||
**Done when**: after server start, each AI account has at least one `Deck` row with at least
|
||
one `DeckCard` child row; querying `decks WHERE account_id IN (ai account IDs)` returns 50 rows.
|
||
|
||
---
|
||
|
||
### Phase 1.6 — Lobby Handlers: Add / Remove / Configure AI
|
||
|
||
**Goal**: Expose the three message handlers that let a host manage AI seats in a custom lobby.
|
||
After this phase, a host can add/remove AI players from a lobby via the client — though the AI
|
||
won't actually play yet (turn execution comes later).
|
||
|
||
**New message types** — add to `SOR.Game/GameMessages.cs`:
|
||
```csharp
|
||
public record GameAddAiRequest(Guid LobbyId, int Difficulty, string Strategy);
|
||
public record GameAddAiResponse(Guid AiAccountId, string AiDisplayName, int SeatIndex);
|
||
|
||
public record GameRemoveAiRequest(Guid LobbyId, Guid AiAccountId);
|
||
public record GameRemoveAiResponse(bool Success);
|
||
|
||
public record GameConfigureAiRequest(Guid LobbyId, Guid AiAccountId,
|
||
int? Difficulty, string? Strategy);
|
||
public record GameConfigureAiResponse(bool Success);
|
||
|
||
public record CustomLobbyAiSlotsChangedPush(Guid LobbyId,
|
||
IReadOnlyList<AiSlotInfo> CurrentAiSlots);
|
||
|
||
public record AiSlotInfo(Guid AccountId, string DisplayName,
|
||
int Difficulty, string Strategy, int SeatIndex);
|
||
```
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
├── Lobby/
|
||
│ ├── AiSlotAssigner.cs — resolves (difficulty, strategy) → AI Account + seat index
|
||
│ └── AiLobbyService.cs — shared read/write helpers for CustomLobby.AiSlotsJson
|
||
└── Handlers/
|
||
├── GameAddAiHandler.cs
|
||
├── GameRemoveAiHandler.cs
|
||
└── GameConfigureAiHandler.cs
|
||
```
|
||
|
||
**Handler pattern**: each handler extends `GameHandlerBase` (from `SOR.Game.Handlers`),
|
||
taking a `GameDbContext` and `IClientPush` via constructor (injected as transient, same as all
|
||
existing game handlers). Each validates:
|
||
- `conn.UserId == lobby.HostAccountId` (only host can manage AI slots)
|
||
- Lobby status is `Open` or `Full` (not `Started` or `Completed`)
|
||
- For Add: seat count after add does not exceed `lobby.MaxPlayers`
|
||
- For Remove: the given AI account is actually in `AiSlotsJson`
|
||
|
||
`AiSlotAssigner.Assign(difficulty, strategy)` queries `identityDb.Users WHERE IsAi = true
|
||
AND AiDifficulty = difficulty AND AiStrategy = strategy LIMIT 1` and returns the account.
|
||
|
||
After any mutation, all handlers push `CustomLobbyAiSlotsChangedPush` to all lobby members
|
||
(using the same `clientPush.PushAsync` pattern as existing lobby handlers).
|
||
|
||
**DI wiring** in `SOR.Ai/ServiceRegistration.cs`:
|
||
```csharp
|
||
services.AddTransient<IMessageHandler, GameAddAiHandler>();
|
||
services.AddTransient<IMessageHandler, GameRemoveAiHandler>();
|
||
services.AddTransient<IMessageHandler, GameConfigureAiHandler>();
|
||
services.AddScoped<AiSlotAssigner>();
|
||
services.AddScoped<AiLobbyService>();
|
||
```
|
||
|
||
**Done when**: a client can call `game.ai.add` on an open lobby and receive a valid
|
||
`GameAddAiResponse`; calling `game.ai.remove` removes it; both changes are persisted to
|
||
`CustomLobby.AiSlotsJson` and pushed to all lobby members.
|
||
|
||
---
|
||
|
||
### Phase 1.7 — AI Session Manager (Hosted Service Skeleton)
|
||
|
||
**Goal**: Create `AiPlayerSessionManager` — the singleton hosted service that will orchestrate
|
||
AI turns. In this phase it only handles the game-start event and registers active AI sessions.
|
||
Turn execution is wired in Phase 2.1.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Core/
|
||
├── AiPlayerSession.cs — per-session state for one AI seat
|
||
├── AiPlayerSessionManager.cs — singleton hosted service, manages all active AI sessions
|
||
└── AiTurnContext.cs — snapshot of GameState from one AI's perspective
|
||
```
|
||
|
||
**`AiPlayerSession`** holds:
|
||
- `Guid SessionId`
|
||
- `Guid AiAccountId`
|
||
- `int Difficulty`, `string Strategy`
|
||
- `int SeatIndex`
|
||
- `CancellationTokenSource SessionCts` — cancelled when game ends
|
||
|
||
**`AiPlayerSessionManager`** is a `BackgroundService` that:
|
||
1. Subscribes to NATS subject `NatsSubjects.GameStarted` (the same event `SOR.Matchmaking`
|
||
already publishes when any game starts — including custom lobby games)
|
||
2. On `GameStartedEvent`, loads the `GameSession` from DB and inspects `AdditionalPlayersJson`
|
||
plus `GuestAccountId` / `PlayerOneAccountId` to identify any seats whose account has `IsAi = true`
|
||
3. Creates one `AiPlayerSession` per AI seat and stores it in a `ConcurrentDictionary<Guid, List<AiPlayerSession>>`
|
||
4. Subscribes to NATS subject `NatsSubjects.GameEnded` and disposes sessions for that game
|
||
|
||
At this stage, the sessions are created but no turn logic fires yet.
|
||
|
||
**Auto-ready**: when the game session is first created and an AI is in a seat, the manager
|
||
sends `game.ready` (via a direct handler call using `AiAuthenticatedConnection` + `AiClientMessage`)
|
||
with a short random delay (200–800ms). This allows a 1-human-vs-1-AI lobby to start without
|
||
the human waiting for a fake "opponent connect" event.
|
||
|
||
**DI wiring** in `ServiceRegistration.cs`:
|
||
```csharp
|
||
services.AddSingleton<AiPlayerSessionManager>();
|
||
services.AddHostedService(sp => sp.GetRequiredService<AiPlayerSessionManager>());
|
||
```
|
||
|
||
**Done when**: starting a custom lobby game that has one AI seat causes `AiPlayerSessionManager`
|
||
to log "AI session registered: {sessionId} seat {seatIndex}" and the game transitions past the
|
||
ready phase automatically (the AI submits `game.ready`).
|
||
|
||
---
|
||
|
||
### Phase 2.1 — Turn Event + Action Submission Pipeline
|
||
|
||
**Goal**: Wire up the `AiTurnStartedEvent` from `GameEndTurnHandler` and implement the action
|
||
submission loop in `AiPlayerSession`. After this phase, the AI will take turns — even if it
|
||
does nothing useful on them (end turn immediately). This proves the end-to-end pipeline works.
|
||
|
||
**Files to modify:**
|
||
|
||
- `SOR.Shared/Nats/NatsSubjects.cs` — add `public const string AiTurnStarted = "sor.game.ai_turn_started";`
|
||
- `SOR.Game/Handlers/GameEndTurnHandler.cs` — after advancing the turn, if the new
|
||
`state.ActivePlayerAccountId` is an AI account (check via `IEventBus` — publish
|
||
`AiTurnStartedEvent { SessionId, AiAccountId, TurnNumber }`). The check is done by looking up
|
||
whether `activePlayerId` appears in a locally-injected `IAiAccountRegistry` (see below).
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Core/
|
||
└── AiAccountRegistry.cs — singleton: set of all known AI account IDs (loaded at startup)
|
||
```
|
||
|
||
`AiAccountRegistry` is a singleton loaded by `AiSeedStartupService` after seeding — it reads
|
||
all `IsAi = true` account IDs into a `HashSet<string>` for O(1) lookups. Injected into
|
||
`GameEndTurnHandler` via `IAiAccountRegistry` interface (defined in `SOR.Networking.Abstractions`
|
||
or `SOR.Shared` to avoid a circular dependency from `SOR.Game` → `SOR.Ai`).
|
||
|
||
**`AiPlayerSession.ExecuteTurnAsync`** (Phase 2.1 stub):
|
||
```csharp
|
||
internal async Task ExecuteTurnAsync(GameState state, CancellationToken ct)
|
||
{
|
||
// Phase 2.1: immediately end turn (no decision logic yet)
|
||
await SubmitActionAsync("game.end_turn", new GameEndTurnRequest(SessionId), ct);
|
||
}
|
||
```
|
||
|
||
`SubmitActionAsync` constructs `AiAuthenticatedConnection` + `AiClientMessage`, resolves the
|
||
matching `IMessageHandler` from `IServiceProvider` (keyed by `msg.Type`), and calls
|
||
`handler.HandleAsync`. Handler resolution follows the same `MessageDispatcher` pattern already
|
||
used in `SOR.Gateway`.
|
||
|
||
**`AiPlayerSessionManager`** subscribes to `AiTurnStartedEvent` via NATS and calls
|
||
`session.ExecuteTurnAsync` after a configurable base delay.
|
||
|
||
**Done when**: in a human-vs-AI custom game, after the human ends their turn, the AI's turn
|
||
starts and immediately ends (AI passes). The human sees the state update and their turn resumes.
|
||
The game can reach game-over naturally when the human attacks the AI ArchSpirit to zero health.
|
||
|
||
---
|
||
|
||
### Phase 2.2 — Placement Phase Handling
|
||
|
||
**Goal**: Teach the AI to handle the `Placement` phase — specifically `game.place_arch_spirit`.
|
||
Without this the AI will never leave Placement and the game cannot begin.
|
||
|
||
This is a discrete phase because placement has its own logic: the AI must pick a valid starting
|
||
coordinate in its placement zone, which is determined by `SeatIndex` and `GameRules`.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Engine/
|
||
└── PlacementStrategy.cs — picks a valid arch-spirit placement coordinate
|
||
```
|
||
|
||
**`PlacementStrategy.SelectCoord(AiTurnContext ctx) → Coord`**:
|
||
- Reads `ctx.State.Board.StartingZones[aiSeatIndex]`
|
||
- For Phase 2.2 (novice behaviour): picks a random coordinate from the starting zone
|
||
- Later phases will have `HeuristicDecisionEngine` call this too, potentially picking
|
||
a coordinate that maximises affinity push toward the board center
|
||
|
||
**`AiPlayerSession.ExecuteTurnAsync`** gains a phase check:
|
||
```csharp
|
||
if (state.Phase == GamePhase.Placement)
|
||
{
|
||
var coord = PlacementStrategy.SelectCoord(ctx);
|
||
await SubmitActionAsync("game.place_arch_spirit", new GamePlaceArchSpiritRequest(SessionId, coord), ct);
|
||
return;
|
||
}
|
||
```
|
||
|
||
**Done when**: an AI seat progresses through Placement automatically and the board reaches
|
||
the Draw phase, at which point both human and AI have ArchSpirits on the board.
|
||
|
||
---
|
||
|
||
### Phase 2.3 — Random Decision Engine (Difficulty 1)
|
||
|
||
**Goal**: Implement `IAiDecisionEngine`, the `AiAction` discriminated union, `AiDifficultyProfile`,
|
||
and `RandomDecisionEngine`. After this phase Difficulty 1 AI plays a legal (but random) game.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Engine/
|
||
├── IAiDecisionEngine.cs — interface + AiAction hierarchy (records)
|
||
├── AiDifficultyProfile.cs — record definition
|
||
├── AiDifficultyProfiles.cs — static table of all 10 profiles
|
||
└── RandomDecisionEngine.cs — picks random legal action each step
|
||
```
|
||
|
||
**`IAiDecisionEngine`**:
|
||
```csharp
|
||
public interface IAiDecisionEngine
|
||
{
|
||
IReadOnlyList<AiAction> ComputeTurn(AiTurnContext ctx);
|
||
}
|
||
```
|
||
|
||
`AiAction` discriminated union: `AiDrawAction`, `AiPlayCardAction`, `AiMoveAction`,
|
||
`AiAttackAction`, `AiActivateAbilityAction`, `AiSacrificeAction`, `AiAscendAction`,
|
||
`AiEndTurnAction`.
|
||
|
||
**`RandomDecisionEngine`** loops:
|
||
1. Generate one random legal action (from any category) — or `AiEndTurnAction` if none exist
|
||
2. Append to plan
|
||
3. If action was `AiEndTurnAction` or SP/MP exhausted, stop
|
||
|
||
**`AiPlayerSession`** selects engine based on `AiDifficultyProfiles.Get(difficulty).EngineType`.
|
||
For this phase only `"Random"` works; other engine types fall back to `RandomDecisionEngine`.
|
||
|
||
**DI wiring**:
|
||
```csharp
|
||
services.AddTransient<RandomDecisionEngine>();
|
||
```
|
||
|
||
Engines are resolved by `AiPlayerSession` directly from `IServiceProvider` (keyed by engine type
|
||
string from the profile). This avoids a factory abstraction we don't need yet.
|
||
|
||
**Done when**: an AI on Difficulty 1 plays a full game from Placement to game-over (either the
|
||
human kills the AI ArchSpirit, the AI accidentally kills the human's, or turn limit is reached).
|
||
All actions are valid (no `GameException` thrown).
|
||
|
||
---
|
||
|
||
### Phase 2.4 — Action Candidate Generator
|
||
|
||
**Goal**: Build `ActionCandidateGenerator` — the component that enumerates every legal move
|
||
the AI can make from a given `GameState`. This is a pure function (no side effects, no DB),
|
||
reused by both the heuristic and MCTS engines.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Heuristics/
|
||
└── ActionCandidateGenerator.cs
|
||
```
|
||
|
||
**Method signatures:**
|
||
```csharp
|
||
public static class ActionCandidateGenerator
|
||
{
|
||
// All legal actions for the active player in the given state.
|
||
public static IReadOnlyList<AiAction> All(AiTurnContext ctx);
|
||
|
||
// Channeling candidates only (play card to tile)
|
||
public static IReadOnlyList<AiPlayCardAction> Channelings(AiTurnContext ctx);
|
||
|
||
// Movement candidates for a specific unit
|
||
public static IReadOnlyList<AiMoveAction> Movements(AiTurnContext ctx, string unitInstanceId);
|
||
|
||
// Attack candidates for a specific unit
|
||
public static IReadOnlyList<AiAttackAction> Attacks(AiTurnContext ctx, string unitInstanceId);
|
||
|
||
// Ability candidates for a specific unit
|
||
public static IReadOnlyList<AiActivateAbilityAction> Abilities(AiTurnContext ctx, string unitInstanceId);
|
||
}
|
||
```
|
||
|
||
Implementation delegates range/path/affinity logic back to `SOR.Game` modules directly —
|
||
`ChannelingRange`, `Pathfinding`, `AffinitySystem` — so no game rules are duplicated in `SOR.Ai`.
|
||
|
||
**`AiTurnContext`** (from Phase 1.7) stores:
|
||
- `GameState State`
|
||
- `string AiAccountId`
|
||
- `PlayerState AiPlayer` (convenience: `State.Players[AiAccountId]`)
|
||
- `IReadOnlyList<string> OpponentIds`
|
||
- `GameRules Rules`
|
||
|
||
**Done when**: unit tests (xUnit, same test project pattern as existing `SOR.Game.Tests`) cover:
|
||
- Channeling with sufficient SP and matching affinity → produces candidates
|
||
- Channeling with insufficient SP → no candidates
|
||
- Movement with zero MP remaining → no candidates
|
||
- Attack out of range → not in candidates
|
||
- Ascend when next-tier ArchSpirit is in hand → ascend candidate present
|
||
|
||
---
|
||
|
||
### Phase 2.5 — Heuristic Scoring & Decision Engine (Difficulties 2–5)
|
||
|
||
**Goal**: Implement board evaluation and the greedy heuristic engine. After this phase,
|
||
Difficulties 2–5 play purposefully — they attack weak targets, defend the ArchSpirit, and
|
||
spend SP on cards that improve their board position.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Heuristics/
|
||
├── ScoringFunctions.cs — board evaluation: material, position, affinity, threat
|
||
├── ThreatDetector.cs — which enemy units can reach own ArchSpirit next turn
|
||
└── HeuristicDecisionEngine.cs — greedy loop with mistake injection
|
||
```
|
||
|
||
**`ScoringFunctions.Evaluate(GameState state, string aiAccountId, AiDifficultyProfile profile) → float`**
|
||
uses the weighted formula defined in §5.2. Weights come from `profile`, allowing different
|
||
difficulties and strategies to push the AI toward different behaviours without changing code.
|
||
|
||
**`HeuristicDecisionEngine.ComputeTurn(AiTurnContext ctx) → IReadOnlyList<AiAction>`**:
|
||
```
|
||
1. Draw (always)
|
||
2. Greedy loop:
|
||
a. candidates = ActionCandidateGenerator.All(ctx)
|
||
b. for each candidate: score = ScoringFunctions.Evaluate(Simulate(state, candidate))
|
||
c. best = argmax(score)
|
||
d. if best.score <= current score AND no mandatory actions remain: break
|
||
e. apply MistakeRate: with probability MistakeRate, replace best with random candidate
|
||
f. append best to plan; update ctx with simulated state
|
||
3. AiEndTurnAction
|
||
```
|
||
|
||
`Simulate(state, action)` calls `GameEngine.Draw / MoveUnit / Attack / ChannelCard` etc.
|
||
directly (same pure static methods — no DB, no side effects) to get the post-action state for
|
||
scoring. This is cheap: `GameEngine` is designed to be called this way.
|
||
|
||
**`AiDifficultyProfiles`** now defines full profiles for 1–5:
|
||
- Difficulty 1: `EngineType = "Random"`, `MistakeRate = 1.0`
|
||
- Difficulty 2: `EngineType = "Heuristic"`, `MistakeRate = 0.60`
|
||
- Difficulty 3: `EngineType = "Heuristic"`, `MistakeRate = 0.40`
|
||
- Difficulty 4: `EngineType = "Heuristic"`, `MistakeRate = 0.25`
|
||
- Difficulty 5: `EngineType = "Heuristic"`, `MistakeRate = 0.10`
|
||
|
||
Strategy weight overlays (Aggressive, Control, etc.) are applied on top of the difficulty profile
|
||
via `AiDifficultyProfile.WithStrategy(strategy)` — a `with`-expression that adjusts weights.
|
||
|
||
**DI wiring**:
|
||
```csharp
|
||
services.AddTransient<HeuristicDecisionEngine>();
|
||
```
|
||
|
||
**Done when**: manual playtesting confirms:
|
||
- Difficulty 2 AI makes obviously suboptimal moves ~half the time
|
||
- Difficulty 5 AI consistently attacks low-HP units first, channels Spirits to relevant affinity
|
||
tiles, and does not leave its ArchSpirit adjacent to enemy attackers without blocking
|
||
- Difficulty 5 AI wins > 60% of games against Difficulty 1 AI in a 100-game self-play run
|
||
(run via a temporary test harness calling `GameEngine` directly in a console test)
|
||
|
||
---
|
||
|
||
### Phase 3.1 — AI Internal ELO Tracking
|
||
|
||
**Goal**: Record win/loss outcomes for AI accounts in a separate `AiEloRecord` table.
|
||
This data is used for calibration in later phases and is never surfaced to players.
|
||
|
||
**Migration**: create `AiEloRecord` table (see §11.2).
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Tracking/
|
||
└── AiEloService.cs — records outcome, updates AiEloRecord after each AI game ends
|
||
```
|
||
|
||
**`AiEloService`** is called from `AiPlayerSessionManager` when it receives `GameEndedEvent`.
|
||
It identifies which participants were AI accounts, loads their `AiEloRecord`, applies the same
|
||
`GameEngine.ComputeEloDelta` formula used by `FinalizeGameAsync`, and saves.
|
||
|
||
Note: AI accounts also go through `FinalizeGameAsync` for their human-facing `Account.RankScore`
|
||
(since the session uses their real account ID). The `AiEloRecord` is an **additional** private
|
||
tracker, not a replacement. AI `RankScore` on the `Account` table should be frozen at `0`
|
||
post-game — add a guard in `FinalizeGameAsync`: if `winner.IsAi || loser.IsAi`, skip the
|
||
`identityDb.SaveChangesAsync` ELO adjustment (human's ELO still updates normally).
|
||
|
||
**DI wiring**:
|
||
```csharp
|
||
services.AddScoped<AiEloService>();
|
||
```
|
||
|
||
**Done when**: after an AI game completes, the `ai_elo_records` table has updated win/loss
|
||
counts and an adjusted internal ELO score for the AI account.
|
||
|
||
---
|
||
|
||
### Phase 3.2 — Self-Play Runner
|
||
|
||
**Goal**: Build an in-memory AI-vs-AI game runner for data generation and engine benchmarking.
|
||
Runs entirely via `GameEngine` static methods — no DB writes, no network, no handlers. Pure
|
||
computation. Used by Phase 3.3 (data export) and for validating engine improvements.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Training/
|
||
└── SelfPlayRunner.cs — runs one in-memory AI-vs-AI game, returns outcome
|
||
```
|
||
|
||
**`SelfPlayRunner.RunGameAsync(AiDifficultyProfile p1, AiDifficultyProfile p2, GameRules rules) → SelfPlayResult`**:
|
||
1. Build two `AiTurnContext` instances with a shared `GameState` (initialized via `GameEngine.Initialize`)
|
||
2. Alternate turns: `decisionEngine.ComputeTurn(ctx)` → apply each action via `GameEngine.*`
|
||
3. After `GameEngine.EndTurn` returns `(state, gameOver: true)`, return `SelfPlayResult { WinnerSeat, TurnCount, FinalState }`
|
||
4. No delays, no DB, no NATS — pure CPU
|
||
|
||
**`SelfPlayOrchestrator`** wraps this in a batch loop:
|
||
```csharp
|
||
public async Task<SelfPlayBatchResult> RunBatchAsync(int numGames, int difficulty, CancellationToken ct)
|
||
```
|
||
Runs games in parallel via `Task.WhenAll` (configurable concurrency limit). Reports
|
||
win counts, average turn counts, and game records for export.
|
||
|
||
**Admin API** in `SOR.Admin`:
|
||
- `POST /admin/ai/self-play/start { numGames, difficulty }` — kicks off a background batch
|
||
- `GET /admin/ai/self-play/status` — returns progress (games completed / total, win rates)
|
||
|
||
**Done when**: a 100-game self-play batch completes between two Difficulty 5 heuristic AIs
|
||
in under 30 seconds, with a win rate between 45–55% (roughly equal opponents), confirming
|
||
the runner produces valid complete games.
|
||
|
||
---
|
||
|
||
### Phase 3.3 — Training Data Export
|
||
|
||
**Goal**: Export human game replays and self-play results as structured JSONL, ready for
|
||
offline feature extraction and model training.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Training/
|
||
├── GameReplayExporter.cs — reads GameActionLog rows, emits training samples
|
||
├── FeatureExtractor.cs — GameState → float[] feature vector
|
||
└── TrainingDataWriter.cs — writes JSONL to disk, one record per action taken
|
||
```
|
||
|
||
**`TrainingRecord`** (serialized to JSONL):
|
||
```csharp
|
||
public record TrainingRecord(
|
||
string SessionId,
|
||
string ActorId,
|
||
int TurnNumber,
|
||
string ActionType,
|
||
string ActionPayloadJson,
|
||
string StateFeaturesBase64, // FeatureExtractor output, base64-encoded float[]
|
||
int Outcome); // 1 = this actor won, 0 = lost
|
||
```
|
||
|
||
**`GameReplayExporter`** queries:
|
||
```sql
|
||
SELECT al.*, gs.winner_account_id
|
||
FROM game_action_logs al
|
||
JOIN game_sessions gs ON gs.id = al.game_session_id
|
||
WHERE gs.status = 'Completed'
|
||
AND gs.ended_at > @lastExportedAt
|
||
AND al.action_type NOT IN ('game.ready', 'game.concede')
|
||
ORDER BY al.game_session_id, al.sequence_number
|
||
```
|
||
|
||
For each row, it deserializes the state from `StateJson` (at that point in the log), calls
|
||
`FeatureExtractor.Extract`, and writes a `TrainingRecord`.
|
||
|
||
**Admin API**:
|
||
- `POST /admin/ai/export-replays { sinceDate }` — triggers an export job
|
||
- Output path: configurable via `appsettings.json`, e.g. `"Ai:TrainingDataPath": "/data/training/"`
|
||
|
||
**Done when**: calling the export API on a DB with at least 10 completed games produces a
|
||
valid `.jsonl` file where each line deserializes to a `TrainingRecord` and `StateFeaturesBase64`
|
||
decodes to a float array of length ~990.
|
||
|
||
---
|
||
|
||
### Phase 3.4 — MCTS Engine (Difficulties 6–8)
|
||
|
||
**Goal**: Implement Monte Carlo Tree Search and wire it as the engine for Difficulties 6–8.
|
||
This engine does lookahead — it should noticeably outperform the heuristic engine.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── MCTS/
|
||
├── MctsNode.cs — tree node (state, action, visits, wins)
|
||
├── MctsTree.cs — UCB1 selection + expansion + backpropagation
|
||
├── MctsSimulator.cs — random playout from a node using RandomDecisionEngine
|
||
├── MctsEvaluator.cs — leaf-node board score (delegates to ScoringFunctions)
|
||
└── MonteCarloEngine.cs — IAiDecisionEngine implementation wrapping MctsTree
|
||
```
|
||
|
||
**`MonteCarloEngine.ComputeTurn(AiTurnContext ctx)`**:
|
||
```
|
||
Given timeBudgetMs (from profile):
|
||
1. Root = MctsNode(currentState)
|
||
2. While elapsed < timeBudgetMs AND iterations < maxIterations:
|
||
a. node = Selection(root) — UCB1 traversal
|
||
b. child = Expansion(node) — pick unexplored candidate action
|
||
c. result = MctsSimulator.Playout(child.state, maxDepth)
|
||
d. BackPropagate(child, result) — increment visits and wins up to root
|
||
3. bestChild = root.children.MaxBy(c => c.Visits)
|
||
4. Return bestChild.Action + recurse into bestChild for multi-step plans
|
||
```
|
||
|
||
Simulation uses `SelfPlayRunner` internally (configured for max-speed random play). Because
|
||
`SelfPlayRunner` calls `GameEngine` directly, the playout is very fast — expect 100–500
|
||
simulations per second per thread.
|
||
|
||
**`AiDifficultyProfiles`** entries for 6–8:
|
||
- Difficulty 6: `EngineType = "MCTS"`, `MctsTimeBudgetMs = 500`, `MctsMaxDepth = 3`
|
||
- Difficulty 7: `EngineType = "MCTS"`, `MctsTimeBudgetMs = 1500`, `MctsMaxDepth = 5`
|
||
- Difficulty 8: `EngineType = "MCTS"`, `MctsTimeBudgetMs = 4000`, `MctsMaxDepth = 7`
|
||
|
||
**DI wiring**:
|
||
```csharp
|
||
services.AddTransient<MonteCarloEngine>();
|
||
```
|
||
|
||
**Done when**:
|
||
- A 100-game self-play batch of MCTS-Difficulty-7 vs Heuristic-Difficulty-5 shows MCTS winning
|
||
> 70% of games, confirming meaningful lookahead improvement
|
||
- Per-turn latency for Difficulty 6 is < 600ms measured wall-clock (budget + overhead)
|
||
|
||
---
|
||
|
||
### Phase 3.5 — AI Calibration Job
|
||
|
||
**Goal**: Automated measurement of AI win rates across difficulty tiers to confirm the
|
||
calibration targets from §7.5 are being met. Admin-triggered; results stored for review.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Calibration/
|
||
└── AiCalibrationJob.cs — runs cross-difficulty self-play batches, records results
|
||
```
|
||
|
||
**`AiCalibrationJob.RunAsync(CancellationToken ct)`**:
|
||
- Runs 50-game batches for each adjacent difficulty matchup (1v2, 2v3, ..., 7v8)
|
||
- Records win rates in a new `ai_calibration_runs` table (id, run_at, difficulty_a, difficulty_b, win_rate_a, game_count)
|
||
- Also runs the full heuristic difficulty ladder (1v5, 2v5, 3v5, 4v5) to confirm relative strength
|
||
|
||
**Admin API**:
|
||
- `POST /admin/ai/calibrate` — triggers calibration job
|
||
- `GET /admin/ai/calibrate/history` — returns last N calibration run results
|
||
|
||
**Done when**: calibration completes and the output shows monotonically increasing win rates
|
||
across the difficulty ladder (Difficulty 3 beats Difficulty 2 > 60% of games, etc.).
|
||
|
||
---
|
||
|
||
### Phase 4.1 — Feature Extractor & Training Pipeline Validation
|
||
|
||
**Goal**: Finalize `FeatureExtractor` (already stubbed in Phase 3.3) to produce a stable,
|
||
documented feature vector. Validate it against known game states before the Python training
|
||
pipeline is built against it.
|
||
|
||
**Files to modify:**
|
||
|
||
- `SOR.Ai/Training/FeatureExtractor.cs` — finalize all feature groups per §7.2, ensure
|
||
output length is constant regardless of board size variation (pad or truncate to fixed dims)
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/scripts/ai_training/
|
||
├── requirements.txt — numpy, torch, pyarrow, onnx, onnxruntime
|
||
├── extract_features.py — reads JSONL from Phase 3.3, converts to Parquet
|
||
├── train.py — PyTorch training loop (policy + value heads)
|
||
├── export_onnx.py — exports best checkpoint to ONNX
|
||
└── benchmark.py — runs AiVsAi in ONNX mode, reports win rates
|
||
```
|
||
|
||
These are Python scripts committed to the repo under `Server/scripts/`. They are not part of
|
||
the .NET build. Documentation in `Server/scripts/ai_training/README.md` covers:
|
||
- Environment setup
|
||
- How to point scripts at exported JSONL data
|
||
- Expected training time per epoch
|
||
- How to validate the ONNX output shape matches what `NeuralDecisionEngine` expects
|
||
|
||
**Done when**: `extract_features.py` reads a `.jsonl` file from Phase 3.3 and writes a
|
||
`.parquet` file; `train.py` runs at least 1 epoch without error and outputs a `.pt` checkpoint;
|
||
`export_onnx.py` produces an `.onnx` file with the expected input/output shape.
|
||
|
||
---
|
||
|
||
### Phase 4.2 — Neural Decision Engine (Difficulties 9–10)
|
||
|
||
**Goal**: Wire ONNX model inference into the server as `NeuralDecisionEngine`. This phase
|
||
requires a trained model from Phase 4.1 to be useful, but the code can be written and tested
|
||
with a randomly-initialized model first.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Engine/
|
||
└── NeuralDecisionEngine.cs — IAiDecisionEngine wrapping OnnxRuntime inference
|
||
```
|
||
|
||
**`NeuralDecisionEngine`**:
|
||
- Loads `{AiTrainingDataPath}/models/sor-ai-v{N}.onnx` at construction
|
||
- `ComputeTurn(ctx)`:
|
||
1. `float[] features = FeatureExtractor.Extract(ctx.State, ctx.AiAccountId)`
|
||
2. Run ONNX session inference → `policyLogits[]`, `valueScore`
|
||
3. Generate `ActionCandidateGenerator.All(ctx)`
|
||
4. Map candidates to policy indices; take softmax
|
||
5. Pick action with highest policy score where value doesn't drop below threshold
|
||
6. Repeat until `AiEndTurnAction`
|
||
|
||
**Hot-reload API**:
|
||
- `POST /admin/ai/reload-model { version: N }` — `NeuralDecisionEngine.ReloadModel(version)`
|
||
swaps the ONNX session without restart. Uses a read-write lock so in-flight turns complete
|
||
before the swap.
|
||
|
||
**`AiDifficultyProfiles`** for 9–10:
|
||
- Difficulty 9: `EngineType = "Neural"`, inference timeout 200ms, fallback to MCTS-7 if model not loaded
|
||
- Difficulty 10: `EngineType = "Neural"`, beam search (top-3 policy candidates, pick highest value), 500ms
|
||
|
||
**Package**: add `Microsoft.ML.OnnxRuntime` to `SOR.Ai.csproj` via `Directory.Packages.props`
|
||
(using the existing central package version management pattern).
|
||
|
||
**DI wiring**:
|
||
```csharp
|
||
services.AddSingleton<NeuralDecisionEngine>(); // singleton: ONNX session is expensive to load
|
||
```
|
||
|
||
**Done when**: `NeuralDecisionEngine` runs inference without exception (even with a
|
||
randomly-initialized model) and produces a legal sequence of `AiAction`s. The hot-reload API
|
||
swaps the model file and subsequent turns use the new model.
|
||
|
||
---
|
||
|
||
### Phase 5.1 — Game-Over Handling & ELO Guard
|
||
|
||
**Goal**: Ensure that when an AI is eliminated or the game ends, AI sessions are properly
|
||
cleaned up and AI ELO adjustments are skipped on the human-facing `Account.RankScore`.
|
||
Also handle the edge case where an AI is eliminated mid-game (FFA/team games).
|
||
|
||
**Files to modify:**
|
||
|
||
- `SOR.Game/Handlers/GameHandlerBase.cs` `FinalizeGameAsync` — add guard:
|
||
```csharp
|
||
if (!winner.IsAi) { winner.RankScore += winnerDelta; }
|
||
if (!loser.IsAi) { loser.RankScore = Math.Max(0, loser.RankScore - loserDelta); }
|
||
```
|
||
Same guard for `FinalizeMultiPlayerGameAsync`.
|
||
OP rewards (`OriginPoints`) are also withheld for AI accounts (they never show a balance).
|
||
|
||
- `SOR.Ai/Core/AiPlayerSessionManager.cs` — on `GameEndedEvent`, cancel all `AiPlayerSession`
|
||
CancellationTokens for that session and remove from the dictionary
|
||
|
||
- `SOR.Game/Handlers/GameHandlerBase.cs` `PushStateToPlayersAsync` — AI player IDs should
|
||
**not** receive Redis push (they have no WebSocket subscriber). Add filter:
|
||
`allIds.Where(pid => !aiRegistry.IsAi(pid))` before pushing. This avoids wasted Redis
|
||
publishes to queues nobody reads.
|
||
|
||
**Done when**: completing a human-vs-AI game does not change the AI account's `RankScore`
|
||
and does not trigger ELO/OP changes for the AI in the identity DB; the human's stats update
|
||
correctly; Redis push is not sent to the AI account ID.
|
||
|
||
---
|
||
|
||
### Phase 5.2 — Triggered Ability Handling for AI
|
||
|
||
**Goal**: Handle `game.ability.triggered_target_request` pushes for AI accounts. When an
|
||
ability fires that needs manual target selection, the push currently goes to the triggering
|
||
player's Redis channel — if that player is AI, nobody reads it and the game stalls.
|
||
|
||
**Files to modify:**
|
||
|
||
- `SOR.Game/Handlers/GameHandlerBase.cs` `PushStateToPlayersAsync` — after pushing the
|
||
`triggered_target_request`, check if `pending.ActorId` is an AI account. If so, instead
|
||
of pushing to Redis, call `AiTriggeredTargetResolver.ResolveAsync(pending, state, ct)` directly.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Engine/
|
||
└── AiTriggeredTargetResolver.cs — picks targets for triggered abilities
|
||
```
|
||
|
||
**`AiTriggeredTargetResolver.ResolveAsync`** reads the pending action's target requirements
|
||
(from `PendingTriggeredTarget.ActionsJson`) and picks targets using the same heuristic scoring
|
||
as the main decision engine — prefer targets that maximize board score. Falls back to a random
|
||
valid target if scoring is too expensive.
|
||
|
||
Submits the selection via `AiAuthenticatedConnection` + `game.triggered_target` message,
|
||
identical to how a human client would respond.
|
||
|
||
**Done when**: a game where the AI has a card with a triggered target-selection ability
|
||
completes without stalling. Verify with a specific card/ability known to trigger this path.
|
||
|
||
---
|
||
|
||
### Phase 5.3 — Adaptive Difficulty
|
||
|
||
**Goal**: Allow the system to auto-suggest (or auto-adjust) AI difficulty based on a player's
|
||
recent win rate against AI, so new players aren't stuck on a difficulty that's too hard, and
|
||
veteran players aren't bored on one that's too easy.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Adaptive/
|
||
└── AiDifficultyAdvisor.cs — computes recommended difficulty from recent game history
|
||
```
|
||
|
||
**`AiDifficultyAdvisor.GetRecommendedDifficultyAsync(Guid humanAccountId, CancellationToken ct) → int`**:
|
||
- Queries last 20 completed AI games for `humanAccountId` from `game_sessions` where any
|
||
participant `IsAi = true`
|
||
- Computes human win rate
|
||
- If win rate > 70%: recommend current + 1 (up to 10)
|
||
- If win rate < 30%: recommend current - 1 (down to 1)
|
||
- Otherwise: return current difficulty
|
||
|
||
**Client API**: `GET /game/ai/recommended-difficulty` — returns `{ recommendedDifficulty: N }`.
|
||
Called by the client when the custom lobby AI configuration panel opens.
|
||
|
||
**Done when**: a player who has won their last 15 AI games gets a `recommendedDifficulty`
|
||
higher than their last used difficulty; a player on a losing streak gets a lower recommendation.
|
||
|
||
---
|
||
|
||
### Phase 5.4 — AI Personality & Lobby Display Polish
|
||
|
||
**Goal**: Add display metadata (personality label, flavor text, avatar) to AI slots in the
|
||
custom lobby. This is purely presentational — no game logic changes.
|
||
|
||
**Files to create:**
|
||
|
||
```
|
||
Server/src/SOR.Ai/
|
||
└── Metadata/
|
||
└── AiPersonalityMetadata.cs — static display data per strategy archetype
|
||
```
|
||
|
||
**`AiPersonalityMetadata`** is a static dictionary keyed by strategy name, providing:
|
||
- `string PersonalityLabel` — e.g. "The Relentless" (Aggressive), "The Architect" (Control)
|
||
- `string FlavorText` — 1-sentence description shown in lobby
|
||
- `string AvatarSlug` — key into asset server for an AI avatar image
|
||
|
||
**New response field**: `GameAddAiResponse` gains `string PersonalityLabel`, `string FlavorText`,
|
||
`string AvatarSlug`. The client shows these in the AI slot card.
|
||
|
||
**Done when**: adding an AI to a lobby returns personality metadata in the response; the custom
|
||
lobby screen (client-side, separate ticket) can display the AI's avatar and personality label.
|
||
|
||
---
|
||
|
||
### Phase 5.5 — Counter-Deck Logic
|
||
|
||
**Goal**: Allow the AI to pick a deck archetype that counters the human opponent's observed
|
||
ArchSpirit, rather than always using its static default deck.
|
||
|
||
**Files to modify / create:**
|
||
|
||
- `SOR.Ai/Lobby/AiSlotAssigner.cs` — when the human's deck is known (lobby `HostDeckId`),
|
||
load the human's ArchSpirit affinity. Apply counter-affinity logic:
|
||
- Fire ArchSpirit → prefer Water-control AI deck
|
||
- Water ArchSpirit → prefer Nature-ramp AI deck
|
||
- etc. (full matrix defined in `CounterAffinityMatrix.cs`)
|
||
|
||
- `SOR.Ai/Lobby/CounterAffinityMatrix.cs` — static `Affinity → Affinity[]` mapping (preferred
|
||
counter affinities in priority order)
|
||
|
||
`AiSlotAssigner.Assign` now takes an optional `Affinity? opponentAffinity` parameter. When
|
||
provided, it queries for AI accounts whose deck's ArchSpirit affinity appears in the counter list
|
||
for that opponent affinity.
|
||
|
||
**Done when**: adding an AI to a lobby where the host has a Fire-affinity ArchSpirit deck
|
||
causes the AI account selected to have a Water-affinity deck (or the closest available match).
|
||
|
||
---
|
||
|
||
## Phase Summary
|
||
|
||
| Phase | Track | Status | Goal | Key Deliverable |
|
||
|---|---|:---:|---|---|
|
||
| 1.1 | A | done | Scaffold | SOR.Ai.csproj builds, wired into Host |
|
||
| 1.2 | A | done | Transport | AiAuthenticatedConnection, AiClientMessage |
|
||
| 1.3 | A | done | DB Schema | Migrations for IsAi, AiSlotsJson, ai_elo_records, ai_calibration_runs, ai_deck_assignments |
|
||
| 1.4 | A | done | AI Accounts | 50 seeded AI accounts at startup (10 tiers x 5 strategies) |
|
||
| 1.5 | A | done | AI Decks | Resolved dynamically from prebuilt starter decks; admin deck-per-difficulty config |
|
||
| 1.6 | A | done | Lobby Handlers | Host can add/remove/configure AI in lobby (server handlers + client UI) |
|
||
| 1.7 | A | done | Session Manager | AI auto-sends game.ready, sessions tracked |
|
||
| 2.1 | B | done | Turn Pipeline | AI takes turns end-to-end |
|
||
| 2.2 | B | done | Placement | AI places ArchSpirit in Placement phase |
|
||
| 2.3 | B | done | Random Engine | Difficulty 1 plays legal random game end-to-end |
|
||
| 2.4 | B | done | Candidate Gen | All legal moves enumerated (draw/channel/move/attack/sacrifice/ascend) |
|
||
| 2.5 | B | done | Heuristic Engine | Difficulties 2-5 with weighted scoring and mistake injection |
|
||
| 3.1 | C | done | AI ELO | Separate ai_elo_records table; FinalizeGameAsync guards with IsAi |
|
||
| 3.2 | C | done | Self-Play | In-process SelfPlayOrchestrator, admin calibration page |
|
||
| 3.3 | C | done | Data Export | GameReplayExporter writes JSONL; admin export UI |
|
||
| 3.4 | C | done | MCTS Engine | UCT tree search for Difficulties 6-8 (2-4s budget) |
|
||
| 3.5 | C | done | Calibration | AiCalibrationJob pairwise runs; ai_calibration_runs table |
|
||
| 4.1 | D | done | Feature Extractor | FeatureExtractor 1024-float vector; matches Python training contract |
|
||
| 4.2 | D | done | Neural Engine | NeuralDecisionEngine MCTS + ONNX leaf eval; hot-swap via admin |
|
||
| 4.3 | D | done | Training Pipeline | tools/train_neural.py PyTorch MLP -> ONNX; tools/README.md workflow docs |
|
||
| 4.4 | A | done | Client AI UI | Lobby Add AI Opponent button with difficulty (D1-D10) and strategy picker |
|
||
| 5.1 | E | TODO | Active Abilities | AI generates AiActivateAbilityAction candidates and executes active abilities |
|
||
| 5.2 | E | TODO | Triggered Targets | AI resolves ability target-selection without stalling |
|
||
| 5.3 | E | TODO | Adaptive Difficulty | Recommended difficulty API based on human ELO rank |
|
||
| 5.4 | E | TODO | Personality | Display metadata, avatars, flavor text per strategy archetype |
|
||
| 5.5 | E | TODO | Counter-Deck | AI selects counter-affinity deck vs human opponent |
|
||
| 5.6 | E | TODO | Trained Model | Run self-play -> export -> train cycle to produce initial model.onnx for D9-D10 |
|
||
|
||
---
|
||
|
||
---
|
||
|
||
## Remaining Work (Phases 5.x)
|
||
|
||
The following phases are not yet implemented. They are ordered by recommended priority.
|
||
|
||
---
|
||
|
||
### Phase 5.1 — Active Ability Support
|
||
|
||
**Gap**: `ActionCandidateGenerator` does not generate `AiActivateAbilityAction` candidates.
|
||
The action type is defined in `IAiDecisionEngine.cs` but never produced, so the AI never
|
||
uses unit active abilities regardless of difficulty.
|
||
|
||
**Files to create/modify**:
|
||
- `SOR.Ai/Heuristics/ActionCandidateGenerator.cs` — add `ActiveAbilities(ctx)` method that
|
||
iterates `aiPlayer.Field`, checks each unit`s `Abilities` list for `CanActivate == true`
|
||
and `CurrentCooldown == 0`, and yields `AiActivateAbilityAction(unitInstanceId, abilityIndex)`
|
||
- `SOR.Ai/Heuristics/HeuristicDecisionEngine.cs` — add `AiActivateAbilityAction` case to
|
||
`ApplyAction` calling `GameEngine.ActivateAbility`
|
||
- `SOR.Ai/Training/SelfPlayRunner.cs` — same `ApplyAction` extension
|
||
|
||
**Done when**: a unit with a 0-cooldown active ability uses it during AI turns.
|
||
|
||
---
|
||
|
||
### Phase 5.2 — Triggered Target Selection
|
||
|
||
**Gap**: Some game effects require target selection mid-turn (triggered abilities, on-play
|
||
effects with target prompts). The current AI pipeline submits the initial action but has no
|
||
mechanism to respond to a follow-up target-selection request from the server.
|
||
|
||
**Files to create/modify**:
|
||
- `SOR.Ai/Core/AiPlayerSession.cs` — after submitting each action, check for a
|
||
`game.target_required` push and respond with `AiTargetSelectionAction`
|
||
- `SOR.Ai/Heuristics/TargetSelector.cs` (new) — given a list of valid target candidates,
|
||
pick the best target using heuristic scoring (prefer highest-threat enemy, prefer own
|
||
lowest-HP unit for healing, etc.)
|
||
- `SOR.Ai/Engine/IAiDecisionEngine.cs` — optionally extend with a `SelectTarget` method
|
||
so MCTS/Neural engines can participate in target selection
|
||
|
||
**Done when**: an AI playing a card that requires target selection completes the full
|
||
play-then-target flow without stalling the game.
|
||
|
||
---
|
||
|
||
### Phase 5.3 — Adaptive Difficulty API
|
||
|
||
**Goal**: expose an endpoint that recommends a difficulty tier for a new human player based on
|
||
their ELO rank, so the client can suggest an appropriate starting difficulty.
|
||
|
||
**Files to create/modify**:
|
||
- `SOR.Ai/Handlers/GetRecommendedDifficultyHandler.cs` (new) — message type
|
||
`game.ai.recommended_difficulty`; returns difficulty 1-10 based on `Account.RankScore`
|
||
mapped against calibration win-rate data in `ai_calibration_runs`
|
||
- `SOR.Admin/Components/Pages/Ai/AiCalibrationPage.razor` — display recommended-difficulty
|
||
mapping table derived from calibration results
|
||
|
||
**Done when**: a player with ELO 1400 gets recommended D5-D6; a player with ELO 800 gets D2-D3.
|
||
|
||
---
|
||
|
||
### Phase 5.4 — AI Personality & Display
|
||
|
||
**Goal**: give each AI strategy archetype a display name, avatar, and flavor text so they feel
|
||
like distinct opponents rather than `Balanced AI (Adept)`.
|
||
|
||
**Files to create/modify**:
|
||
- `SOR.Ai/Seeding/AiPersonality.cs` (new) — static record per (difficulty, strategy):
|
||
display name, short bio, avatar asset key
|
||
- `SOR.Ai/Handlers/GameAddAiHandler.cs` — include personality fields in
|
||
`GameAddAiResponse` and `CustomLobbyAiSlotsChangedPush`
|
||
- Client `lobby_room_screen.gd` — render avatar + bio in guest slot when AI is present
|
||
- `SOR.Admin/Components/Pages/Ai/AiEloPage.razor` — show avatar next to AI ELO rows
|
||
|
||
**Done when**: each of the 50 AI accounts has a distinct portrait visible in the lobby room.
|
||
|
||
---
|
||
|
||
### Phase 5.5 — Counter-Deck Selection
|
||
|
||
**Goal**: when a host adds an AI opponent, automatically select an AI account whose deck
|
||
affinity counters the host`s ArchSpirit affinity, making the AI a more interesting opponent.
|
||
|
||
**Files to create/modify**:
|
||
- `SOR.Ai/Lobby/CounterAffinityMatrix.cs` (new) — static `Affinity -> Affinity[]` mapping
|
||
(preferred counter affinities in priority order for each affinity)
|
||
- `SOR.Ai/Lobby/AiSlotAssigner.cs` — add `opponentAffinity` parameter; prefer AI accounts
|
||
whose active deck`s ArchSpirit affinity appears in the counter list
|
||
- `SOR.Ai/Handlers/GameAddAiHandler.cs` — resolve host`s deck affinity from
|
||
`CollectionDb`, pass to `AiSlotAssigner`
|
||
|
||
**Done when**: adding an AI to a lobby where the host has a Fire-affinity deck causes the AI
|
||
to select a Water-affinity account.
|
||
|
||
---
|
||
|
||
### Phase 5.6 — Initial Trained Model
|
||
|
||
**Goal**: produce and deploy the first real `model.onnx` so D9-D10 use neural evaluation
|
||
instead of the heuristic fallback.
|
||
|
||
**Steps** (not a code change — operational work):
|
||
|
||
1. Run `AiCalibrationJob.RunAllPairsAsync` with `gameCount = 500` per pair.
|
||
2. Export training data from admin portal to `/var/sor/training/data.jsonl`.
|
||
3. Train: `python tools/train_neural.py --data data.jsonl --out model-v1.onnx --epochs 100`
|
||
4. Copy `model-v1.onnx` to path configured in `Ai:NeuralModelPath`.
|
||
5. Admin -> AI -> Neural Model -> Hot-swap Model.
|
||
6. Run calibration again; confirm D9 win rate vs D8 > 60%.
|
||
|
||
**Done when**: admin neural model page shows `Loaded` and D9/D10 calibration win rates
|
||
are measurably higher than D8.
|
||
|
||
---
|
||
|
||
## Key Design Decisions & Rationale
|
||
|
||
| Decision | Rationale |
|
||
|---|---|
|
||
| AI goes through full handler pipeline | Ensures AI actions are fully validated, logged, and pushed to humans exactly as human actions are. No code duplication, no drift. |
|
||
| AI accounts are real DB rows | Allows lobby, session, and replay systems to work unmodified. AI is a player, not a special case. |
|
||
| Heuristic engine first | Fastest path to a playable feature. Gives training data. MCTS and Neural can replace it later with no API changes. |
|
||
| ONNX Runtime for inference | Train in Python (PyTorch ecosystem, mature ML tooling), run in .NET (production server). Standard interop pattern. |
|
||
| Self-play for training data | Human game data is sparse and biased toward popular strategies. Self-play explores the full strategy space faster. |
|
||
| In-process action submission | No network hop, no extra infra. AI turn latency is controlled purely by think-time delay, not transport. |
|
||
| Per-strategy deck seeding | Strategy is only meaningful if the AI's deck supports it. A control AI with an aggro deck would play incoherently. |
|
||
| Mistake injection for difficulty | Easier to implement and tune than reducing search depth for Heuristic AI. More realistic too — low-skill AIs play wrong, not just slowly. |
|
||
|
||
---
|
||
|
||
## File: Server/initial-plan.md
|
||
|
||
# SOR Server Architecture — Initial Plan
|
||
|
||
## Overview
|
||
|
||
The server is composed of purpose-built services communicating over an internal TCP network. Clients connect exclusively through the Gateway via WebSocket. All inter-service communication is TCP-based.
|
||
|
||
**Scale target**: hundreds of thousands of concurrent users. Every service is designed for horizontal scaling from the start.
|
||
|
||
---
|
||
|
||
## Tech Stack
|
||
|
||
All components are open-source and self-hosted. No licensing fees.
|
||
|
||
| Component | Choice | License |
|
||
|---|---|---|
|
||
| **Programming language** | **C# 12 (.NET 8)** | MIT |
|
||
| Primary database | PostgreSQL | PostgreSQL License |
|
||
| Session store / live game state / rankings | Redis (Community Edition) | BSD 3-Clause |
|
||
| Async event bus (inter-service fan-out) | NATS | Apache 2.0 |
|
||
| Synchronous inter-service RPC | gRPC + Protobuf | Apache 2.0 |
|
||
| Container orchestration | Kubernetes | Apache 2.0 |
|
||
| Client transport | WebSocket | Open standard |
|
||
| Object storage (CDN origin) | Ceph (via RADOSGW S3 API) | LGPL v2.1 |
|
||
| Chat cold storage (archive) | Remote MySQL (third-party hosted, unlimited storage deal) | N/A |
|
||
| ORM | Entity Framework Core + Npgsql | MIT |
|
||
| Logging | Serilog | Apache 2.0 |
|
||
|
||
**Programming architecture** (repo structure, service patterns, DI, config, error handling, testing): see `Server/architecture.md`.
|
||
|
||
**Payment processing** is the one mandatory third-party service. Accepting real-money card payments requires PCI DSS compliance and direct card network relationships — this cannot be built in-house. Stripe is the recommended processor (per-transaction fee only, no monthly license). The integration will be **implemented but disabled** until real-money features are ready to launch. All other payment handling logic (wallets, currency conversion, transaction records) is built internally in the Bazaar service.
|
||
|
||
---
|
||
|
||
## Topology
|
||
|
||
```
|
||
[ Thick Client ] [ Web Browser ]
|
||
| |
|
||
+-------(WebSocket)------+
|
||
|
|
||
[ GATEWAY ] ←──── Redis Pub/Sub (client push delivery)
|
||
|
|
||
gRPC (sync) + NATS (async fan-out)
|
||
| | | | | | | |
|
||
[AUTH] [GAME] [CHAT] [COLL] [BAZ] [ADMIN] [WEB] [LDRBD]
|
||
| | | | | | | |
|
||
+-------+-------+-------+-------+-------+-------+-------+
|
||
[ PostgreSQL ] [ Redis ] [ NATS ] [ Ceph/CDN ]
|
||
[ MySQL archive (chat cold) ]
|
||
```
|
||
|
||
---
|
||
|
||
## Shared Infrastructure
|
||
|
||
### Redis
|
||
Scoped to: session management, client push delivery, live game state, and runtime config. Not used for inter-service event routing (that is NATS).
|
||
|
||
- **Session store** — Gateway resolves session tokens on WS connect; cached in-process for the life of that connection after first lookup
|
||
- **Client push (Pub/Sub)** — The final hop from services to connected clients. Services publish to Redis channels; each Gateway instance subscribes to channels for its connected clients and delivers over WebSocket. This is the only pub/sub use of Redis.
|
||
- **Active game state** — Hot game data for sub-millisecond read/write; flushed to PostgreSQL on game completion
|
||
- **Live leaderboard rankings** — Redis Sorted Sets for O(log N) rank reads and writes
|
||
- **Runtime config / feature flags** — Admin writes; all services read on startup and poll periodically
|
||
|
||
### NATS
|
||
Async event bus for all inter-service fan-out. Chosen over RabbitMQ for its lower latency, simpler operations, and native support for both pub/sub and request/reply patterns in one system. Apache 2.0.
|
||
|
||
- **Async fan-out** — One service publishes an event (e.g., game ended, purchase completed); multiple services subscribe independently without the publisher needing to know its consumers
|
||
- **Request/reply** — Used where synchronous responses are needed but gRPC is too heavy (e.g., lightweight internal queries)
|
||
- **JetStream** — NATS persistence layer; used for events that must survive a service restart (e.g., currency grants, match result recording)
|
||
|
||
Separation of concerns:
|
||
- **NATS** — service-to-service async events
|
||
- **Redis Pub/Sub** — final delivery from services to connected WebSocket clients (via Gateway)
|
||
- **gRPC** — direct synchronous service-to-service RPC
|
||
|
||
### PostgreSQL
|
||
Chosen over MySQL for this project. Key reasons: superior JSONB support (card/ability definitions map naturally to structured JSON), better concurrency under write-heavy load (MVCC), cleaner window functions for leaderboard and analytics queries, and stronger standards compliance as schema complexity grows.
|
||
|
||
Each service owns a dedicated schema. No cross-service DB queries — services talk to each other via TCP only.
|
||
|
||
| Service | Schema | Contents |
|
||
|-------------|---------------|----------|
|
||
| Auth | `auth` | Users, credentials, OAuth tokens |
|
||
| Collection | `collection` | Card inventory, decks |
|
||
| Bazaar | `bazaar` | Shop listings, marketplace, transactions, currency ledger |
|
||
| Game | `game` | Match history, ratings, replays |
|
||
| Chat | `chat` | Active messages (30-day hot window; archived to MySQL after) |
|
||
| Admin | `admin` | Audit logs, admin accounts, config history |
|
||
| Content | `content` | Card definitions, asset metadata, CDN asset references |
|
||
| Leaderboard | `leaderboard` | Historical ranking snapshots, season records |
|
||
|
||
---
|
||
|
||
## Services
|
||
|
||
---
|
||
|
||
### Gateway
|
||
|
||
**Role**: Single point of entry for all client connections (thick client and web browser).
|
||
|
||
**Transport**: WebSocket inbound from clients; TCP outbound to internal services.
|
||
|
||
**Stateful/Stateless**: Hybrid — *stateful per connection, stateless per session*.
|
||
|
||
WebSocket connections are bound to a specific TCP socket on a specific machine — you cannot move an open connection. The Gateway is therefore inherently stateful in that it holds open sockets. However, all session state lives in Redis, not in the Gateway process.
|
||
|
||
**How it works**:
|
||
- Each instance maintains an in-process map: `connectionId → { userId, sessionToken, subscriptions }`
|
||
- On WS handshake: resolves session token against Redis → caches result in-process for the life of that connection. No Redis round-trip on subsequent messages.
|
||
- On client disconnect + reconnect: any Gateway instance can pick them up by re-resolving their session token from Redis.
|
||
- For server push: services publish to Redis pub/sub channels; each Gateway instance subscribes to channels for its currently connected clients and delivers events over WebSocket.
|
||
|
||
**Responsibilities**:
|
||
- Authenticate and authorize incoming connections via session token
|
||
- Route client messages to the correct downstream service
|
||
- Subscribe to Redis pub/sub; deliver pushed events to connected clients
|
||
- Heartbeat / connection keepalive
|
||
- Rate limiting at the connection level
|
||
- Relay admin commands from privileged clients to the Admin service
|
||
|
||
**Scaling**:
|
||
Horizontal. Load balancer uses session-affinity (sticky sessions) for the WebSocket upgrade — once a connection is established it stays on that instance for its lifetime. New connections are distributed across instances freely. Gateway instances carry no durable business state; scaling in/out only affects which instance holds active sockets. Clients reconnect transparently via Redis session resolution.
|
||
|
||
**Database**: Redis only (no direct PostgreSQL access).
|
||
|
||
---
|
||
|
||
### Auth
|
||
|
||
**Role**: Login, registration, account management, OAuth (social login providers).
|
||
|
||
**Stateless**: Pure request/response. No persistent in-process state.
|
||
|
||
**Responsibilities**:
|
||
- Register new accounts (email + password)
|
||
- Login: validate credentials → issue session token → write to Redis with TTL
|
||
- OAuth: redirect to provider → callback → create or link account → issue session token
|
||
- Account management: email change, password reset, display name, profile
|
||
- Token refresh and revocation
|
||
- Internal endpoint: validate session token (called by Gateway on WS handshake)
|
||
|
||
**Token format**: Opaque session tokens. Full session state lives in Redis (userId, permissions, TTL). Tokens are immediately revocable by deleting the Redis key. No JWT — avoids revocation complexity for a server-authoritative game where sessions must be killable instantly (ban, forced logout, admin action).
|
||
|
||
**Scaling**: Fully stateless. Horizontal with no affinity requirement.
|
||
|
||
**Database**: PostgreSQL (`auth`), Redis (session tokens with TTL).
|
||
|
||
---
|
||
|
||
### Game
|
||
|
||
**Role**: All game sessions — matchmaking, game state, turn processing, win conditions, ratings.
|
||
|
||
**Note**: The Game service is the most complex and robust service in the system. A full design draft will be done separately once all other services are spec'd.
|
||
|
||
**Stateful**: Active sessions carry state. Hot state lives in Redis; completed game data flushed to PostgreSQL.
|
||
|
||
**Responsibilities** (high-level):
|
||
- Matchmaking queue and pairing
|
||
- Initialize game sessions; deal opening hands; set up board state
|
||
- Validate and process player actions (move, attack, channel, use ability, end turn)
|
||
- Apply game rules and resolve effects (driven by the ability/effect engine defined in context-files)
|
||
- Publish state delta events to Redis pub/sub → Gateway delivers to players
|
||
- Detect end-of-game; compute ratings; flush to PostgreSQL
|
||
- Reconnect handling: send current state snapshot to reconnecting player
|
||
|
||
**Scaling**: TBD in the Game service design draft.
|
||
|
||
**Database**: Redis (active game state, matchmaking queue), PostgreSQL (`game` — match history, ratings, replays).
|
||
|
||
---
|
||
|
||
### Chat
|
||
|
||
**Role**: Real-time messaging — lobby, in-game chat, direct messages, and future guild/party channels.
|
||
|
||
**Stateless processing**: Chat service receives messages, validates, persists, publishes to Redis pub/sub. Delivery is handled by Gateway.
|
||
|
||
**Responsibilities**:
|
||
- Channel management (create, join, leave, list)
|
||
- Message routing via Redis pub/sub
|
||
- Message persistence: all messages written to PostgreSQL for the duration of the session; retained for admin review and moderation purposes
|
||
- Moderation: profanity filter hooks, mute, ban (enforced at write time)
|
||
|
||
**Persistence policy**:
|
||
- Messages written to PostgreSQL (`chat`) on send
|
||
- **30-day hot window**: messages older than 30 days are archived out of PostgreSQL
|
||
- **Cold archive**: archived messages moved to the remote third-party MySQL instance (unlimited storage); kept indefinitely for moderation and legal review
|
||
- Primary use: if a player is reported, staff pulls the session log from hot or cold storage as needed
|
||
- Retention and GDPR/privacy policy to be defined before public launch
|
||
|
||
**Scaling**: Fully stateless. Horizontal. Pub/sub fanout is handled by Redis; Chat service only processes and routes.
|
||
|
||
**Database**: Redis (pub/sub), PostgreSQL (`chat` — messages, channels).
|
||
|
||
---
|
||
|
||
### Collection
|
||
|
||
**Role**: Player card collection and deck management.
|
||
|
||
**Stateless**: Pure request/response.
|
||
|
||
**Responsibilities**:
|
||
- Read player card inventory
|
||
- Create, update, delete decks
|
||
- Validate deck legality (card count limits, banned list, format restrictions)
|
||
- Grant or revoke cards (called by Bazaar on purchase; by Admin for manual grants)
|
||
|
||
**Scaling**: Fully stateless. Horizontal.
|
||
|
||
**Database**: PostgreSQL (`collection` — card_inventory, decks, deck_cards).
|
||
|
||
---
|
||
|
||
### Bazaar
|
||
|
||
**Role**: In-game shop and player-to-player marketplace.
|
||
|
||
**Stateless**: Request/response with transactional DB operations for consistency.
|
||
|
||
**Currency model**:
|
||
Two currency types:
|
||
- **Earned currency (soft)** — gained through gameplay (wins, quests, events). Spent in shop and marketplace.
|
||
- **Real-money currency (hard)** — purchased with real money via Stripe. Spent directly in shop, or converted to earned currency at a defined rate.
|
||
|
||
Players can: spend earned currency, spend hard currency, or purchase earned currency with hard currency (real money → earned conversion). All currency flows are atomic DB transactions with a full ledger for audit.
|
||
|
||
**Responsibilities**:
|
||
- Shop: fixed-price card and item purchases in both currency types
|
||
- Marketplace: player-to-player listings, bids, buyouts (earned currency only)
|
||
- Real-money purchase flow: initiate Stripe payment → webhook confirms → credit hard currency to player wallet
|
||
- Earned currency purchase: deduct hard currency → credit earned currency (conversion rate configurable by Admin)
|
||
- Transaction history and receipt generation
|
||
- Currency management: all debit/credit operations are atomic PostgreSQL transactions to prevent double-spend
|
||
|
||
**Scaling**: Stateless compute. Database is the coordination point. Read replicas for browsing/search; primary for all transaction writes.
|
||
|
||
**Database**: PostgreSQL (`bazaar` — listings, transactions, currency_ledger, wallets).
|
||
|
||
---
|
||
|
||
### Admin
|
||
|
||
**Role**: Dual-purpose — hosts the admin web dashboard and processes incoming admin commands. Also serves as the card content authoring tool and asset pipeline entry point.
|
||
|
||
**Responsibilities**:
|
||
- **Admin web UI**: internal web application; player management, session visibility, economy metrics, config management
|
||
- **Card builder**: admin UI tool for creating and editing card definitions (stats, abilities, genus, affinity, costs); card data written to the `content` schema via the Content service
|
||
- **Asset management**: upload card art, UI assets, 3D models, and animations directly from the admin UI; assets are pushed to Ceph (CDN origin) and their metadata (filename, CDN URL, card association) recorded in `content`; clients download assets from the CDN
|
||
- **Admin command processing**: privileged client commands relayed by Gateway; validated, executed, and logged
|
||
- **Player actions**: ban, mute, grant/revoke cards, force-end game, system announcements
|
||
- **Config management**: write feature flags and runtime config to Redis
|
||
- **Audit logging**: all admin actions logged with actor, timestamp, and full payload
|
||
|
||
**Access**: NOT publicly routable. Internal network or VPN only. Admin auth is a separate credential layer on top of normal Auth.
|
||
|
||
**Scaling**: Low-traffic. Single instance sufficient initially; stateless and horizontally scalable.
|
||
|
||
**Database**: PostgreSQL (`admin` — audit_logs, admin_users, config_history), Redis (runtime config / feature flags — write side).
|
||
|
||
---
|
||
|
||
### Leaderboard
|
||
|
||
**Role**: Real-time and historical player rankings.
|
||
|
||
**Stateless processing**: Ranking logic is stateless; all ranking state lives in Redis Sorted Sets for live data and PostgreSQL for historical snapshots.
|
||
|
||
**Responsibilities**:
|
||
- Maintain live rankings by multiple dimensions (overall rating, wins, win streak, season rank, etc.)
|
||
- Receive match result events via NATS → update Redis Sorted Sets atomically
|
||
- Serve rank reads: O(log N) lookups from Redis for live rankings
|
||
- Periodic snapshots: flush current standings to PostgreSQL at end of season or on a schedule
|
||
- Expose ranked queries to Web and client (top N, player rank and percentile, nearby players in ranking)
|
||
|
||
**Scaling**: Stateless compute. Redis Sorted Sets handle concurrent ranking updates efficiently. Horizontal scaling of the compute layer behind a load balancer.
|
||
|
||
**Database**: Redis (live Sorted Sets per ranking dimension), PostgreSQL (`leaderboard` — historical snapshots, season records).
|
||
|
||
---
|
||
|
||
### Content
|
||
|
||
**Role**: Canonical store for card definitions and game asset metadata. Serves the card library to clients and the admin card builder.
|
||
|
||
**Stateless**: Pure request/response.
|
||
|
||
**Responsibilities**:
|
||
- Store and serve card definitions (all fields from card-design.md: stats, abilities, genus, affinity, costs, etc.) as structured data
|
||
- Store asset metadata: for each card, the CDN URLs for card art, 3D model, animations, UI elements
|
||
- Serve card library to clients (full card catalog, filterable)
|
||
- Serve individual card definitions to Game service during game session initialization
|
||
- Receive card creation/update calls from Admin card builder; write to `content` schema
|
||
|
||
**Scaling**: Stateless. Horizontal. Card definitions are read-heavy — Redis caching layer in front of PostgreSQL for frequently accessed card data.
|
||
|
||
**Database**: PostgreSQL (`content` — card_definitions, card_assets, asset_metadata). Redis (card definition cache).
|
||
|
||
---
|
||
|
||
### CDN / Asset Pipeline
|
||
|
||
**Role**: Infrastructure layer for storing and delivering all game assets (card art, UI assets, 3D models, animations).
|
||
|
||
This is not a service but an infrastructure component managed through the Admin UI.
|
||
|
||
**How it works**:
|
||
1. Admin uploads asset (art, model, animation) via Admin web UI
|
||
2. Admin service pushes the file to **Ceph** via the RADOSGW S3-compatible API
|
||
3. Admin service writes asset metadata (filename, type, CDN URL, associated card ID) to `content` schema via Content service
|
||
4. CDN layer sits in front of Ceph RADOSGW as the public edge — clients always pull from CDN, never directly from Ceph origin (see Open Questions for CDN edge decision)
|
||
5. Client downloads assets from CDN URLs stored in card definitions; initial sync on game launch, incremental updates on patch
|
||
|
||
**Components**:
|
||
- **Ceph** — Distributed object storage origin. Self-hosted. LGPL v2.1. Object storage exposed via Ceph Object Gateway (RADOSGW) which provides an S3-compatible API — no vendor lock-in. Ceph also supports block and file storage, giving room to expand storage needs without adding new systems.
|
||
- **CDN edge** — Caches and delivers assets globally. Sits in front of Ceph RADOSGW. Options TBD (see Open Questions).
|
||
|
||
**Asset types**:
|
||
- Card art (2D, per card)
|
||
- 3D models and animations (per unit/spirit)
|
||
- UI assets (icons, backgrounds, effects)
|
||
- Audio (TBD)
|
||
|
||
---
|
||
|
||
### Web
|
||
|
||
**Role**: Public-facing game website.
|
||
|
||
**Responsibilities**:
|
||
- Landing page, news, patch notes, update announcements
|
||
- Account creation and management in-browser (calls Auth service)
|
||
- Thick client download links
|
||
- Web client entry point
|
||
- Leaderboard display (calls Leaderboard service)
|
||
- Card library browser (calls Content service — read-only)
|
||
- Lore, media, community links
|
||
|
||
**Stateless**: Static and server-rendered pages. All dynamic data is fetched from internal services — Web holds no data directly.
|
||
|
||
**Deployment**: Built and deployed entirely separately from the server stack. Hosted in its own Kubernetes namespace with no shared deployments. Communicates with backend services through the same Gateway as any other client.
|
||
|
||
**Scaling**: Fully stateless. CDN for static assets. Horizontal for server-rendered pages.
|
||
|
||
**Database**: None. All data via internal service calls.
|
||
|
||
---
|
||
|
||
## Transport Layer
|
||
|
||
| Connection | Protocol | Notes |
|
||
|---|---|---|
|
||
| Client → Gateway | WebSocket | Persistent, full-duplex |
|
||
| Gateway → Services (sync) | gRPC over TCP | Request routing, auth validation |
|
||
| Service → Service (sync) | gRPC over TCP | Direct RPC; schema-defined via Protobuf |
|
||
| Service → Service (async) | NATS | Event fan-out; multiple services can subscribe to one event |
|
||
| Services → Gateway (push) | Redis Pub/Sub | Final delivery hop to connected clients via Gateway subscriptions |
|
||
| Admin → Ceph | HTTP (RADOSGW S3 API) | Asset upload |
|
||
| Client → CDN | HTTPS | Asset download (card art, models, animations) |
|
||
|
||
**Framing**:
|
||
- gRPC uses Protobuf — strongly typed, code-generated, binary. All service contracts defined as `.proto` files and versioned.
|
||
- NATS messages use Protobuf or MessagePack — TBD when service contracts are defined.
|
||
- Game state deltas (high-frequency) may use a compact binary format over NATS if gRPC overhead is measurable at scale.
|
||
|
||
---
|
||
|
||
## Decided
|
||
|
||
| Decision | Choice | Notes |
|
||
|---|---|---|
|
||
| Programming language | C# 12 (.NET 8) | ASP.NET Core for gRPC + WebSocket; EF Core for ORM; see architecture.md |
|
||
| Primary database | PostgreSQL | JSONB, concurrency, analytics; over MySQL |
|
||
| Async event bus | NATS | Lightweight, low-latency, pub/sub + request/reply; Apache 2.0 |
|
||
| Sync inter-service RPC | gRPC + Protobuf | Schema-first, code-generated, binary |
|
||
| Object storage (CDN origin) | Ceph (RADOSGW) | Self-hosted, S3-compatible, LGPL v2.1 |
|
||
| Auth token format | Opaque session tokens in Redis | Instantly revocable; avoids JWT revocation complexity |
|
||
| Currency model | Soft (earned) + Hard (real money) | Real money → earned conversion supported |
|
||
| Payment processing | Stripe (third-party, implemented but disabled) | PCI compliance not DIY-able; enabled when real-money launch is ready |
|
||
| Web client | Full game client via WebSocket | Built separately; own Kubernetes namespace |
|
||
| Chat hot storage | PostgreSQL, 30-day window | Active messages; archived after 30 days |
|
||
| Chat cold archive | Remote MySQL (third-party, unlimited storage) | Long-term audit/moderation storage |
|
||
|
||
---
|
||
|
||
## Open Questions
|
||
|
||
1. **Game service design**: Deferred — will be drafted separately as the most complex service. Sharding strategy, session coordinator, matchmaking design, and reconnect flow all TBD.
|
||
|
||
2. **CDN edge layer**: What sits in front of Ceph RADOSGW for client-facing delivery? Options: self-hosted Nginx with caching, Cloudflare (free tier covers most cases), or BunnyCDN (low cost, high performance). Decision needed before asset pipeline is built.
|
||
|
||
3. **Legal / GDPR / compliance**: See `Shared/legal.md` for all outstanding legal TODOs including GDPR, privacy policy, EULA, TOS, and Stripe compliance requirements.
|
||
|
||
---
|
||
|
||
## File: Shared/context-files/abilities.md
|
||
|
||
# Abilities
|
||
|
||
This file is the canonical reference for the ability and effect system. The same model is used by:
|
||
- Unit abilities (`ArchSpirit` and `Spirit`)
|
||
- `Instinct` card effects
|
||
- `Repentance` card effects
|
||
|
||
The system is designed to be fully data-driven. Every ability, effect, condition, and target is expressible through the schema below — no additional programming required to create new content.
|
||
|
||
---
|
||
|
||
## 1) Ability Structure
|
||
|
||
```
|
||
AbilityDefinition {
|
||
Type: Active | Passive | Aura | Triggered
|
||
ActivationConditions: Condition[] // optional; if any unmet, ability cannot fire
|
||
Actions: Action[]
|
||
|
||
// Active only:
|
||
Cost: CostEntry[]? // see §6.6 in gameplay.md for cost types
|
||
Range: { Min, Max }? // targeting range from source unit, in tiles
|
||
UsesPerTurn: N // default 1
|
||
|
||
// Aura only:
|
||
AuraRange: { Min, Max }
|
||
|
||
// Triggered only:
|
||
TriggerEvent: TriggerEvent // see §8; specifies when the ability fires
|
||
// ActivationConditions handles whether it fires
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 2) Ability Types
|
||
|
||
### 2.1 Active
|
||
|
||
Manually activated by the controlling player.
|
||
|
||
- Default: once per turn. May be increased or decreased by effects.
|
||
- Optional **cost** — any supported cost type (see §6.6 in gameplay.md).
|
||
- Optional **range** — min/max tile distance from source unit to valid targets.
|
||
- Optional **activation conditions** — ability cannot be activated unless all conditions are met.
|
||
- Supports N or more targets via the target selector on each action.
|
||
|
||
### 2.2 Aura
|
||
|
||
Always active while the unit is in play and conditions are met.
|
||
|
||
- Applies effects passively to all valid targets within `AuraRange` (min/max tiles from source).
|
||
- Optional **activation conditions** — if any are unmet, the aura is fully suppressed.
|
||
- No manual activation. No cost.
|
||
- **Instant stat modifiers** (e.g. `ModifyDamage`, `ModifyMP`) apply when a unit enters range and are removed when the unit leaves range or the aura is suppressed.
|
||
- **Per-turn effects** (e.g. `DealDamage`, `Heal`, `DOT`) apply once per turn to each unit currently in range, resolved during the start-of-turn triggers phase for the aura owner's turn. These effects also fire immediately when a unit enters range.
|
||
- **On-exit effects** are not automatic — to fire effects when a unit leaves range, use a companion `Triggered` ability on `OnLeaveAuraRange` (§8.12).
|
||
|
||
### 2.3 Passive
|
||
|
||
Always active while the unit is in play and conditions are met.
|
||
|
||
- No range constraint.
|
||
- Optional **activation conditions** — if any are unmet, the passive is fully suppressed.
|
||
- No manual activation. No cost.
|
||
|
||
### 2.4 Triggered
|
||
|
||
Automatically fires when the trigger condition is met.
|
||
|
||
- Defined by a `TriggerEvent` from the catalog in §8, plus optional state conditions.
|
||
- Fires once per trigger event unless modified by an effect.
|
||
- Not manually activated. No cost.
|
||
|
||
---
|
||
|
||
## 3) Action Model
|
||
|
||
All effect execution — whether from unit abilities, `Instinct` cards, or `Repentance` cards — uses the same Action model.
|
||
|
||
An action is the atomic unit of targeting and effect delivery. An ability contains one or more actions that resolve in sequence. Each action may have its own target, conditions, and effects.
|
||
|
||
```
|
||
Action {
|
||
Target: TargetSelector
|
||
Conditions: Condition[] // optional; if any unmet, this action is skipped
|
||
Effects: Effect[]
|
||
Duration: DurationModel
|
||
}
|
||
```
|
||
|
||
**Duration scope**: The `Duration` field applies to all effects within the action. If two effects in the same action need different durations, split them into separate actions targeting the same target.
|
||
|
||
**Interrupt rule**: All actions within a single ability (or card play) resolve in full sequence before any interrupt window opens. Opponents cannot interrupt between individual actions of the same ability.
|
||
|
||
**Instinct and Repentance**: The `Effects` field on these card types is an `Action[]` using this same model.
|
||
|
||
**ChooseOne**: An ability or card may branch into mutually exclusive effect paths, with the controlling player selecting which branch to take at resolution time.
|
||
|
||
```
|
||
ChooseOne {
|
||
Branches: [
|
||
{ Label: string, Actions: Action[] },
|
||
...
|
||
]
|
||
}
|
||
```
|
||
|
||
`ChooseOne` may appear anywhere an `Action[]` can appear. When reached, the player controlling the source is presented with the branch labels and must select exactly one. Only the selected branch's actions resolve. Conditions on individual actions within a branch still apply normally.
|
||
|
||
Example: "Discard a card from your hand OR pay 2 SP and channel it — all channeling rules apply."
|
||
|
||
---
|
||
|
||
## 4) Target Selector
|
||
|
||
```
|
||
TargetSelector {
|
||
Scope: Hand | Deck | Discard | Battlefield | Player | AnyZone
|
||
Type: Unit | ArchSpirit | Spirit | SpiritToken | Ruin | Tile | Card | Player
|
||
Ownership: Self | Owner | Ally | Enemy | Any | Random
|
||
Count: N | UpToN | All
|
||
Filters: Filter[]
|
||
}
|
||
```
|
||
|
||
- `Unit` — alias for `Spirit | ArchSpirit | SpiritToken`; use when targeting any unit type without restriction
|
||
- `AnyZone` — target a card regardless of which zone it currently occupies
|
||
- `Self` — the source unit itself (see §4.3)
|
||
- `UpToN` — player may select between 0 and N valid targets; fewer than N is valid
|
||
|
||
### 4.1 Unit/Card Filters
|
||
|
||
- `GenusContains(tag)`
|
||
- `AffinityMatches(affinity)`
|
||
- `HealthBelow(N)` / `HealthAbove(N)`
|
||
- `DamageRange(min, max)`
|
||
- `DefenseRange(min, max)`
|
||
- `MPRange(min, max)`
|
||
- `HasFlag(flag)` — e.g., `CanAttack`, `CanMove`, `CanBeSacrificed`
|
||
- `TierIs(N)` — ArchSpirit only; matches a specific tier
|
||
- `IsAdjacentToSource` — target must be adjacent to the source unit
|
||
- `CardTypeIs(type)`
|
||
- `CardSPCostRange(min, max)`
|
||
- `CardSTCostRange(min, max)`
|
||
- `WithinRange(min, max)` — from source unit, in tiles
|
||
- `IsSelf` — matches only the specific unit or card that owns this ability
|
||
|
||
### 4.2 Tile Filters
|
||
|
||
- `TileAffinityMatches(affinity)`
|
||
- `TileIsOccupied(unitType?)`
|
||
- `TileIsUnoccupied`
|
||
- `TileWithinRange(min, max)` — from source unit, in tiles
|
||
- `TileIsAdjacentToUnit(ownership, filter?)` — tile is adjacent to a unit matching the filter
|
||
- `TileIsOnPlayerSide(ownership)` — tile falls within the starting side of the specified player
|
||
- `TileIsInArchSpiritChannelRange(ownership)` — tile is within the channeling range of the specified player's active ArchSpirit
|
||
|
||
### 4.3 Ownership Values
|
||
|
||
- `Self` — the specific unit using the ability (not just any unit the owner controls)
|
||
- `Target` — the entity resolved as this action's target; used to reference the current target in conditions or subsequent chained actions
|
||
- `Owner` — any unit/card controlled by the ability's owner
|
||
- `Ally` — controlled by a teammate (distinct from owner in team modes)
|
||
- `Enemy` — controlled by an opponent
|
||
- `Any` — any player's units/cards
|
||
- `Random` — random selection from valid pool after all other filters apply
|
||
|
||
---
|
||
|
||
### 4.4 Chained Targeting
|
||
|
||
Some abilities need a second target defined relative to a first (e.g., "target an enemy Spirit, then target a tile adjacent to that Spirit"). This is expressed by referencing a prior action's resolved target in a subsequent action's filter.
|
||
|
||
```
|
||
Action 1: { Target: { Scope: Battlefield, Type: Spirit, Ownership: Enemy }, ... }
|
||
Action 2: { Target: { Scope: Battlefield, Type: Tile, Filters: [TileIsAdjacentToUnit(ref: Action1.Target)] }, ... }
|
||
```
|
||
|
||
Actions reference prior resolved targets by index (`Action1.Target`, `Action2.Target`, etc.).
|
||
|
||
---
|
||
|
||
### 4.5 Dynamic Value References
|
||
|
||
Filter parameters and effect amounts may reference runtime values instead of fixed constants:
|
||
|
||
- `Action{N}.Target.{Property}` — a property of the Nth action's resolved target (e.g. `Action1.Target.Affinity`)
|
||
- `Self.{Property}` — a property of the source unit (e.g. `Self.Damage`, `Self.Affinity`)
|
||
- `Self.Owner.ArchSpirit.{Property}` — a property of the source unit's owner's active ArchSpirit (e.g. `Self.Owner.ArchSpirit.Affinity`)
|
||
- `EventData.{Field}` — trigger payload values (see §6.0.2); available in `Triggered` abilities only
|
||
|
||
Dynamic references resolve at the time the filter or effect is evaluated. They may be used in any parameter that accepts a numeric value, an affinity, or a unit/player reference.
|
||
|
||
Example: `TileAffinityMatches(Action1.Target.Affinity)` — restrict tile selection to tiles that match the affinity of the spirit targeted in Action 1.
|
||
|
||
Example: `SetAffinity(Self.Owner.ArchSpirit.Affinity)` — change the target unit's affinity to match the source unit's ArchSpirit.
|
||
|
||
---
|
||
|
||
## 5) Effect Types
|
||
|
||
### 5.1 Stat Modification
|
||
|
||
Applies to `Spirit`, `ArchSpirit`, `SpiritToken`:
|
||
|
||
- `ModifyHealth(amount, target: current | max)` — increase or decrease health
|
||
- `ModifyDefense(amount, target: current | max)` — increase or decrease defense
|
||
- `ModifyDamage(amount)` — increase or decrease damage
|
||
- `ModifyMP(amount, target: current | max)` — increase or decrease movement points
|
||
- `SetMovementType(type)` — change movement style (`Walk`, `Flight`, `Jump`, `Teleport`)
|
||
- `SetAttackRange(min, max)` — change attack range
|
||
- `ModifyCost(sp?, st?)` — change SP or ST cost
|
||
- `SetAffinity(affinity)` — change the affinity of the target unit or card; accepts a fixed value or a dynamic reference (see §4.5)
|
||
- `GrantAdditionalAttack(N)` — allow the unit to attack N additional times this turn; stacks with multiple applications
|
||
- `SetStatModMultiplier(stat, multiplier)` — multiply any incoming stat modifications to the specified stat by the given value (e.g. `SetStatModMultiplier(Damage, 2.0)` doubles all Damage modifiers applied to this unit)
|
||
|
||
---
|
||
|
||
### 5.2 Flag Modification
|
||
|
||
Applies to `Spirit`, `ArchSpirit`, `SpiritToken`, or `Player`:
|
||
|
||
Unit flags:
|
||
- `SetCanMove(bool)`
|
||
- `SetCanAttack(bool)`
|
||
- `SetCanDefend(bool)` — if false, incoming damage bypasses defense
|
||
- `SetCanBeAttacked(bool)`
|
||
- `SetCanBeBlocked(bool)` — if false, damage dealt ignores target defense
|
||
- `SetCanBeObstructed(bool)` — if false, unit ignores movement obstruction
|
||
- `SetCanUseAbility(bool)`
|
||
- `SetCanBeSacrificed(bool)` — Spirit only
|
||
|
||
Player flags:
|
||
- `SetCanDrawCards(bool)`
|
||
- `SetAccumulatesSP(bool)`
|
||
- `SetCanChannelSpirit(bool)`
|
||
- `SetCanSacrificeSpirit(bool)`
|
||
- `SetCanAscendArchSpirit(bool)`
|
||
- `SetCanTransitionArchSpirit(bool)`
|
||
- `SetCanChannelRepentance(bool)`
|
||
- `SetCanChannelInstinct(bool)`
|
||
- `SetCanChannelRuin(bool)`
|
||
- `SetCanChannelTerramorphaMono(bool)`
|
||
- `SetCanChannelTerramorphaDi(bool)`
|
||
- `SetCanChannelTerramorphaTri(bool)`
|
||
|
||
---
|
||
|
||
### 5.3 Ability Modification
|
||
|
||
Applies to `Spirit`, `ArchSpirit`, `SpiritToken`:
|
||
|
||
- `AddAbility(abilityDef)` — add a new ability to the unit
|
||
- `RemoveAbility(abilityRef)` — permanently remove an ability
|
||
- `EnableAbility(abilityRef)` — re-enable a disabled ability
|
||
- `DisableAbility(abilityRef)` — disable without removing
|
||
|
||
---
|
||
|
||
### 5.4 Genus Modification
|
||
|
||
Applies to `Spirit`, `ArchSpirit`, `SpiritToken`:
|
||
|
||
- `AddGenus(tag)`
|
||
- `RemoveGenus(tag)`
|
||
|
||
---
|
||
|
||
### 5.5 Player Resource Modification
|
||
|
||
Applies to `Player`:
|
||
|
||
- `ModifySP(amount)` — increase or decrease current SP
|
||
- `ModifySPAccumulation(amount)` — increase or decrease SP gained per turn
|
||
- `ModifyST(amount)` — increase or decrease current ST
|
||
- `ModifyCardsDrawnPerTurn(amount)` — change per-turn draw count
|
||
|
||
---
|
||
|
||
### 5.6 Tile Modification
|
||
|
||
Applies to `Tile`:
|
||
|
||
- `SetBaseAffinity1(affinity)` — set Base1 affinity slot directly
|
||
- `SetBaseAffinity2(affinity)` — set Base2 affinity slot directly
|
||
- `PushAffinity(affinity)` — push basic affinity into Base2; Base2 shifts to Base1
|
||
- `PushFinalAffinity(affinity)` — set Base1/Base2 to the pair yielding the target final affinity
|
||
|
||
---
|
||
|
||
### 5.7 Zone and Card Operations
|
||
|
||
- `DrawCards(N, player)` — target player draws N cards
|
||
- `DiscardCards(N, player, filter?)` — discard N cards; optional filter or random selection
|
||
- `ReturnToHand(card)` — move card from discard/battlefield to hand
|
||
- `ReturnToDeck(card, position: top | bottom | random)` — move card to deck
|
||
- `ReturnToBattlefield(card, controller?: Ownership, tileFilter?: TileFilter[])` — place card from discard/hand onto battlefield; `controller` overrides which player controls the unit (defaults to original owner); `tileFilter` restricts which tile the placing player may select
|
||
- `SendToDiscard(card)` — move card from any zone to discard
|
||
- `SearchDeck(filter, count?: N, thenAction)` — player searches deck for up to `count` cards matching filter (default 1); `thenAction` is applied once per found card with `SearchResult` referencing the current found card; deck is shuffled after the search
|
||
- `ShuffleDeck(player)` — shuffle target player's deck
|
||
- `RevealCards(N, toOwnership)` — reveal N hand cards to specified players
|
||
- `PlaceOnDeck(card, position: top | bottom)` — place card on top or bottom of deck
|
||
- `ChannelCard(card, payCost: bool, costMultiplier?: float)` — channel a card directly from hand or as referenced by `SearchResult`; `payCost: true` deducts normal SP/ST channel costs and all channeling rules apply; `costMultiplier` scales the cost (e.g. `2.0` = double, `0.5` = half); `payCost: false` overrides to no cost regardless of multiplier
|
||
|
||
**`SearchResult`**: When used inside a `SearchDeck` `thenAction`, the keyword `SearchResult` refers to the currently found card. It may be used as the `card` argument in any §5.7 operation — `ReturnToHand(SearchResult)`, `SendToDiscard(SearchResult)`, `ChannelCard(SearchResult, ...)`, etc.
|
||
|
||
---
|
||
|
||
### 5.8 Combat and Damage
|
||
|
||
- `DealDamage(amount, bypassDefense?: bool)` — deal damage to target; optionally bypass defense
|
||
- `Heal(amount)` — restore health up to max
|
||
- `DealDamageToSelf(amount, bypassDefense?: bool)` — source unit takes damage
|
||
- `DOT(amount, duration, bypassDefense?: bool)` — damage over time; applies `amount` each turn tick
|
||
- `HOT(amount, duration)` — heal over time; restores `amount` each turn tick
|
||
|
||
---
|
||
|
||
### 5.9 Displacement
|
||
|
||
Moves a unit without spending that unit's MP.
|
||
|
||
- `PushUnit(tiles, awayFromSource)` — move target N tiles away from the source
|
||
- `PullUnit(tiles, towardSource)` — move target N tiles toward the source
|
||
- `DisplaceUnit(tiles, direction)` — move target N tiles in a fixed cardinal/hex direction
|
||
|
||
Rules:
|
||
- Does not consume the displaced unit's MP.
|
||
- Blocked if destination tile is occupied or invalid; unit stops at last valid tile.
|
||
- Does not respect the displaced unit's own movement type or obstruction flags.
|
||
|
||
---
|
||
|
||
### 5.10 Control Effects
|
||
|
||
Applies to `Spirit`, `ArchSpirit`, `SpiritToken`:
|
||
|
||
- `TakeControl(duration)` — transfers control of the target unit to the ability owner for the specified duration; the unit acts as a friendly unit for that player until the effect expires, then returns to its original owner
|
||
- `GrantMovementControl(N)` — the activating player may issue N move commands to the target unit this turn; each command uses the target unit's own MP, respects its `CanMove` flag, movement type, and obstruction rules; does not transfer ownership or affect any other flags
|
||
- `SetFixedSacrificeReturn(stAmount)` — overrides the standard sacrifice formula for this unit; when sacrificed, the controller receives exactly `stAmount` ST instead of the formula result (see §6.15 in gameplay.md)
|
||
|
||
---
|
||
|
||
### 5.11 Token Summoning
|
||
|
||
- `SummonToken(tokenDef, tileFilter?: TileFilter[])` — place a `SpiritToken` onto a player-selected tile meeting the filter; `tokenDef` references a token definition specifying the token's stats, abilities, and genus; follows normal occupancy rules for the tile
|
||
|
||
---
|
||
|
||
### 5.12 Deferred Effects
|
||
|
||
- `ApplyOnEvent(trigger, effects)` — schedule effects to fire once the next time the specified trigger event occurs; the scheduled effects resolve as if originating from the same source unit; consumed after firing once; if the source unit leaves the battlefield before the event fires, the scheduled effect is cancelled
|
||
|
||
Example: Channel a card for free, then `ApplyOnEvent(OnTurnEnd(Owner), [SendToDiscard(Self)])` ensures it leaves the battlefield at end of turn.
|
||
|
||
---
|
||
|
||
## 6) Condition Types
|
||
|
||
Conditions can gate an entire ability or individual actions. If the condition group is not satisfied, the gated ability or action is skipped.
|
||
|
||
### 6.0 Logical Operators
|
||
|
||
Conditions may be grouped with logical operators:
|
||
|
||
- `AND` (default) — all conditions in the group must be met
|
||
- `OR` — at least one condition in the group must be met
|
||
- `XOR` — exactly one condition in the group must be met
|
||
|
||
Groups may be nested to express compound logic:
|
||
```
|
||
OR [
|
||
AND [ SPAtLeast(2), UnitCountOnBattlefield(Enemy, Spirit, >=, 1) ]
|
||
HandSizeAtLeast(3, subject: Target)
|
||
]
|
||
```
|
||
|
||
### 6.0.1 Condition Subject
|
||
|
||
Each condition evaluates against a **subject** — the entity whose state is checked:
|
||
|
||
- `subject: Self` (default) — evaluates against the source unit or the ability owner
|
||
- `subject: Target` — evaluates against the current action's resolved target
|
||
|
||
Example: `UnitCountOnBattlefield(Owner, Spirit, >, 1, subject: Target)` checks whether *the targeted player* controls more than 1 Spirit, not the ability's owner.
|
||
|
||
### 6.0.2 EventData Reference
|
||
|
||
`Triggered` ability actions have access to the payload of the triggering event via `EventData`. This allows effects to reference numeric values from the event rather than fixed constants.
|
||
|
||
Available fields (availability depends on the triggering event):
|
||
|
||
- `EventData.Amount` — the numeric magnitude of the event (e.g., HP gained, damage dealt, SP spent)
|
||
- `EventData.Source` — the unit or player that caused the event
|
||
- `EventData.Target` — the unit or player the event acted upon
|
||
|
||
`EventData` fields may be used anywhere a numeric value or unit reference is accepted in an effect or condition within the same action sequence.
|
||
|
||
Example: `OnHealed(Enemy, ArchSpirit)` → `DealDamage(EventData.Amount * 3)` — when an enemy ArchSpirit gains HP, deal 3× that amount as damage.
|
||
|
||
### 6.1 Unit Conditions
|
||
|
||
- `HealthBelow(N)` / `HealthAbove(N)`
|
||
- `DefenseIs(N)`
|
||
- `HasGenus(tag)`
|
||
- `HasAbility(abilityRef)`
|
||
- `IsOnTileWithAffinity(affinity)`
|
||
- `IsAdjacentTo(unitType, ownership)`
|
||
- `WithinRangeOf(target, min, max)`
|
||
- `MovementTypeIs(type)`
|
||
|
||
### 6.2 Player Conditions
|
||
|
||
- `SPAtLeast(N)` / `SPAtMost(N)`
|
||
- `STAtLeast(N)` / `STAtMost(N)`
|
||
- `HandSizeAtLeast(N)` / `HandSizeAtMost(N)`
|
||
- `DeckSizeAtLeast(N)`
|
||
- `DiscardSizeAtLeast(N)`
|
||
|
||
### 6.3 Tile Conditions
|
||
|
||
- `TileAffinityMatches(affinity)`
|
||
- `TileIsOccupied(unitType?)`
|
||
- `TileIsUnoccupied`
|
||
|
||
### 6.4 Turn/Timing Conditions
|
||
|
||
- `IsOwnTurn`
|
||
- `IsOpponentTurn`
|
||
- `IsAllyTurn`
|
||
- `IsActivePlayerTurn(ownership)` — scoped to a specific player ownership group
|
||
|
||
### 6.5 Battlefield Conditions
|
||
|
||
- `UnitCountOnBattlefield(ownership, unitType, comparator, N)` — e.g. "ally Spirit count >= 3"
|
||
- `CardInZone(cardRef, zone)`
|
||
|
||
---
|
||
|
||
## 7) Duration Model
|
||
|
||
All effects support a duration. Reversible effects retain source and modifier context for rollback when duration ends.
|
||
|
||
- `Instant` — one-time change, no ongoing state
|
||
- `UntilEndOfTurn`
|
||
- `UntilStartOfOwnerTurn`
|
||
- `UntilStartOfSourceOwnerTurn`
|
||
- `ForNTurns(N)`
|
||
- `WhileCondition(condition)`
|
||
- `PermanentInMatch`
|
||
|
||
Duration anchors can be scoped to a specific player:
|
||
- Until end of `X` player's turn
|
||
- Until start of `X` player's turn
|
||
|
||
Delayed timing:
|
||
- Effect starts after `X` turns
|
||
- Effect ends after `X` turns
|
||
|
||
---
|
||
|
||
## 8) Trigger Event Catalog
|
||
|
||
All `Triggered` abilities specify a `TriggerEvent` from this catalog. Every event supports an **ownership scope** (`Owner | Ally | Enemy | Any`) applied to the acting unit, player, or card. Most events also accept an optional **filter** using the same filter types as §4.
|
||
|
||
---
|
||
|
||
### 8.1 Turn Phase
|
||
|
||
- `OnTurnStart(player)` — start of the specified player's turn
|
||
- `OnTurnEnd(player)` — end of the specified player's turn
|
||
|
||
---
|
||
|
||
### 8.2 Channeling
|
||
|
||
Single event, parameterized by card type:
|
||
|
||
- `OnChanneled(type, ownership, filter?)` — a card of the given type is channeled
|
||
- `type`: `Spirit | Terramorpha | Repentance | Instinct | Ruin`
|
||
|
||
---
|
||
|
||
### 8.3 ArchSpirit Tier Actions
|
||
|
||
- `OnAscend(ownership)` — an ArchSpirit is ascended to the next tier
|
||
- `OnTransition(ownership)` — an ArchSpirit is transitioned out and replaced
|
||
|
||
---
|
||
|
||
### 8.4 Unit Actions
|
||
|
||
- `OnUnitMove(ownership, filter?)` — a unit spends MP to move to a tile
|
||
- `OnUnitAttack(ownership, filter?)` — a unit declares an attack
|
||
- `OnUnitAbilityActivated(ownership, filter?)` — a unit activates an Active ability
|
||
- `OnUnitMPSpent(ownership, filter?, amount?)` — a unit spends movement points
|
||
|
||
---
|
||
|
||
### 8.5 Damage and Healing
|
||
|
||
- `OnDamageDealt(sourceOwnership, targetOwnership, type: HP | Defense | Any, amount?)` — damage lands on a unit
|
||
- `OnDamagePrevented(targetOwnership, filter?)` — incoming damage is fully blocked by defense or an effect
|
||
- `OnHealed(targetOwnership, filter?, amount?)` — a unit is restored health
|
||
|
||
---
|
||
|
||
### 8.6 Unit Lifecycle
|
||
|
||
- `OnUnitEnterBattlefield(unitType, ownership, filter?)` — a unit is placed on the battlefield (any cause)
|
||
- `OnUnitLeaveBattlefield(unitType, ownership, filter?)` — a unit leaves the battlefield (any cause)
|
||
- `OnUnitDeath(unitType, ownership, filter?)` — a unit's HP reaches 0
|
||
- `OnUnitSentToDiscard(unitType, ownership, filter?, causedBy?)` — a unit is sent to the discard from the battlefield by any means other than death (e.g. used as a cost, forced removal)
|
||
- `OnSpiritSacrificed(ownership, filter?)` — a Spirit is sacrificed (see §6.15 in gameplay.md)
|
||
- `OnTokenSummoned(ownership, filter?)` — a SpiritToken enters the battlefield
|
||
|
||
**`causedBy` parameter**: An optional ownership reference (`Self | Owner | Ally | Enemy | Any`) that filters events to only those caused by a specific unit or player. Applies to unit lifecycle events and unit action events where the acting entity can be identified.
|
||
|
||
Example: `OnUnitSentToDiscard(Spirit, Any, causedBy: Self)` — fires only when this unit is the one that sent a spirit to the discard.
|
||
|
||
---
|
||
|
||
### 8.7 Unit State Changes
|
||
|
||
- `OnStatModified(ownership, filter?, stat?)` — a mutable stat on a unit is changed
|
||
- `OnAbilityAdded(ownership, filter?)` — an ability is added to a unit
|
||
- `OnAbilityRemoved(ownership, filter?)` — an ability is removed from a unit
|
||
- `OnGenusChanged(ownership, filter?)` — a unit's genus tags are modified
|
||
|
||
---
|
||
|
||
### 8.8 Ruin
|
||
|
||
- `OnRuinActivation(ruinOwnership, occupantOwnership?)` — a Ruin fires one of its abilities
|
||
- `OnUnitOccupyRuin(unitOwnership, filter?)` — a unit moves onto a tile containing a Ruin
|
||
|
||
---
|
||
|
||
### 8.9 Tile
|
||
|
||
- `OnTileAffinityChanged(filter?)` — a tile's Base1 or Base2 affinity changes
|
||
|
||
---
|
||
|
||
### 8.10 Player Resources
|
||
|
||
- `OnSPGained(player, amount?)`
|
||
- `OnSPSpent(player, amount?)`
|
||
- `OnSTGained(player, amount?)`
|
||
- `OnSTSpent(player, amount?)`
|
||
|
||
---
|
||
|
||
### 8.11 Card Zone Events
|
||
|
||
- `OnCardDrawn(player, filter?)`
|
||
- `OnCardDiscarded(player, filter?, cause?: voluntary | forced)` — `cause` filters by whether the discard was player-initiated or forced by an effect
|
||
- `OnCardReturnedToHand(player, filter?)`
|
||
- `OnCardReturnedToDeck(player, filter?)`
|
||
- `OnDeckShuffled(player)`
|
||
- `OnCardsRevealed(player, filter?)`
|
||
|
||
---
|
||
|
||
### 8.12 Effect and Targeting Lifecycle
|
||
|
||
- `OnTargetedByAbility(targetOwnership, sourceOwnership, filter?)` — a unit or player is selected as a target of an ability action (fires before effects resolve)
|
||
- `OnEffectApplied(targetOwnership, sourceOwnership, filter?)` — an effect successfully resolves on a target (fires after resolution; distinct from targeting if action conditions blocked the effect)
|
||
- `OnEnterAuraRange(auraOwnership, unitOwnership, filter?)` — a unit moves into the active range of an aura ability
|
||
- `OnLeaveAuraRange(auraOwnership, unitOwnership, filter?)` — a unit moves out of the active range of an aura ability
|
||
|
||
---
|
||
|
||
## File: Shared/context-files/affinity.md
|
||
|
||
# Affinity Rules (Current Understanding)
|
||
|
||
This file documents the current affinity system as a strict rules reference.
|
||
|
||
## 1) Slot Model
|
||
|
||
Each tile has two affinity slots:
|
||
- `Base1`: older slot (filled first)
|
||
- `Base2`: newer slot (filled second, most recent)
|
||
|
||
When pushing a new basic affinity `X` to a tile:
|
||
1. Current `Base2` shifts into `Base1`.
|
||
2. New affinity `X` becomes `Base2`.
|
||
|
||
Equivalent update:
|
||
- `Base1 = old(Base2)`
|
||
- `Base2 = X`
|
||
|
||
## 2) Basic Affinities
|
||
|
||
- `Void`
|
||
- `Aether`
|
||
- `Lake`
|
||
- `Hill`
|
||
- `Forest`
|
||
- `Field`
|
||
|
||
## 3) Derived Tile Affinity
|
||
|
||
The tile's active affinity is determined by the pair `(Base1, Base2)`.
|
||
|
||
## 4) Non-Basic Affinity Map
|
||
|
||
Combination key uses `Base1 + Base2`.
|
||
|
||
- `Ocean = Lake + Lake`
|
||
- `Island = Lake + Hill` or `Hill + Lake`
|
||
- `Marsh = Lake + Field` or `Field + Lake`
|
||
- `Swamp = Lake + Forest` or `Forest + Lake`
|
||
- `Mountain = Hill + Hill`
|
||
- `Steppe = Hill + Field` or `Field + Hill`
|
||
- `Fort = Hill + Forest` or `Forest + Hill`
|
||
- `Plains = Field + Field`
|
||
- `Grove = Field + Forest` or `Forest + Field`
|
||
- `Jungle = Forest + Forest`
|
||
- `GatewayLake = Lake + Void`
|
||
- `GatewayHill = Hill + Void`
|
||
- `GatewayField = Field + Void`
|
||
- `GatewayForest = Forest + Void`
|
||
- `UnstableAether = Aether + (Void or Hill or Forest or Field or Lake)`
|
||
- `UnstableAether = (Void or Hill or Forest or Field or Lake) + Aether`
|
||
- `PerfectAether = Aether + Aether`
|
||
- `PureVoid = Void + Void`
|
||
|
||
## 5) Notes on Order
|
||
|
||
Current interpretation:
|
||
- Most terrain combinations are order-insensitive (both orders listed).
|
||
- `Gateway*` is directional only and requires `Base2 = Void` (`X + Void` only).
|
||
- `UnstableAether` is explicitly both directions.
|
||
|
||
## 6) Example Slot Evolution
|
||
|
||
Starting tile slots:
|
||
- `Base1 = Lake`
|
||
- `Base2 = Hill`
|
||
|
||
Push `Forest`:
|
||
- New `Base1 = Hill`
|
||
- New `Base2 = Forest`
|
||
- Tile affinity resolves from `Hill + Forest` -> `Fort`
|
||
|
||
## 7) Resolution Completeness
|
||
|
||
Every `(Base1, Base2)` pair is valid and must resolve to a defined affinity result.
|
||
|
||
## 8) Basic Affinity on Tiles
|
||
|
||
Tiles can resolve to a basic affinity when:
|
||
- `Base1 = Void`
|
||
- `Base2 = <BasicAffinity>`
|
||
|
||
Examples:
|
||
- `Void + Lake` resolves as tile basic `Lake`
|
||
- `Void + Hill` resolves as tile basic `Hill`
|
||
- `Void + Forest` resolves as tile basic `Forest`
|
||
- `Void + Field` resolves as tile basic `Field`
|
||
- `Void + Aether` resolves to `UnstableAether` (special case, not basic)
|
||
|
||
## 9) Card Affinity vs Tile Affinity
|
||
|
||
Cards use almost the same affinity set as tiles, with exclusions:
|
||
- Cards do use basic and standard non-basic affinities.
|
||
- Cards do not use `Gateway*`.
|
||
- Cards do not use `UnstableAether`.
|
||
|
||
`PerfectAether` is valid via `Aether + Aether`.
|
||
|
||
---
|
||
|
||
## File: Shared/context-files/card-design.md
|
||
|
||
# Card Design (WIP)
|
||
|
||
This file is the canonical reference for card types, their mutable state properties, and card-specific rules.
|
||
|
||
---
|
||
|
||
## 1) CardState (Shared)
|
||
|
||
Non-mutable:
|
||
- `DefinitionId`
|
||
- `LibraryId` (unique GUID per card instance)
|
||
- `Name`
|
||
- `Description`
|
||
- `CardType`
|
||
|
||
Targeting note: `CardType` is valid for targeting/scoping. All mutable properties are valid selectors.
|
||
|
||
---
|
||
|
||
## 2) CardState.ArchSpirit
|
||
|
||
Mutable:
|
||
- `MinChannelRange`
|
||
- `MaxChannelRange`
|
||
- `SPCost`
|
||
- `STCost`
|
||
- `OtherCosts`
|
||
- `Affinity`
|
||
- `AttackType`
|
||
- `RequiresLOS`
|
||
- `MinAttackRange`
|
||
- `MaxAttackRange`
|
||
- `CanAttack`
|
||
- `Damage`
|
||
- `CanDefend` (if false, incoming damage bypasses defense)
|
||
- `Health`
|
||
- `CanMove`
|
||
- `MovementType`
|
||
- `MovementPoints`
|
||
- `CanBeObstructed` (if false, ignores movement obstruction)
|
||
- `Defense`
|
||
- `CanBeAttacked`
|
||
- `CanBeBlocked` (if false, damage dealt ignores defense)
|
||
- `CanUseAbility`
|
||
- `AddAbility`
|
||
- `RemoveAbility`
|
||
- `EnableAbility`
|
||
- `DisableAbility`
|
||
- `Genus`
|
||
|
||
---
|
||
|
||
## 3) CardState.Spirit
|
||
|
||
Mutable:
|
||
- `SPCost`
|
||
- `STCost`
|
||
- `OtherCosts`
|
||
- `Affinity`
|
||
- `AttackType`
|
||
- `RequiresLOS`
|
||
- `MinAttackRange`
|
||
- `MaxAttackRange`
|
||
- `CanAttack`
|
||
- `Damage`
|
||
- `CanDefend` (if false, incoming damage bypasses defense)
|
||
- `Health`
|
||
- `CanMove`
|
||
- `MovementType`
|
||
- `MovementPoints`
|
||
- `CanBeObstructed` (if false, ignores movement obstruction)
|
||
- `Defense`
|
||
- `CanBeAttacked`
|
||
- `CanBeBlocked` (if false, damage dealt ignores defense)
|
||
- `CanBeSacrificed`
|
||
- `CanUseAbility`
|
||
- `AddAbility`
|
||
- `RemoveAbility`
|
||
- `EnableAbility`
|
||
- `DisableAbility`
|
||
- `Genus`
|
||
|
||
---
|
||
|
||
## 4) CardState.Repentance
|
||
|
||
Mutable:
|
||
- `SPCost`
|
||
- `STCost`
|
||
- `OtherCosts`
|
||
- `Affinity`
|
||
- `Effects` (`Action[]` — see **abilities.md**)
|
||
|
||
Rules:
|
||
- Goes to discard once played unless an effect says otherwise.
|
||
- Can only be played if the player's ArchSpirit is on a tile matching the Repentance affinity.
|
||
|
||
---
|
||
|
||
## 5) CardState.Terramorpha
|
||
|
||
Mutable:
|
||
- `SPCost`
|
||
- `STCost`
|
||
- `OtherCosts`
|
||
- `Affinity`
|
||
- `TerramorphaMode` (`Mono`, `Di`, `Tri`)
|
||
|
||
---
|
||
|
||
## 6) CardState.Ruin
|
||
|
||
Mutable:
|
||
- `SPCost`
|
||
- `STCost`
|
||
- `OtherCosts`
|
||
- `Affinity`
|
||
- `Abilities`
|
||
|
||
Rules:
|
||
- Channeled to a random battlefield tile matching Ruin affinity.
|
||
- One ability activates at random at the start of the occupying player's turn, after SP gain and card draw.
|
||
- The occupying unit is a valid target for all Ruin abilities regardless of which player controls the Ruin — the controller is not exempt from its negative effects.
|
||
|
||
---
|
||
|
||
## 7) CardState.Instinct
|
||
|
||
Mutable:
|
||
- `SPCost`
|
||
- `STCost`
|
||
- `OtherCosts`
|
||
- `Affinity`
|
||
- `Effects` (`Action[]` — see **abilities.md**)
|
||
|
||
Rules:
|
||
- Goes to discard once played unless an effect says otherwise.
|
||
- Can only be played if the player's ArchSpirit is on a tile matching Instinct affinity.
|
||
- Can be played during any player's turn or as a non-play interrupt.
|
||
|
||
---
|
||
|
||
## File: Shared/context-files/gameplay.md
|
||
|
||
# Gameplay Rules (Current Scope)
|
||
|
||
This file captures confirmed gameplay rules so far.
|
||
It is intentionally incomplete and will be expanded in later passes.
|
||
|
||
## 1) Match Entry and Deck Selection
|
||
|
||
1. Players create decks of cards.
|
||
2. Deck size has no minimum and no maximum.
|
||
3. Every deck must contain at least one `Tier 1` `ArchSpirit`.
|
||
4. Players can enter either:
|
||
- Ranked match
|
||
- Custom match (join or create)
|
||
5. Before match start, each player selects:
|
||
- The deck they will use
|
||
- The `Tier 1 ArchSpirit` they will start with
|
||
|
||
## 2) Match Size and Battlefield
|
||
|
||
1. Matches support `2..N` players.
|
||
2. Battlefield size scales based on player count.
|
||
3. Each player has a defined starting side.
|
||
4. Grid styles supported:
|
||
- `Square`
|
||
- `Hex`
|
||
|
||
## 3) Opening Placement
|
||
|
||
1. Each player places their selected `Tier 1 ArchSpirit` on a tile in the first row of their side.
|
||
2. On placement, the `ArchSpirit` affinity is pushed to the placement tile itself and all valid adjacent tiles:
|
||
- Square grid (non-corner): the placement tile + `3` adjacent tiles = `4` tiles total.
|
||
- Square grid (corner): the placement tile + `2` adjacent tiles = `3` tiles total.
|
||
- Hex grid (non-corner edge): the placement tile + `4` adjacent tiles = `5` tiles total.
|
||
3. Edge-side explanation:
|
||
- On a square edge, the tile behind the ArchSpirit is off the board, so only 3 adjacent tiles are valid.
|
||
- On a hex edge, two sides face off the board, leaving four valid adjacent tiles.
|
||
- Example (square, 5,0 placement): tiles `4,0`, `5,0`, `5,1`, `6,0` all receive the affinity push.
|
||
|
||
## 3.1 Opening Draw
|
||
|
||
1. At game start, each player draws `7` cards.
|
||
2. This value is the default and may be overridden by custom match settings.
|
||
|
||
## 4) Turn Order
|
||
|
||
## 4.1 Free-for-All
|
||
|
||
Turn order is randomized among all players.
|
||
|
||
## 4.2 Team Play
|
||
|
||
1. Team order alternates by team.
|
||
2. Within each team slot, player order is randomized among that team's players.
|
||
3. Example:
|
||
- Team 1 Player A
|
||
- Team 2 Player C
|
||
- Team 1 Player B
|
||
- Team 2 Player D
|
||
|
||
## 5) Turn Economy
|
||
|
||
1. Base SP gain per turn is driven by game settings:
|
||
- Ranked: static/default ranked setting
|
||
- Custom: defined by custom rules
|
||
2. Effects may modify SP gained per turn.
|
||
3. SP currently has no enforced cap.
|
||
4. SP cap should be supported by settings in the future.
|
||
5. Default per-turn card draw is `1`; may be modified by effects.
|
||
|
||
## 5.1 Resource Rules
|
||
|
||
1. `Sacrifice Tokens` are a separate resource from `SP`.
|
||
2. `Sacrifice Tokens` do not accumulate automatically per turn.
|
||
3. `Sacrifice Tokens` are obtained by other game effects/systems and spent to pay card costs.
|
||
|
||
## 6) Turn Flow (Current High-Level)
|
||
|
||
1. Active player takes actions during their turn.
|
||
2. Active player clicks "end turn" when finished; `UntilEndOfTurn` effects expire at this point.
|
||
3. Turn advances to next player in current turn order.
|
||
|
||
## 6.0 Start-of-Turn Phase
|
||
|
||
At the start of each turn, the following resolve in order:
|
||
|
||
1. MP replenishment — all friendly `ArchSpirit` and `Spirit` units restore movement points.
|
||
2. Defense restoration — all friendly `ArchSpirit` and `Spirit` units restore defense to max.
|
||
3. SP gain — the active player gains their current SP accumulation amount.
|
||
4. Start-of-turn triggered abilities resolve.
|
||
5. Card draw — the active player draws their current per-turn card count.
|
||
6. Draw-triggered abilities resolve.
|
||
7. Ruin activations — one ability activates at random for each Ruin tile occupied by a friendly unit.
|
||
|
||
## 6.1 Hand Rules
|
||
|
||
1. There is no enforced hand size limit.
|
||
|
||
## 6.2 Turn-Timing Rule (Current)
|
||
|
||
During the active player's turn, they may channel:
|
||
- `Spirit`
|
||
- `Ruins`
|
||
- `Terramorpha`
|
||
- `Repentance`
|
||
- `Instinct`
|
||
|
||
The active player may continue channeling cards while they can still pay all required costs.
|
||
|
||
Channeling cards and taking unit actions (move, attack, ability, sacrifice) may be freely interleaved with no required ordering.
|
||
|
||
Special timing exception:
|
||
- `Instinct` cards may also be played during other players' turns.
|
||
- `Instinct` cards may also be played as non-play interrupts.
|
||
|
||
## 6.2.1 Card Resolution and Interrupt Windows
|
||
|
||
1. Card resolution follows play order (first played, first resolved in sequence).
|
||
2. Between each card played and between each unit action (move, attack, ability use), there is a `10` second interrupt window.
|
||
3. During that window, opponents may interrupt by playing an `Instinct`.
|
||
4. An ability's actions resolve in full sequence without interrupt windows between individual actions — the window opens only after the entire ability has resolved.
|
||
|
||
## 6.3 Channeling Spirits
|
||
|
||
1. A player may channel Spirit cards to tiles in the active `ArchSpirit`'s channeling range.
|
||
2. Channeling range is an `ArchSpirit`-specific property with `min` and `max` values.
|
||
3. Range rules:
|
||
- `min` can never be less than `1` in normal cases.
|
||
- If channeling range is set to `0`, that `ArchSpirit` cannot channel.
|
||
4. Channeling requires:
|
||
- Paying the channel cost
|
||
- Affinity validity on the target tile
|
||
5. Affinity validation:
|
||
- If the card has a basic affinity, `Base1` or `Base2` on the target tile must match that basic affinity.
|
||
- If the card has a non-basic affinity, the target tile must match that final resolved affinity exactly.
|
||
|
||
## 6.4 Channeling Terramorpha
|
||
|
||
1. Players may channel `Terramorpha` cards by paying their cost.
|
||
2. Terramorpha pushes affinity to target tiles.
|
||
3. Terramorpha can target any tile on the battlefield.
|
||
4. Terramorpha types:
|
||
- `Mono`: pushes affinity to one target tile.
|
||
- `Di-morpha`: target one tile, then target one adjacent tile.
|
||
- `Tri-morpha`: target one tile, then target one adjacent tile, then target one adjacent tile.
|
||
|
||
## 6.5 Unit Actions Per Turn
|
||
|
||
1. A player may move their `ArchSpirit` and `Spirit` units until each unit is out of movement points.
|
||
2. `ArchSpirit` can attack once per turn, unless modified by an ability/effect.
|
||
3. `Spirit` can attack once per turn, unless modified by an ability/effect.
|
||
4. `ArchSpirit` can use one activated ability per turn, unless modified by an ability/effect.
|
||
5. `Spirit` can use one activated ability per turn, unless modified by an ability/effect.
|
||
|
||
## 6.6 Cost Types (Channeling and Activated Abilities)
|
||
|
||
Supported costs include:
|
||
- `Spirit Points`
|
||
- `Sacrifice Tokens`
|
||
- Discard card from hand (with optional restrictions such as specific card, card type, or card cost)
|
||
- Move card from top of deck to discard
|
||
- Move card from bottom of deck to discard
|
||
- Send a controlled `Spirit` from battlefield to discard
|
||
- Deal damage to own `ArchSpirit`
|
||
- Deal damage to own `Spirit`
|
||
|
||
## 6.7 ArchSpirit Tier Actions
|
||
|
||
## 6.7.1 Transition
|
||
|
||
1. `Transition` swaps the `ArchSpirit` in play with a `Tier 1 ArchSpirit` from that player's hand.
|
||
2. `Transition` can only be performed during that player's turn.
|
||
3. The outgoing `ArchSpirit` goes to discard.
|
||
4. The incoming `ArchSpirit` enters with full health and defense.
|
||
5. `Transition` uses the incoming `ArchSpirit`'s channeling cost.
|
||
6. The incoming `ArchSpirit` may move, attack, and use abilities during the turn it enters.
|
||
|
||
## 6.7.2 Ascend
|
||
|
||
1. `Ascend` upgrades the in-play `ArchSpirit` by exactly one tier (for example `Tier 1 -> Tier 2`).
|
||
2. `Ascend` can only be performed during that player's turn.
|
||
3. The target higher-tier `ArchSpirit` must be the direct predecessor/successor line of the in-play `ArchSpirit`.
|
||
4. Valid example:
|
||
- `ArchSpirit A Tier 1 -> ArchSpirit A Tier 2`
|
||
5. Invalid examples:
|
||
- `ArchSpirit A Tier 1 -> ArchSpirit B Tier 2`
|
||
- `ArchSpirit A Tier 1 -> ArchSpirit A Tier 3+`
|
||
6. `Ascend` uses the incoming (higher-tier) `ArchSpirit`'s channeling cost.
|
||
7. The higher-tier `ArchSpirit` source zone is not restricted (hand, deck, or other).
|
||
8. The incoming `ArchSpirit` may move, attack, and use abilities during the turn it enters.
|
||
|
||
## 6.8 Movement Rules (Spirit and ArchSpirit)
|
||
|
||
1. Movement is `1-to-1`: moving one tile spends one MP.
|
||
3. A tile can contain at most one `Spirit` or `ArchSpirit` at a time.
|
||
4. Movement can be obstructed by other `Spirit`/`ArchSpirit` units.
|
||
5. Each `Spirit` defines:
|
||
- Whether its own movement can be obstructed
|
||
- Whether it obstructs movement for others
|
||
6. Supported movement styles include:
|
||
- `Walk`
|
||
- `Flight`
|
||
- `Jump`
|
||
- `Teleport`
|
||
7. Movement style behavior:
|
||
- `Walk`: can be obstructed by any `Spirit` or `ArchSpirit` occupying a tile.
|
||
- `Flight`: can only be obstructed by units with `Flight`.
|
||
- `Jump`: cannot be obstructed. Has a min/max movement range. Costs `1 MP` per tile landed on (not per tile traversed in path).
|
||
- `Teleport`: cannot be obstructed. Same min/max range model as `Jump`. Costs `1 MP` per tile landed on.
|
||
8. Line-of-sight (`LOS`) requirements:
|
||
- `Walk` and `Flight` do not require LOS (path-based movement).
|
||
- `Jump` does not require LOS.
|
||
- `Teleport` requires LOS.
|
||
9. Pathing:
|
||
- Movement pathing is built through adjacent tiles.
|
||
- On `Square` grids, diagonal movement is not allowed.
|
||
- On `Hex` grids, pathing uses standard BFS over adjacent tiles with 1-to-1 tile movement cost.
|
||
|
||
## 6.9 ArchSpirit/Spirit Shared Properties
|
||
|
||
## 6.9.1 Genus
|
||
|
||
1. `Genus` is an array of type tags (examples: `Goblin`, `Undead`, `Warrior`).
|
||
2. A unit is affected by any effect that matches any of its genus tags.
|
||
|
||
## 6.9.2 Health
|
||
|
||
1. A unit with `Health <= 0` is dead.
|
||
2. Dead units go to the discard unless an ability/effect specifies otherwise.
|
||
|
||
## 6.9.3 Defense
|
||
|
||
1. Defense restores to max at the start of each turn (see §6.0).
|
||
2. Incoming damage is applied to `Defense` first.
|
||
3. Damage is applied to `Health` only after `Defense` reaches `0`.
|
||
4. Example:
|
||
- Start: `Health = 5`, `Defense = 2`
|
||
- Take `1` damage -> `Health = 5`, `Defense = 1`
|
||
- Before defense restore, take `2` damage -> `Defense` goes to `0`, remaining `1` damage applies to health -> `Health = 4`
|
||
- At next turn start, defense restores to its full value (`2` in this example)
|
||
|
||
## 6.10 Attack System (Spirit and ArchSpirit)
|
||
|
||
1. `Spirit` and `ArchSpirit` units define:
|
||
- `attackStyle`
|
||
- `minAttackRange`
|
||
- `maxAttackRange`
|
||
- `damage`
|
||
2. Units can target friendly units (`Spirit`/`ArchSpirit`) with attacks, but friendly-target attack attempts require confirmation.
|
||
3. Damage normally applies through defense first, unless an ability/effect specifies defense bypass.
|
||
4. Attack style may define whether line-of-sight (`LOS`) is required.
|
||
5. Attack definitions may be:
|
||
- Single target
|
||
- Multi-target (`N` targets)
|
||
6. Attacks may include dynamic damage modifiers that decrease or increase damage based on defined factors.
|
||
7. Attacks may be `AOE`.
|
||
8. Attack range behavior may be constrained to linear-only targeting.
|
||
9. Attack range behavior may be constrained to diagonal-only targeting.
|
||
|
||
## 6.11 Ability System
|
||
|
||
See **abilities.md** for the full ability model (types, action model, effect types, conditions, durations).
|
||
|
||
## 6.12 Mutable Properties
|
||
|
||
See **object-context.md** for the canonical mutable property inventory and **card-design.md** for card-specific state properties.
|
||
|
||
## 6.13 Card Instance Rule
|
||
|
||
Gameplay operates on card instances.
|
||
There is no permanent card loss/gain of base definitions during play.
|
||
|
||
## 6.14 Stateful Mutation Model (Object-by-Object)
|
||
|
||
All mutable changes support duration metadata so effects can expire or be undone.
|
||
|
||
Duration model (applies to all objects):
|
||
- `Instant` (one-time change, no ongoing state)
|
||
- `UntilEndOfTurn`
|
||
- `UntilStartOfOwnerTurn`
|
||
- `UntilStartOfSourceOwnerTurn`
|
||
- `ForNTurns`
|
||
- `WhileCondition`
|
||
- `PermanentInMatch`
|
||
|
||
For reversible/temporary effects, the game must retain source + modifier context so rollback can be resolved correctly when duration ends.
|
||
|
||
## 6.14.1 PlayerState (Mutable Properties)
|
||
|
||
- `SPTotal`
|
||
- `SPAccumulationAmount`
|
||
- `AccumulatesSP` (bool)
|
||
- `STTotal`
|
||
- `CardsDrawnPerTurn`
|
||
- `CanDrawCards` (bool)
|
||
- `CanAscendArchSpirit` (bool)
|
||
- `CanTransitionArchSpirit` (bool)
|
||
- `CanChannelSpirit` (bool)
|
||
- `CanSacrificeSpirit` (bool)
|
||
- `CanChannelRepentance` (bool)
|
||
- `CanChannelInstinct` (bool)
|
||
- `CanChannelRuin` (bool)
|
||
- `CanChannelTerramorphaMono` (bool)
|
||
- `CanChannelTerramorphaDi` (bool)
|
||
- `CanChannelTerramorphaTri` (bool)
|
||
|
||
## 6.14.2 TileState (Mutable Properties)
|
||
|
||
- `BaseAffinitySlot1`
|
||
- `BaseAffinitySlot2`
|
||
- `PushAffinity` (push basic affinity into Base2 with slot shift)
|
||
- `PushFinalAffinity` (set Base1/Base2 to the pair required for a target final affinity)
|
||
- Occupancy-driven behavior/effects
|
||
- Occupant-targeting behavior/effects
|
||
|
||
Current occupant classes that tile behavior can reference:
|
||
- `Spirit`
|
||
- `ArchSpirit`
|
||
- `SpiritToken` (temporary spirit/summon)
|
||
- `Ruin`
|
||
|
||
## 6.14.3 Canonical Object Property Inventory (WIP)
|
||
|
||
This section is the normalized source for object properties.
|
||
|
||
## 6.14.3.1 Player
|
||
|
||
Non-mutable:
|
||
- `Id`
|
||
- `Name`
|
||
- `SelectedDeck`
|
||
- `SelectedArchSpirit`
|
||
|
||
Mutable:
|
||
- See `PlayerState` in `6.14.1`.
|
||
|
||
## 6.14.3.2 Tile
|
||
|
||
Non-mutable:
|
||
- `Id`
|
||
- `Coords`
|
||
|
||
Mutable:
|
||
- `CanBeOccupiedBy`: `Spirit`, `ArchSpirit`, `Ruin`
|
||
- `BaseAffinitySlot1`
|
||
- `BaseAffinitySlot2`
|
||
- `PushAffinity`
|
||
- `PushFinalAffinity`
|
||
- Occupancy-based effects
|
||
- Occupant-targeting effects
|
||
|
||
## 6.14.3.3 Battlefield
|
||
|
||
Non-mutable:
|
||
- Battlefield is a collection of tiles.
|
||
|
||
Mutable:
|
||
- Derived from tile state mutations and battlefield-level effects/rules.
|
||
|
||
## 6.14.3.4 CardState
|
||
|
||
See **card-design.md** for full CardState definitions (Shared, ArchSpirit, Spirit, Repentance, Terramorpha, Ruin, Instinct).
|
||
|
||
## 6.14.3.5 Deck / Hand / Discard Mutable Operations
|
||
|
||
Deck:
|
||
- Return card from `Hand`/`Discard`/`Battlefield` to deck
|
||
- Shuffle deck
|
||
- Place card from source zone to top or bottom of deck
|
||
- Draw `X` cards
|
||
- Place `X` cards from deck into discard
|
||
|
||
Hand:
|
||
- Discard `N` cards
|
||
- Reveal cards to `N` players
|
||
- Discard random cards
|
||
- Target player selects card(s) to discard
|
||
- Put `N` cards from hand on top/bottom of deck
|
||
- Put `N` cards from hand to battlefield as Instinct
|
||
- Play `N` cards from hand for modified cost `X`
|
||
|
||
Discard:
|
||
- Return cards from discard to deck
|
||
- Return cards from discard to hand
|
||
- Return cards from discard to battlefield
|
||
|
||
## 6.14.4 Global Targeting Filters and Location Scopes
|
||
|
||
Additional target filters:
|
||
- `Owner`
|
||
- `Ally`
|
||
- `Enemy`
|
||
- `Any`
|
||
- `Random`
|
||
|
||
Location scopes:
|
||
- `Hand`
|
||
- `Deck`
|
||
- `Discard`
|
||
- `Battlefield`
|
||
|
||
## 6.14.5 Duration Rule Primitives
|
||
|
||
Supported duration timing patterns:
|
||
- `UntilEndOfTurn`
|
||
- `UntilStartOfTurn`
|
||
- Duration anchors can be scoped to specific player turns:
|
||
- Until end of `X` player's turn
|
||
- Until start of `X` player's turn
|
||
- Delayed start/end:
|
||
- Effect starts after `X` turns
|
||
- Effect ends after `X` turns
|
||
- Conditional durations:
|
||
- While condition `X` is true
|
||
- While condition `X` is false
|
||
|
||
## 6.14.6 Summon and Occupancy Limits
|
||
|
||
1. There are no summon limits.
|
||
2. If a tile is in valid range and meets summon requirements, it is a valid summon target.
|
||
3. Every tile on the battlefield can be occupied.
|
||
|
||
## 6.15 Sacrifice Action
|
||
|
||
1. Sacrifice is a free action (does not consume an attack or ability use).
|
||
2. A player may sacrifice a `Spirit` only if that `Spirit` is adjacent to the player's `ArchSpirit`.
|
||
3. The sacrificed `Spirit` goes to discard.
|
||
4. Sacrifice value is computed first:
|
||
- `SpiritSacValue = (CardSTCost * 3) + CardSPCost`
|
||
5. Sacrifice Token (`ST`) return is computed from current `ST` and `SpiritSacValue`.
|
||
6. Sacrifice return function:
|
||
|
||
```csharp
|
||
public int GetSTReturn(int CurrentST, int SpiritSacValue)
|
||
{
|
||
int STReturn = 0;
|
||
if (CurrentST == 0)
|
||
{
|
||
if (SpiritSacValue <= 15)
|
||
{
|
||
STReturn = 1;
|
||
}
|
||
if (SpiritSacValue >= 16)
|
||
{
|
||
STReturn = 2;
|
||
}
|
||
}
|
||
if (CurrentST == 1)
|
||
{
|
||
if (SpiritSacValue <= 2)
|
||
{
|
||
STReturn = 0;
|
||
}
|
||
if (SpiritSacValue >= 3 && SpiritSacValue <= 15)
|
||
{
|
||
STReturn = 1;
|
||
}
|
||
if (SpiritSacValue >= 16)
|
||
{
|
||
STReturn = 2;
|
||
}
|
||
}
|
||
if (CurrentST == 2)
|
||
{
|
||
if (SpiritSacValue <= 6)
|
||
{
|
||
STReturn = 0;
|
||
}
|
||
if (SpiritSacValue >= 7 && SpiritSacValue <= 15)
|
||
{
|
||
STReturn = 1;
|
||
}
|
||
if (SpiritSacValue >= 16)
|
||
{
|
||
STReturn = 2;
|
||
}
|
||
}
|
||
if (CurrentST == 3)
|
||
{
|
||
if (SpiritSacValue <= 9)
|
||
{
|
||
STReturn = 0;
|
||
}
|
||
if (SpiritSacValue >= 10 && SpiritSacValue <= 15)
|
||
{
|
||
STReturn = 1;
|
||
}
|
||
if (SpiritSacValue >= 16)
|
||
{
|
||
STReturn = 2;
|
||
}
|
||
}
|
||
if (CurrentST >= 4)
|
||
{
|
||
STReturn = 0;
|
||
}
|
||
return STReturn;
|
||
}
|
||
```
|
||
|
||
## 7) Win Condition (Current)
|
||
|
||
Last `ArchSpirit` standing wins.
|
||
|
||
## 8) Deferred Rules (To Be Added Next)
|
||
|
||
The following are intentionally not defined yet:
|
||
- Full timing windows and reaction timing
|
||
- Affinity push timing and replacement edge cases
|
||
- Elimination timing details for team modes
|
||
- Mulligan rules
|
||
- Status effects, death checks, and simultaneous resolution order
|
||
- Ranked ruleset constants and custom rules schema
|
||
- Full adjacent-tile targeting constraints for `Di-morpha`/`Tri-morpha`
|
||
|
||
---
|
||
|
||
## File: Shared/context-files/object-context.md
|
||
|
||
# Object Context
|
||
|
||
This file is the canonical reference for all game objects, their properties, the ability action model, and the full catalog of effect and condition types.
|
||
|
||
---
|
||
|
||
## 1) Object Definitions
|
||
|
||
### 1.1 Player
|
||
|
||
Non-mutable:
|
||
- `Id`
|
||
- `Name`
|
||
- `SelectedDeck`
|
||
- `SelectedArchSpirit`
|
||
|
||
Mutable (see §6.14.1 in gameplay.md):
|
||
- `SPTotal`
|
||
- `SPAccumulationAmount`
|
||
- `AccumulatesSP` (bool)
|
||
- `STTotal`
|
||
- `CardsDrawnPerTurn`
|
||
- `CanDrawCards` (bool)
|
||
- `CanAscendArchSpirit` (bool)
|
||
- `CanTransitionArchSpirit` (bool)
|
||
- `CanChannelSpirit` (bool)
|
||
- `CanSacrificeSpirit` (bool)
|
||
- `CanChannelRepentance` (bool)
|
||
- `CanChannelInstinct` (bool)
|
||
- `CanChannelRuin` (bool)
|
||
- `CanChannelTerramorphaMono` (bool)
|
||
- `CanChannelTerramorphaDi` (bool)
|
||
- `CanChannelTerramorphaTri` (bool)
|
||
|
||
---
|
||
|
||
### 1.2 Tile
|
||
|
||
Non-mutable:
|
||
- `Id`
|
||
- `Coords`
|
||
|
||
Mutable:
|
||
- `CanBeOccupiedBy`: `Spirit`, `ArchSpirit`, `Ruin`
|
||
- `BaseAffinitySlot1`
|
||
- `BaseAffinitySlot2`
|
||
- `PushAffinity` (push basic affinity into Base2 with slot shift)
|
||
- `PushFinalAffinity` (set Base1/Base2 to the pair required for a target final affinity)
|
||
- Occupancy-based effects
|
||
- Occupant-targeting effects
|
||
|
||
Occupant classes tile behavior can reference:
|
||
- `Spirit`
|
||
- `ArchSpirit`
|
||
- `SpiritToken`
|
||
- `Ruin`
|
||
|
||
---
|
||
|
||
### 1.3 Battlefield
|
||
|
||
Non-mutable:
|
||
- Collection of tiles.
|
||
|
||
Mutable:
|
||
- Derived from tile state mutations and battlefield-level effects.
|
||
|
||
---
|
||
|
||
### 1.4 CardState
|
||
|
||
See **card-design.md** for the full CardState definitions (Shared, ArchSpirit, Spirit, Repentance, Terramorpha, Ruin, Instinct).
|
||
|
||
---
|
||
|
||
## 2) Ability and Effect System
|
||
|
||
See **abilities.md** for the full ability action model, target selectors, effect types, condition types, and duration model.
|
||
|
||
---
|
||
|
||
## File: Shared/context-files/README.md
|
||
|
||
# Shared Context Files
|
||
|
||
These context files are domain-agnostic and intended for both Client and Server:
|
||
- abilities.md
|
||
- affinity.md
|
||
- card-design.md
|
||
- gameplay.md
|
||
- object-context.md
|
||
|
||
---
|
||
|
||
## File: Shared/legal.md
|
||
|
||
# Legal TODO
|
||
|
||
This file tracks all outstanding legal, compliance, and policy requirements. None of these need to be resolved before internal development, but all must be addressed before any public launch or real-money feature enablement.
|
||
|
||
---
|
||
|
||
## Priority Order
|
||
|
||
| Priority | Item | Required Before |
|
||
|---|---|---|
|
||
| P0 | Privacy Policy | Any user data collection (even closed beta) |
|
||
| P0 | Terms of Service | Any public access |
|
||
| P0 | EULA | Thick client distribution |
|
||
| P1 | GDPR compliance | Any users in the EU/EEA |
|
||
| P1 | Stripe / payment compliance | Real-money feature enablement |
|
||
| P2 | CCPA compliance | Any users in California |
|
||
| P2 | Cookie Policy | Web client / website |
|
||
| P3 | COPPA | If under-13 users are permitted |
|
||
|
||
---
|
||
|
||
## Terms of Service (TOS)
|
||
|
||
- [ ] Draft TOS covering: account rules, prohibited conduct, content ownership, service availability, suspension/termination rights
|
||
- [ ] Define what constitutes a bannable offense (feeds into Admin tooling)
|
||
- [ ] Address virtual currency: no real-world cash value, no refunds on earned currency, Stripe purchase refund policy
|
||
- [ ] Jurisdiction and governing law (choose state/country for dispute resolution)
|
||
- [ ] Age requirement (minimum age — likely 13, or 18 for real-money purchases)
|
||
|
||
---
|
||
|
||
## End User License Agreement (EULA)
|
||
|
||
- [ ] Required before thick client is distributed publicly
|
||
- [ ] Cover: license grant (limited, non-transferable), restrictions (no reverse engineering, no cheating tools, no redistribution), termination
|
||
- [ ] Embedded in installer or presented on first launch with required acceptance
|
||
- [ ] Separate from TOS or combined — TBD
|
||
|
||
---
|
||
|
||
## Privacy Policy
|
||
|
||
- [ ] Required before any user data is collected (name, email, IP, gameplay data)
|
||
- [ ] Must cover: what data is collected, how it is used, how long it is retained, with whom it is shared (Stripe, any analytics), how users can request deletion
|
||
- [ ] Chat log retention policy must be explicitly stated (30-day hot, long-term cold archive — reason and access policy must be disclosed)
|
||
- [ ] Contact information for privacy requests
|
||
|
||
---
|
||
|
||
## GDPR (EU/EEA)
|
||
|
||
- [ ] **Right to erasure (Right to be forgotten)**: must be able to delete all user PII on request; define which data can be truly deleted vs. anonymized (e.g., transaction records may need to be kept for financial/legal reasons)
|
||
- [ ] **Data portability**: must be able to export a user's data in machine-readable format on request
|
||
- [ ] **Consent**: define consent flow for data collection; explicit opt-in for marketing
|
||
- [ ] **Data retention limits**: document and enforce retention periods per data category (auth data, gameplay data, chat logs, transaction records)
|
||
- [ ] **DPA (Data Processing Agreement)**: required if using any EU-based users with third-party processors (Stripe, any analytics)
|
||
- [ ] **Chat archive**: cold archive in remote MySQL — GDPR deletion requests must propagate to cold storage; design the deletion pipeline before launch
|
||
- [ ] Appoint a Data Protection contact point (can be internal)
|
||
|
||
---
|
||
|
||
## Stripe / Payment Compliance
|
||
|
||
- [ ] Stripe account setup and terms acceptance (Stripe Connected Accounts or standard Stripe account — TBD on business entity)
|
||
- [ ] **PCI DSS**: Stripe handles card data; our scope is SAQ A (minimal) as long as we never touch raw card numbers. Confirm no card data touches our servers.
|
||
- [ ] **Refund policy**: define refund rules for hard currency purchases (Stripe chargebacks, voluntary refunds)
|
||
- [ ] **Subscription vs. one-time**: confirm no subscription billing at launch (simplifies compliance)
|
||
- [ ] **Age gate**: real-money purchases must be restricted to users meeting minimum age requirement
|
||
- [ ] **Regional restrictions**: some jurisdictions restrict virtual currency purchases or loot boxes (Belgium, Netherlands, etc.) — review before enabling real-money features globally
|
||
- [ ] Stripe integration is **implemented but disabled** in Bazaar service; enable only after all payment compliance items are checked off
|
||
|
||
---
|
||
|
||
## CCPA (California)
|
||
|
||
- [ ] Privacy Policy must include CCPA-specific disclosures (right to know, right to delete, right to opt-out of sale of personal information)
|
||
- [ ] "Do Not Sell My Personal Information" link/flow on website if applicable
|
||
- [ ] Verify whether data sharing with Stripe constitutes a "sale" under CCPA (generally no, if it's a service provider relationship)
|
||
|
||
---
|
||
|
||
## Cookie Policy
|
||
|
||
- [ ] Required for the website (Web service)
|
||
- [ ] Identify all cookies: session cookies, analytics cookies, any third-party embeds
|
||
- [ ] Consent banner for EU visitors (GDPR cookie consent)
|
||
- [ ] Keep minimal — avoid third-party tracking cookies if possible
|
||
|
||
---
|
||
|
||
## COPPA (Under-13 Users)
|
||
|
||
- [ ] Decision needed: do we allow users under 13?
|
||
- **Option A**: Minimum age 13, enforce at registration with DOB or age gate. Simplest compliance path.
|
||
- **Option B**: Allow under-13 with verifiable parental consent. Significant compliance overhead.
|
||
- [ ] Recommendation: minimum age 13 (standard for online gaming). Real-money features age-gated to 18.
|
||
|
||
---
|
||
|
||
## Notes
|
||
|
||
- All legal documents should be reviewed by a qualified attorney before public release.
|
||
- Internal development and closed testing do not require finalized legal docs, but privacy policy and TOS should be in place before any external users access the system.
|
||
- The Admin service audit log design should account for GDPR deletion requirements — logged actions referencing a deleted user should anonymize the user reference, not block deletion.
|
||
|
||
---
|
||
|
||
## File: Shared/README.md
|
||
|
||
# Shared
|
||
|
||
Cross-cutting assets and docs used by both Client and Server.
|
||
|
||
---
|
||
|
||
## File: tools/README.md
|
||
|
||
# SOR Neural AI Training Tools
|
||
|
||
This directory contains the Python training pipeline for the SOR neural decision engine
|
||
(tiers 9-10). The workflow is:
|
||
|
||
```
|
||
self-play (admin) -> JSONL export (admin) -> train_neural.py -> model.onnx -> hot-swap (admin)
|
||
```
|
||
|
||
---
|
||
|
||
## Prerequisites
|
||
|
||
Python 3.11+ with pip:
|
||
|
||
```bash
|
||
pip install -r tools/requirements.txt
|
||
```
|
||
|
||
GPU training is supported via CUDA. Use `--cpu` to force CPU-only mode.
|
||
|
||
---
|
||
|
||
## Step 1 — Generate self-play data (Admin portal)
|
||
|
||
1. Navigate to **Admin -> AI -> Calibration**.
|
||
2. Click **Run All Pairs** (or a specific difficulty pair) to trigger in-process self-play games.
|
||
3. Wait for the run to complete — check the calibration table for results.
|
||
|
||
Alternatively, trigger a full calibration run via the API:
|
||
```
|
||
POST /api/ai/calibration/run-all
|
||
```
|
||
|
||
---
|
||
|
||
## Step 2 — Export training data (Admin portal)
|
||
|
||
1. Navigate to **Admin -> AI -> Calibration**.
|
||
2. Click **Export Training Data** and enter an output path on the server
|
||
(e.g. `/var/sor/training/data.jsonl`).
|
||
3. The exporter replays completed game sessions and writes one JSON line per action:
|
||
|
||
```json
|
||
{
|
||
"GameSessionId": "3fa85f64...",
|
||
"TurnNumber": 5,
|
||
"ActorAccountId": "...",
|
||
"Features": [0.0, 1.0, ...],
|
||
"ActionType": "AiPlayCardAction",
|
||
"ActionJson": "{}",
|
||
"Outcome": 1.0
|
||
}
|
||
```
|
||
|
||
`Outcome` is `+1.0` if the acting player won the game, `-1.0` if they lost.
|
||
|
||
---
|
||
|
||
## Step 3 — Train the model
|
||
|
||
```bash
|
||
cd /path/to/SOR
|
||
python tools/train_neural.py --data /var/sor/training/data.jsonl --out /var/sor/models/model.onnx --epochs 50 --batch-size 512 --lr 1e-3
|
||
```
|
||
|
||
### Options
|
||
|
||
| Flag | Default | Description |
|
||
|------|---------|-------------|
|
||
| `--data` | *(required)* | Path to the JSONL export file |
|
||
| `--out` | `model.onnx` | Output ONNX file path |
|
||
| `--epochs` | `50` | Number of training epochs |
|
||
| `--batch-size` | `512` | Mini-batch size |
|
||
| `--lr` | `0.001` | AdamW initial learning rate |
|
||
| `--val-split` | `0.1` | Fraction of data held out for validation |
|
||
| `--dropout` | `0.2` | Dropout probability in the MLP |
|
||
| `--seed` | `42` | Random seed |
|
||
| `--cpu` | off | Force CPU training (ignores CUDA) |
|
||
|
||
The script prints per-epoch train/val loss and marks the best checkpoint with `*`.
|
||
It restores the best weights before exporting.
|
||
|
||
### Model architecture
|
||
|
||
```
|
||
Input [1, 1024] float32 (FeatureExtractor output)
|
||
Linear 1024 -> 512 + LayerNorm + ReLU + Dropout
|
||
Linear 512 -> 256 + LayerNorm + ReLU + Dropout
|
||
Linear 256 -> 128 + LayerNorm + ReLU
|
||
Linear 128 -> 1 + Tanh
|
||
Output [1, 1] float32 (score in [-1, 1])
|
||
```
|
||
|
||
Total parameters: ~920k
|
||
|
||
---
|
||
|
||
## Step 4 — Deploy the model
|
||
|
||
### Option A: Hot-swap via admin portal (no restart)
|
||
|
||
1. Copy the `model.onnx` file to the path configured in `appsettings`:
|
||
```json
|
||
"Ai": { "NeuralModelPath": "/var/sor/models/model.onnx" }
|
||
```
|
||
2. Navigate to **Admin -> AI -> Neural Model**.
|
||
3. Click **Hot-swap Model**. The old session is disposed atomically and the new
|
||
model is loaded from disk. All subsequent tier 9-10 decisions use the new model.
|
||
|
||
### Option B: Restart the service
|
||
|
||
The model is loaded at startup by `AiNeuralStartupService`. If the file exists at the
|
||
configured path, it will be loaded automatically on the next deploy.
|
||
|
||
---
|
||
|
||
## ONNX contract
|
||
|
||
The exported model must satisfy:
|
||
|
||
| Property | Value |
|
||
|----------|-------|
|
||
| Input tensor name | `features` |
|
||
| Input shape | `[1, 1024]` (or `[batch, 1024]` with dynamic batch) |
|
||
| Input dtype | `float32` |
|
||
| Output tensor name | `score` |
|
||
| Output shape | `[1, 1]` (or `[batch, 1]`) |
|
||
| Output dtype | `float32` |
|
||
| Output range | `[-1, 1]` (tanh) |
|
||
|
||
These names are defined as constants in `NeuralModelRegistry.cs` (`InputName`, `OutputName`).
|
||
The Python script and the C# inference code must agree on these names exactly.
|
||
|
||
---
|
||
|
||
## Iterative training
|
||
|
||
For best results, run multiple rounds:
|
||
|
||
1. Start with random-engine games (all difficulties) to generate diverse data.
|
||
2. Train an initial model and deploy it.
|
||
3. Run additional self-play with the neural engine enabled (tiers 9-10 play each other).
|
||
4. Append new exports to the existing JSONL and retrain with more epochs.
|
||
5. Monitor calibration win rates in the admin portal after each deployment.
|
||
|