All files / web/src/arcade-games/type-racer-jr Validator.ts

42.57% Statements 255/599
31.42% Branches 11/35
31.25% Functions 5/16
42.57% Lines 255/599

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 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 6001x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x                                                 1x 1x                                                                   1x 1x                                                                                                                       1x 1x                                                 1x 1x                                 1x 1x                                                                                                                             1x 1x                                     1x 1x     1x 1x                                             1x 1x                                                                                       1x 1x 2x 2x 2x 2x 2x     2x 2x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x               1x 1x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x       1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * Type Racer Jr. - Server-side Validator
 *
 * Validates all game moves and state transitions.
 * Runs on both client (optimistic) and server (authoritative).
 */
 
import type { GameValidator, PracticeBreakOptions, ValidationResult } from '@/lib/arcade/game-sdk'
import type { GameResultsReport, PlayerResult } from '@/lib/arcade/game-sdk/types'
import {
  finalizeSongContext,
  pluralize,
  songDetail,
  songList,
  songMoment,
} from '@/lib/arcade/song-context'
import {
  type DifficultyLevel,
  type TypeRacerJrConfig,
  type TypeRacerJrMove,
  type TypeRacerJrState,
  TypeRacerJrStateSchema,
} from './types'
import { pickWords, type DifficultyLevel as WordDifficultyLevel } from './words'
 
const PRACTICE_BREAK_DEFAULTS: TypeRacerJrConfig = {
  gameMode: 'free-play',
  timeLimit: null,
  startingDifficulty: 'level1',
  wordCount: 5,
  keyboardLayout: 'qwerty',
  showVirtualKeyboard: false,
}
 
function difficultyToWordLevel(d: DifficultyLevel): WordDifficultyLevel {
  return d
}
 
export class TypeRacerJrValidator implements GameValidator<TypeRacerJrState, TypeRacerJrMove> {
  stateSchema = TypeRacerJrStateSchema as unknown as import('zod').ZodType<TypeRacerJrState>
 
  validateMove(
    state: TypeRacerJrState,
    move: TypeRacerJrMove,
    _context?: { userId?: string; playerOwnership?: Record<string, string> }
  ): ValidationResult {
    switch (move.type) {
      case 'START_GAME':
        return this.validateStartGame(state, move.data)
      case 'COMPLETE_WORD':
        return this.validateCompleteWord(state, move.data)
      case 'ADVANCE_DIFFICULTY':
        return this.validateAdvanceDifficulty(state, move.data)
      case 'END_GAME':
        return this.validateEndGame(state, move.data)
      case 'SET_CONFIG':
        return this.validateSetConfig(state, move.data.field, move.data.value)
      case 'RESET_GAME':
        return this.validateResetGame(state)
      default:
        return {
          valid: false,
          error: `Unknown move type: ${(move as TypeRacerJrMove).type}`,
        }
    }
  }
 
  private validateStartGame(
    state: TypeRacerJrState,
    data: {
      wordQueue: typeof state.wordQueue
      playerMetadata: typeof state.playerMetadata
    }
  ): ValidationResult {
    if (state.gamePhase !== 'setup') {
      return { valid: false, error: 'Can only start from setup phase' }
    }

    if (!Array.isArray(data.wordQueue) || data.wordQueue.length === 0) {
      return { valid: false, error: 'Word queue is required' }
    }

    return {
      valid: true,
      newState: {
        ...state,
        gamePhase: 'playing',
        wordQueue: data.wordQueue,
        currentWordIndex: 0,
        completedWords: [],
        totalStars: 0,
        bestStreak: 0,
        consecutiveCleanWords: 0,
        usedWords: data.wordQueue.map((w) => w.word),
        gameStartTime: Date.now(),
        currentWordStartTime: Date.now(),
        playerMetadata: data.playerMetadata,
        endReason: null,
      },
    }
  }
 
  private validateCompleteWord(
    state: TypeRacerJrState,
    data: {
      word: string
      stars: number
      mistakeCount: number
      durationMs: number
    }
  ): ValidationResult {
    if (state.gamePhase !== 'playing') {
      return {
        valid: false,
        error: 'Can only complete words during playing phase',
      }
    }

    const currentWord = state.wordQueue[state.currentWordIndex]
    if (!currentWord || currentWord.word !== data.word) {
      return { valid: false, error: 'Word does not match current word' }
    }

    const completedWord = {
      word: data.word,
      emoji: currentWord.emoji,
      stars: data.stars,
      mistakeCount: data.mistakeCount,
      durationMs: data.durationMs,
    }

    const newConsecutiveClean = data.mistakeCount === 0 ? state.consecutiveCleanWords + 1 : 0
    const newBestStreak = Math.max(state.bestStreak, newConsecutiveClean)
    const nextWordIndex = state.currentWordIndex + 1

    // Check if all words done (free-play mode)
    const allWordsDone = nextWordIndex >= state.wordQueue.length

    const newState: TypeRacerJrState = {
      ...state,
      completedWords: [...state.completedWords, completedWord],
      currentWordIndex: nextWordIndex,
      totalStars: state.totalStars + data.stars,
      consecutiveCleanWords: newConsecutiveClean,
      bestStreak: newBestStreak,
      currentWordStartTime: allWordsDone ? null : Date.now(),
    }

    // Auto-end if all words completed
    if (allWordsDone) {
      return {
        valid: true,
        newState: {
          ...newState,
          gamePhase: 'results',
          endReason: 'all-words-done',
        },
      }
    }

    return { valid: true, newState }
  }
 
  private validateAdvanceDifficulty(
    state: TypeRacerJrState,
    data: { newDifficulty: DifficultyLevel; newWords: typeof state.wordQueue }
  ): ValidationResult {
    if (state.gamePhase !== 'playing') {
      return {
        valid: false,
        error: 'Can only advance difficulty during playing phase',
      }
    }

    // Append new words to queue
    const newQueue = [...state.wordQueue, ...data.newWords]

    return {
      valid: true,
      newState: {
        ...state,
        currentDifficulty: data.newDifficulty,
        wordQueue: newQueue,
        usedWords: [...state.usedWords, ...data.newWords.map((w) => w.word)],
        consecutiveCleanWords: 0,
      },
    }
  }
 
  private validateEndGame(
    state: TypeRacerJrState,
    data: { reason: 'timer-expired' | 'all-words-done' | 'player-quit' }
  ): ValidationResult {
    if (state.gamePhase !== 'playing') {
      return { valid: false, error: 'Can only end game during playing phase' }
    }

    return {
      valid: true,
      newState: {
        ...state,
        gamePhase: 'results',
        endReason: data.reason,
      },
    }
  }
 
  private validateSetConfig(
    state: TypeRacerJrState,
    field: string,
    value: unknown
  ): ValidationResult {
    if (state.gamePhase !== 'setup') {
      return { valid: false, error: 'Can only change config in setup phase' }
    }

    switch (field) {
      case 'gameMode':
        if (!['free-play', 'beat-the-clock'].includes(value as string)) {
          return { valid: false, error: 'Invalid game mode' }
        }
        return {
          valid: true,
          newState: {
            ...state,
            gameMode: value as TypeRacerJrState['gameMode'],
            // Set default time limit for beat-the-clock
            timeLimit: value === 'beat-the-clock' ? (state.timeLimit ?? 60) : null,
            // Set default word count for free-play
            wordCount: value === 'free-play' ? (state.wordCount ?? 5) : null,
          },
        }

      case 'timeLimit':
        if (value !== null && ![60, 90, 120].includes(value as number)) {
          return { valid: false, error: 'Invalid time limit' }
        }
        return {
          valid: true,
          newState: {
            ...state,
            timeLimit: value as TypeRacerJrState['timeLimit'],
          },
        }

      case 'startingDifficulty':
        if (!['level1', 'level2', 'level3'].includes(value as string)) {
          return { valid: false, error: 'Invalid difficulty level' }
        }
        return {
          valid: true,
          newState: {
            ...state,
            currentDifficulty: value as DifficultyLevel,
          },
        }

      case 'wordCount':
        if (value !== null && (typeof value !== 'number' || value < 1 || value > 20)) {
          return { valid: false, error: 'Invalid word count' }
        }
        return {
          valid: true,
          newState: { ...state, wordCount: value as number | null },
        }

      default:
        return { valid: false, error: `Unknown config field: ${field}` }
    }
  }
 
  private validateResetGame(state: TypeRacerJrState): ValidationResult {
    return {
      valid: true,
      newState: {
        ...state,
        gamePhase: 'setup',
        wordQueue: [],
        currentWordIndex: 0,
        completedWords: [],
        totalStars: 0,
        bestStreak: 0,
        consecutiveCleanWords: 0,
        usedWords: [],
        gameStartTime: null,
        currentWordStartTime: null,
        endReason: null,
      },
    }
  }
 
  isGameComplete(state: TypeRacerJrState): boolean {
    return state.gamePhase === 'results'
  }
 
  getInitialState(config: TypeRacerJrConfig): TypeRacerJrState {
    return {
      gamePhase: 'setup',
      gameMode: config.gameMode,
      timeLimit: config.timeLimit,
      wordCount: config.wordCount,
      keyboardLayout: config.keyboardLayout,
      showVirtualKeyboard: config.showVirtualKeyboard,
      currentDifficulty: config.startingDifficulty,
      consecutiveCleanWords: 0,
      wordQueue: [],
      currentWordIndex: 0,
      completedWords: [],
      usedWords: [],
      totalStars: 0,
      bestStreak: 0,
      gameStartTime: null,
      currentWordStartTime: null,
      playerId: '',
      playerMetadata: {},
      endReason: null,
    }
  }
 
  getInitialStateForPracticeBreak(
    config: Partial<TypeRacerJrConfig>,
    options: PracticeBreakOptions
  ): TypeRacerJrState {
    const fullConfig: TypeRacerJrConfig = {
      ...PRACTICE_BREAK_DEFAULTS,
      ...config,
    }

    const wordCount = fullConfig.wordCount ?? 5
    const words = pickWords(difficultyToWordLevel(fullConfig.startingDifficulty), wordCount)

    const playerId = options.playerId
    const playerMetadata = {
      [playerId]: {
        id: playerId,
        name: options.playerName || 'Player',
        emoji: '⌨️',
        userId: playerId,
      },
    }

    return {
      gamePhase: 'playing',
      gameMode: fullConfig.gameMode,
      timeLimit: fullConfig.timeLimit,
      wordCount: wordCount,
      keyboardLayout: fullConfig.keyboardLayout,
      showVirtualKeyboard: fullConfig.showVirtualKeyboard,
      currentDifficulty: fullConfig.startingDifficulty,
      consecutiveCleanWords: 0,
      wordQueue: words,
      currentWordIndex: 0,
      completedWords: [],
      usedWords: words.map((w) => w.word),
      totalStars: 0,
      bestStreak: 0,
      gameStartTime: Date.now(),
      currentWordStartTime: Date.now(),
      playerId,
      playerMetadata,
      endReason: null,
    }
  }
}
 
function formatDuration(ms: number): string {
  const totalSeconds = Math.floor(ms / 1000)
  const minutes = Math.floor(totalSeconds / 60)
  const seconds = totalSeconds % 60
  if (minutes > 0) {
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  }
  return `${seconds}s`
}
 
function formatCompletedWord(word: TypeRacerJrState['completedWords'][number]) {
  return `${word.emoji} ${word.word}`.trim()
}
 
