All files / web/src/app/arcade/complement-race/hooks useGameLoop.ts

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

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                                                                                                                                           
import { useCallback, useEffect } from 'react'
import { useComplementRace } from '@/arcade-games/complement-race/Provider'

export function useGameLoop() {
  const { state, dispatch } = useComplementRace()

  // Generate first question when game begins
  useEffect(() => {
    if (state.gamePhase === 'playing' && !state.currentQuestion) {
      dispatch({ type: 'NEXT_QUESTION' })
    }
  }, [state.gamePhase, state.currentQuestion, dispatch])

  const nextQuestion = useCallback(() => {
    if (!state.isGameActive) return
    dispatch({ type: 'NEXT_QUESTION' })
  }, [state.isGameActive, dispatch])

  const submitAnswer = useCallback(
    (answer: number) => {
      if (!state.currentQuestion) return

      const isCorrect = answer === state.currentQuestion.correctAnswer

      if (isCorrect) {
        // Update score, streak, progress
        // TODO: Will implement full scoring in next step
        dispatch({ type: 'SUBMIT_ANSWER', answer })

        // Move to next question
        dispatch({ type: 'NEXT_QUESTION' })
      } else {
        // Reset streak
        // TODO: Will implement incorrect answer handling
        dispatch({ type: 'SUBMIT_ANSWER', answer })
      }
    },
    [state.currentQuestion, dispatch]
  )

  const startCountdown = useCallback(() => {
    // Trigger countdown phase
    dispatch({ type: 'START_COUNTDOWN' })

    // Start 3-2-1-GO countdown (lines 11163-11211)
    let count = 3
    const countdownInterval = setInterval(() => {
      if (count > 0) {
        // TODO: Play countdown sound
        count--
      } else {
        // GO!
        // TODO: Play start sound
        clearInterval(countdownInterval)

        // Start the actual game after GO animation (1 second delay)
        setTimeout(() => {
          dispatch({ type: 'BEGIN_GAME' })
        }, 1000)
      }
    }, 1000)
  }, [dispatch])

  return {
    nextQuestion,
    submitAnswer,
    startCountdown,
  }
}