import React, { useState, useEffect } from 'react'; import { BookOpen, CheckCircle, XCircle, Award, Loader, Flag, MessageSquare, HelpCircle, ChevronRight } from 'lucide-react'; const SpanishGame = () => { // Game states const [gameState, setGameState] = useState('welcome'); // welcome, playing, results const [questions, setQuestions] = useState([]); const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0); const [userAnswer, setUserAnswer] = useState(''); const [score, setScore] = useState(0); const [loading, setLoading] = useState(false); const [feedback, setFeedback] = useState(null); const [isChecking, setIsChecking] = useState(false); const [showConfetti, setShowConfetti] = useState(false); const totalQuestions = 10; const fifthGraderThreshold = 7; // Score needed to beat a 5th grader // Generate questions when game starts const startGame = async () => { setLoading(true); setGameState('playing'); try { await generateQuestions(); } catch (error) { console.error("Failed to generate questions:", error); } finally { setLoading(false); } }; // Generate questions using the OpenAI API const generateQuestions = async () => { try { // In a real implementation, this would call the OpenAI API // For demo purposes, we'll use predefined questions const generatedQuestions = [ { question: "¿Cómo te llamas?", correctAnswer: "Me llamo [name]", difficulty: "easy", translation: "What is your name?", hint: "Use 'Me llamo' followed by your name" }, { question: "¿Cuántos años tienes?", correctAnswer: "Tengo [number] años", difficulty: "easy", translation: "How old are you?", hint: "Use 'Tengo' followed by your age and 'años'" }, { question: "¿Cuáles son los colores de la bandera de México?", correctAnswer: "Verde, blanco y rojo", difficulty: "medium", translation: "What are the colors of the Mexican flag?", hint: "Three colors: green, white, and red in Spanish" }, { question: "Cuenta del uno al cinco en español.", correctAnswer: "Uno, dos, tres, cuatro, cinco", difficulty: "easy", translation: "Count from one to five in Spanish.", hint: "Start with 'uno'" }, { question: "¿Qué día es hoy?", correctAnswer: "Hoy es [day]", difficulty: "medium", translation: "What day is today?", hint: "Start with 'Hoy es' followed by the day of the week" }, { question: "Nombra tres animales en español.", correctAnswer: "Perro, gato, pájaro", difficulty: "medium", translation: "Name three animals in Spanish.", hint: "Common animals include 'perro' (dog), 'gato' (cat)" }, { question: "¿Cuál es la capital de España?", correctAnswer: "Madrid", difficulty: "medium", translation: "What is the capital of Spain?", hint: "It's the same word in English and Spanish" }, { question: "Traduce: 'I like to play soccer with my friends.'", correctAnswer: "Me gusta jugar al fútbol con mis amigos", difficulty: "hard", translation: "Translate: 'I like to play soccer with my friends.'", hint: "Start with 'Me gusta jugar'" }, { question: "Conjuga el verbo 'hablar' en presente para 'yo'.", correctAnswer: "Yo hablo", difficulty: "medium", translation: "Conjugate the verb 'hablar' in present tense for 'I'.", hint: "Change the ending from '-ar' to '-o'" }, { question: "¿Cómo se dice 'goodbye' en español?", correctAnswer: "Adiós", difficulty: "easy", translation: "How do you say 'goodbye' in Spanish?", hint: "It's a common farewell word" } ]; setQuestions(generatedQuestions); } catch (error) { console.error("Error generating questions:", error); throw error; } }; // In a real implementation, this would call the OpenAI API to check the answer const checkAnswer = async () => { if (!userAnswer.trim()) return; setIsChecking(true); try { // Simulate API call delay await new Promise(resolve => setTimeout(resolve, 1000)); const currentQuestion = questions[currentQuestionIndex]; // Simple check - in a real app, use AI to evaluate answer quality const isCorrect = userAnswer.toLowerCase().includes( currentQuestion.correctAnswer.toLowerCase().split('[')[0].trim() ); if (isCorrect) { setScore(prevScore => prevScore + 1); setFeedback({ correct: true, message: "¡Correcto! Great job!" }); } else { setFeedback({ correct: false, message: `Not quite. A good answer would be: "${currentQuestion.correctAnswer}"` }); } // Move to next question after a delay setTimeout(() => { if (currentQuestionIndex < totalQuestions - 1) { setCurrentQuestionIndex(prevIndex => prevIndex + 1); setUserAnswer(''); setFeedback(null); } else { setGameState('results'); if (score + (isCorrect ? 1 : 0) >= fifthGraderThreshold) { setShowConfetti(true); } } setIsChecking(false); }, 2000); } catch (error) { console.error("Error checking answer:", error); setFeedback({ correct: false, message: "Error checking your answer. Please try again." }); setIsChecking(false); } }; const handleSubmit = (e) => { e.preventDefault(); checkAnswer(); }; const resetGame = () => { setGameState('welcome'); setQuestions([]); setCurrentQuestionIndex(0); setUserAnswer(''); setScore(0); setFeedback(null); setShowConfetti(false); }; // Confetti component for celebration const Confetti = () => { useEffect(() => { const confettiCount = 200; const container = document.querySelector('.confetti-container'); for (let i = 0; i < confettiCount; i++) { const confetti = document.createElement('div'); confetti.className = 'confetti'; confetti.style.left = `${Math.random() * 100}%`; confetti.style.animationDelay = `${Math.random() * 5}s`; confetti.style.backgroundColor = `hsl(${Math.random() * 360}, 100%, 50%)`; container.appendChild(confetti); } return () => { const confettis = document.querySelectorAll('.confetti'); confettis.forEach(c => c.remove()); }; }, []); return
; }; // Difficulty badge component const DifficultyBadge = ({ difficulty }) => { const colors = { easy: 'bg-green-100 text-green-800 border-green-200', medium: 'bg-yellow-100 text-yellow-800 border-yellow-200', hard: 'bg-red-100 text-red-800 border-red-200' }; return ( {difficulty.charAt(0).toUpperCase() + difficulty.slice(1)} ); }; // Render different game screens based on state const renderGameContent = () => { switch (gameState) { case 'welcome': return (
Spanish Challenge