function buildTypeRacerSongContext(
  state: TypeRacerJrState,
  wordsTyped: number,
  totalMistakes: number,
  accuracy: number,
  headline: string
): NonNullable<GameResultsReport['songContext']> {
  const completedWords = state.completedWords
  const firstWord = completedWords[0]
  const finalWord = completedWords[completedWords.length - 1]
  const cleanWords = completedWords.filter((word) => word.mistakeCount === 0)
  const trickiestWord = [...completedWords].sort(
    (a, b) => b.mistakeCount - a.mistakeCount || b.durationMs - a.durationMs
  )[0]
  const firstMistakeIndex = completedWords.findIndex((word) => word.mistakeCount > 0)
  const cleanAfterMistake =
    firstMistakeIndex >= 0
      ? completedWords.slice(firstMistakeIndex + 1).find((word) => word.mistakeCount === 0)
      : undefined
  const remainingWords = Math.max(0, state.wordQueue.length - wordsTyped)
  const nextWord = state.wordQueue[wordsTyped]?.word
  const cleanRun = wordsTyped > 0 && totalMistakes === 0
 
  return finalizeSongContext({
    summary: `${wordsTyped} ${pluralize(wordsTyped, 'word')} typed, ${state.totalStars} stars, ${accuracy}% typing accuracy`,
    details: [
      firstWord ? songDetail('Opening word', firstWord.word) : undefined,
      finalWord
        ? songDetail(
            'Final word',
            `${finalWord.word} (${finalWord.mistakeCount} ${pluralize(finalWord.mistakeCount, 'mistake')}, ${finalWord.stars} ${pluralize(finalWord.stars, 'star')})`
          )
        : undefined,
      songList(
        'Words typed',
        completedWords.map((word) => word.word),
        8
      ),
      songList('Clean words', cleanWords.map(formatCompletedWord), 5),
      trickiestWord && trickiestWord.mistakeCount > 0
        ? songDetail(
            'Tough word',
            `${trickiestWord.word} with ${trickiestWord.mistakeCount} ${pluralize(
              trickiestWord.mistakeCount,
              'mistake'
            )}`
          )
        : undefined,
    ],
    dramaticMoments: [
      firstWord ? songMoment('Opening beat', `first word was "${firstWord.word}"`) : undefined,
      cleanRun
        ? songMoment(
            'Clean run',
            `no mistakes across ${wordsTyped} ${pluralize(wordsTyped, 'word')}`
          )
        : undefined,
      state.bestStreak > 1
        ? songMoment('Strategy', `built a ${state.bestStreak}-word clean streak`)
        : undefined,
      trickiestWord && trickiestWord.mistakeCount > 0
        ? songMoment(
            'Tough item',
            `"${trickiestWord.word}" took ${trickiestWord.mistakeCount} ${pluralize(
              trickiestWord.mistakeCount,
              'mistake'
            )}`
          )
        : undefined,
      cleanAfterMistake
        ? songMoment('Comeback', `after a mistake, "${cleanAfterMistake.word}" landed clean`)
        : undefined,
      remainingWords === 1
        ? songMoment('Near miss', `one word left${nextWord ? `: "${nextWord}"` : ''}`)
        : undefined,
      finalWord
        ? songMoment(
            'Clutch moment',
            `final word was "${finalWord.word}" with ${finalWord.mistakeCount} ${pluralize(
              finalWord.mistakeCount,
              'mistake'
            )}`
          )
        : undefined,
    ],
    strategyNotes: [
      songDetail('Typing level', state.currentDifficulty),
      songDetail('Keyboard layout', state.keyboardLayout),
      cleanRun
        ? 'Typed carefully enough to keep every completed word clean'
        : totalMistakes > 0
          ? `Recovered from ${totalMistakes} total ${pluralize(totalMistakes, 'mistake')}`
          : undefined,
    ],
    outcome:
      remainingWords === 0 && wordsTyped > 0
        ? `finished ${wordsTyped} typed ${pluralize(wordsTyped, 'word')}`
        : headline,
  })
}
 
