All files / web/src/lib/arcade/game-sdk types.ts

0% Statements 0/314
0% Branches 0/1
0% Functions 0/1
0% Lines 0/314

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
/**
 * Type definitions for the Arcade Game SDK
 * These types define the contract that all games must implement
 */

import type { ReactNode } from 'react'
import type { GameManifest } from '../manifest-schema'
import type { GameMove as BaseGameMove, GameValidator } from '../validation/types'

// Re-export manifest types
export type {
  GameManifest,
  GameResultsConfig,
  PracticeBreakConfig,
} from '../manifest-schema'
/**
 * Re-export base validation types from arcade system
 */
export type {
  GameMove,
  GameValidator,
  PracticeBreakOptions,
  TeamMoveSentinel,
  ValidationContext,
  ValidationResult,
} from '../validation/types'
export { TEAM_MOVE } from '../validation/types'

/**
 * Generic game configuration
 * Each game defines its own specific config type
 */
export type GameConfig = Record<string, unknown>

/**
 * Generic game state
 * Each game defines its own specific state type
 */
export type GameState = Record<string, unknown>

/**
 * Provider component interface
 * Each game provides a React context provider that wraps the game UI
 */
export type GameProviderComponent = (props: { children: ReactNode }) => JSX.Element

/**
 * Main game component interface
 * The root component that renders the game UI
 */
export type GameComponent = () => JSX.Element

/**
 * Complete game definition
 * This is what games export after using defineGame()
 */
export interface GameDefinition<
  TConfig extends GameConfig = GameConfig,
  TState extends GameState = GameState,
  TMove extends BaseGameMove = BaseGameMove,
> {
  /** Parsed and validated manifest */
  manifest: GameManifest

  /** React provider component */
  Provider: GameProviderComponent

  /** Main game UI component */
  GameComponent: GameComponent

  /** Server-side validator */
  validator: GameValidator<TState, TMove>

  /** Default configuration */
  defaultConfig: TConfig

  /**
   * Validate a config object at runtime
   * Returns true if config is valid for this game
   *
   * @param config - Configuration object to validate
   * @returns true if valid, false otherwise
   */
  validateConfig?: (config: unknown) => config is TConfig
}

// =============================================================================
// Game Results Reporting Types
// =============================================================================

/**
 * Individual player's result in a game session.
 * Used for both single-player (array of 1) and multiplayer games.
 */
export interface PlayerResult {
  /** Player ID */
  playerId: string
  /** Player's display name */
  playerName: string
  /** Player's emoji */
  playerEmoji: string
  /** User ID (for cross-device identification) */
  userId: string

  // === Scoring ===
  /** Player's primary score */
  score: number
  /** Rank in this game (1 = winner/best) */
  rank: number
  /** Whether this player won (for competitive games) */
  isWinner?: boolean

  // === Accuracy Metrics ===
  /** Number of correct answers/matches */
  correctCount?: number
  /** Number of incorrect attempts */
  incorrectCount?: number
  /** Total attempts made */
  totalAttempts?: number
  /** Accuracy percentage (0-100) */
  accuracy?: number

  // === Speed/Streak Metrics ===
  /** Best consecutive streak achieved */
  bestStreak?: number
  /** Average response time in ms (for speed games) */
  avgResponseTimeMs?: number

  // === Game-Specific Metrics ===
  /** Flexible key-value for game-specific player stats */
  customMetrics?: Record<string, string | number | boolean>
}

/**
 * Scoreboard category for cross-game comparison
 */
export type ScoreboardCategory =
  | 'puzzle'
  | 'memory'
  | 'speed'
  | 'strategy'
  | 'geography'
  | 'discovery'

/**
 * Game mode type
 */
export type GameModeType = 'single-player' | 'cooperative' | 'competitive' | 'turn-based'

/**
 * Result display theme
 */
export type ResultTheme = 'success' | 'good' | 'neutral' | 'needs-practice'

/**
 * Celebration animation type
 */
export type CelebrationType = 'confetti' | 'fireworks' | 'stars' | 'none'

/**
 * Optional song-specific context that a game can attach to its results report.
 *
 * The normal scoreboard fields are intentionally generic. Session songs need
 * more story-shaped evidence: memorable plays, specific items, and strategy
 * notes that can become a short lyric without inventing details. Prefer short
 * category-prefixed moments such as "Opening beat:", "Clutch moment:",
 * "Near miss:", "Clean run:", "Comeback:", and "Tough item:".
 */