¿Puedes hablar español mejor que un estudiante de quinto grado?

Can You Speak Spanish Better Than a 5th Grader?

10 Questions

Test your Spanish skills with questions a 5th grader should know

Helpful Hints

Get assistance if you're stuck on a challenging question

Get Scored

See if your Spanish skills beat a typical 5th grader

); case 'playing': if (loading) { return (

Generating questions...

Preparing your Spanish challenge

); } if (questions.length === 0) { return (

Failed to load questions. Please try again.

); } const currentQuestion = questions[currentQuestionIndex]; return (
{/* Progress bar */}
Question {currentQuestionIndex + 1} of {totalQuestions}
Score: {score}
{/* Question card */}

{currentQuestion.question}

{currentQuestion.translation}

setUserAnswer(e.target.value)} className="w-full p-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#4ECDC4] focus:border-transparent transition-all text-lg" placeholder="Type your answer in Spanish..." disabled={isChecking} />
{feedback && (
{feedback.correct ? ( ) : ( )}

{feedback.message}

)}
); case 'results': const beatFifthGrader = score >= fifthGraderThreshold; return (
{showConfetti && }
{beatFifthGrader ? (
) : (
)}

{beatFifthGrader ? "¡Felicidades! You beat a 5th grader!" : "Not quite 5th grade level yet!"}

{score} / {totalQuestions}
0 {fifthGraderThreshold} 5th Grade Level {totalQuestions}

{beatFifthGrader ? `¡Excelente! You scored ${score} out of ${totalQuestions}, which is better than an average 5th grader!` : `You scored ${score} out of ${totalQuestions}. A typical 5th grader scores at least ${fifthGraderThreshold}. ¡Sigue practicando! (Keep practicing!)`}

); default: return
Something went wrong
; } }; return (
{renderGameContent()}
); }; export default SpanishGame;