// Create validator instance
const validator = new TypeRacerJrValidator()
 
// Attach getResultsReport as a non-interface method (same pattern as memory-quiz)
;(validator as any).getResultsReport = (
  state: TypeRacerJrState,
  _config: TypeRacerJrConfig
): GameResultsReport => {
  const startedAt = state.gameStartTime ?? Date.now()
  const endedAt = Date.now()
  const durationMs = endedAt - startedAt
 
  const wordsTyped = state.completedWords.length
  const totalMistakes = state.completedWords.reduce((sum, w) => sum + w.mistakeCount, 0)
  const totalLetters = state.completedWords.reduce((sum, w) => sum + w.word.length, 0)
  const accuracy =
    totalLetters > 0 ? Math.round(((totalLetters - totalMistakes) / totalLetters) * 100) : 0
 
  const playerResults: PlayerResult[] = [
    {
      playerId: state.playerId || 'player',
      playerName: Object.values(state.playerMetadata)[0]?.name ?? 'Player',
      playerEmoji: '⌨️',
      userId: state.playerId || 'player',
      score: state.totalStars,
      rank: 1,
      isWinner: true,
      correctCount: wordsTyped,
      incorrectCount: totalMistakes,
      totalAttempts: wordsTyped,
      accuracy,
      bestStreak: state.bestStreak,
    },
  ]
 
  let headline: string
  let resultTheme: GameResultsReport['resultTheme']
  let celebrationType: GameResultsReport['celebrationType']
 
  if (accuracy >= 95 && wordsTyped >= 5) {
    headline = 'Perfect Typing!'
    resultTheme = 'success'
    celebrationType = 'confetti'
  } else if (accuracy >= 80) {
    headline = 'Great Typing!'
    resultTheme = 'good'
    celebrationType = 'stars'
  } else if (wordsTyped >= 3) {
    headline = 'Nice Try!'
    resultTheme = 'neutral'
    celebrationType = 'none'
  } else {
    headline = 'Keep Practicing!'
    resultTheme = 'needs-practice'
    celebrationType = 'none'
  }
 
  const customStats: GameResultsReport['customStats'] = [
    {
      label: 'Words',
      value: wordsTyped,
      icon: '📝',
      highlight: wordsTyped >= 5,
    },
    {
      label: 'Stars',
      value: `${state.totalStars}`,
      icon: '⭐',
      highlight: state.totalStars >= wordsTyped * 2,
    },
    {
      label: 'Accuracy',
      value: `${accuracy}%`,
      icon: '🎯',
      highlight: accuracy >= 90,
    },
    { label: 'Time', value: formatDuration(durationMs), icon: '⏱️' },
  ]
 
  if (state.bestStreak > 1) {
    customStats.push({
      label: 'Best Streak',
      value: state.bestStreak,
      icon: '🔥',
      highlight: true,
    })
  }
 
  return {
    gameName: 'type-racer-jr',
    gameDisplayName: 'Type Racer Jr.',
    gameIcon: '⌨️',
    durationMs,
    completedNormally: state.endReason === 'all-words-done' || state.endReason === 'timer-expired',
    startedAt,
    endedAt,
    gameMode: 'single-player',
    playerCount: 1,
    playerResults,
    winnerId: null,
    itemsCompleted: wordsTyped,
    itemsTotal: state.wordQueue.length,
    completionPercent:
      state.wordQueue.length > 0 ? Math.round((wordsTyped / state.wordQueue.length) * 100) : 0,
    leaderboardEntry: {
      normalizedScore: accuracy,
      category: 'speed',
      difficulty: state.currentDifficulty,
    },
    customStats,
    headline,
    subheadline: `${wordsTyped} words in ${formatDuration(durationMs)}`,
    resultTheme,
    celebrationType,
    songContext: buildTypeRacerSongContext(state, wordsTyped, totalMistakes, accuracy, headline),
  }
}
 
export const typeRacerJrValidator = validator