export interface GameSongContext {
  /** One-sentence summary of what made this game break memorable */
  summary?: string
  /** Concrete, game-specific details worth mentioning */
  details?: string[]
  /** Dramatic beats from gameplay, ordered from most song-worthy to least */
  dramaticMoments?: string[]
  /** Strategy or skill notes used during the game */
  strategyNotes?: string[]
  /** Plain-language outcome, if different from headline/subheadline */
  outcome?: string
}

/**
 * Standard game results report that all games can produce.
 * Games implement this via their validator's getResultsReport() method.
 *
 * Designed to support:
 * - Single-player puzzle games (Card Sorting)
 * - Competitive multiplayer (Matching, Complement Race)
 * - Cooperative multiplayer (Memory Quiz, Know Your World)
 * - Turn-based strategy (Rithmomachia)
 * - Racing/speed games (Complement Race)
 */
export interface GameResultsReport {
  // === Game Identity ===
  /** Internal game name */
  gameName: string
  /** Game display name */
  gameDisplayName: string
  /** Game icon emoji */
  gameIcon: string

  // === Session Metadata ===
  /** Duration in milliseconds */
  durationMs: number
  /** Whether the game was completed normally (vs timeout/skip/resignation) */
  completedNormally: boolean
  /** Timestamp when game started */
  startedAt: number
  /** Timestamp when game ended */
  endedAt: number

  // === Game Mode ===
  /** Type of game session */
  gameMode: GameModeType
  /** Number of players who participated */
  playerCount: number

  // === Player Results ===
  /**
   * Results for each player, ordered by rank (winner first).
   * Single-player games have exactly one entry.
   * Cooperative games may share scores.
   */
  playerResults: PlayerResult[]

  // === Victory Conditions (for competitive/strategy games) ===
  /** Winner player ID (null for ties or cooperative games) */
  winnerId?: string | null
  /** How the game was won (game-specific) */
  winCondition?: string
  /** For strategy games: type of victory achieved */
  victoryType?: string

  // === Aggregate Metrics (for cooperative games or overall stats) ===
  /** Combined/team score (cooperative games) */
  teamScore?: number
  /** Combined accuracy (cooperative games) */
  teamAccuracy?: number
  /** Total items completed (e.g., regions found, pairs matched) */
  itemsCompleted?: number
  /** Total items possible */
  itemsTotal?: number
  /** Completion percentage (0-100) */
  completionPercent?: number

  // === Score Breakdown (for complex scoring like Card Sorting) ===
  /**
   * Detailed score breakdown for games with multi-factor scoring.
   * Each component contributes to the final score.
   */
  scoreBreakdown?: Array<{
    /** Name of score component */
    component: string
    /** Points from this component */
    points: number
    /** Max possible points for this component */
    maxPoints?: number
    /** Description of what this measures */
    description?: string
  }>

  // === Leaderboard Entry (for universal scoreboard) ===
  /**
   * Normalized data for universal scoreboard comparison.
   * Allows comparing across different games.
   */
  leaderboardEntry?: {
    /** Normalized score (0-100 scale for cross-game comparison) */
    normalizedScore: number
    /** Category for grouping on scoreboard */
    category: ScoreboardCategory
    /** Difficulty level played */
    difficulty?: string
    /** Whether this was a personal best */
    isPersonalBest?: boolean
  }

  // === Game-Specific Stats ===
  /**
   * Game-specific statistics for nuanced display.
   * Each entry has a label and value for rendering.
   */
  customStats?: Array<{
    label: string
    value: string | number
    /** Optional: icon or emoji to display with stat */
    icon?: string
    /** Optional: highlight this stat (e.g., "best streak") */
    highlight?: boolean
    /** Optional: group related stats together */
    group?: string
  }>

  // === Display Hints ===
  /**
   * Optional headline message (e.g., "Perfect Game!", "Great Job!")
   * Games can customize this based on performance.
   */
  headline?: string
  /** Optional subheadline */
  subheadline?: string
  /** Optional color theme for results display */
  resultTheme?: ResultTheme
  /** Optional celebration animation to show */
  celebrationType?: CelebrationType

  /**
   * Optional song-generation context. Games should populate this when their
   * normal stats are too generic to produce interesting personalized lyrics.
   */
  songContext?: GameSongContext
}

// GameResultsConfig is re-exported from manifest-schema at line 11