Skip to content

Instantly share code, notes, and snippets.

@esDotDev
Last active December 8, 2022 20:34
Show Gist options
  • Save esDotDev/0b5598b116c06c4a85cf060a27870bc1 to your computer and use it in GitHub Desktop.
Save esDotDev/0b5598b116c06c4a85cf060a27870bc1 to your computer and use it in GitHub Desktop.
Build a flash card game in React to help learn basic addition. It should show a series of 10 questions, one at a time. When all 10 questions have been answered, it should have a game over view showing their score and a button to restart the game.
import React, {useState, useEffect} from 'react';
const FlashCardGame = () => {
const [score, setScore] = useState(0);
const [quesNum, setQuesNum] = useState(0);
const [questions, setQuestions] = useState([]);
useEffect(() => {
generateQuestions();
}, [])
const generateQuestions = () => {
const tempQuestions = [];
for (let i = 0; i < 10; i++) {
const a = Math.floor(Math.random() * 10);
const b = Math.floor(Math.random() * 10);
const answer = a + b;
const question = `What is ${a} + ${b}?`;
tempQuestions.push({
question,
answer
})
}
setQuestions(tempQuestions);
}
const handleAnswer = (answer) => {
const curQues = questions[quesNum];
if (answer === curQues.answer) {
setScore(score + 1);
}
setQuesNum(quesNum + 1);
}
const handleRestart = () => {
generateQuestions();
setScore(0);
setQuesNum(0);
}
if (quesNum < 10) {
const curQues = questions[quesNum];
return (
<div>
<h1>Question {quesNum + 1}</h1>
<h2>{curQues.question}</h2>
<button onClick={() => handleAnswer('yes')}>Yes</button>
<button onClick={() => handleAnswer('no')}>No</button>
</div>
)
} else {
return (
<div>
<h1>Game Over!</h1>
<h2>Your score is {score}/10</h2>
<button onClick={handleRestart}>Restart Game</button>
</div>
)
}
}
export default FlashCardGame
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment