Open In App

Math Sprint Game using React

Last Updated : 22 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create a Math Sprint Game Using ReactJS. Math Sprint is a fun and challenging game where players have to solve math problems within a time limit to earn points. This game presents random math questions with four options. Players click the correct answer, and if correct, it’s acknowledged, otherwise, an incorrect answer message is shown.

Preview of Final Output: Let us have a look at how the final application will look like:

sprint

Prerequisites:

Approach to Create a Math Sprint Game in React:

  • The Math Sprint Game is a React-based web app where players solve math problems against the clock.
  • It dynamically generates problems, manages time, scores correct answers, and displays scores.
  • React components and state management ensure smooth gameplay, offering a fun and challenging math experience.

Steps to Create Math Sprint Game in React:

Step 1: Create a new React JS project using the following command

npx create-react-app <<Project_Name>>

Step 2: Change to the project directory.

cd <<Project_Name>>

Step 3: Add the Game.js , Timer.js and Question.js file in the src directory.

Project Structure:
math

The updated dependencies in package.json will look like this:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Explanation of Components:

  • App.js : This component is responsible, for rendering the layout of the application.
  • Game.js :The Game component is the main component of the Math Sprint Game. It manages the game’s state, including the score, and renders other components such as the Timer and Question.
  • Timer.js :The Timer component is responsible for displaying the time remaining in the game. It utilizes React’s useState and useEffect hooks to manage the time state.
  • Question.js :The Question component generates math questions for the player to solve. It utilizes React’s useState hook to manage the state of the numbers in the question and the user’s answer.
  • App.css : app.css will enhance the visual appearance of our game interface.

Example: Below is an example of creating a Math Sprint Game in React.

CSS
/* App.css */

body {
    font-family: 'Arial', sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
    background: linear-gradient(to bottom, #ef4444, #f59e0b, #9333ea);
    color: #333;
}

.container {
    text-align: center;
    background-color: rgba(255, 255, 255, 0.9);
    /* Adjust opacity as needed */
    padding: 40px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    max-width: 600px;
    /* Adjust as needed */
    width: 90%;
    /* Adjust as needed */
}

.box {
    background-color: #f9fafb;
    border: 2px solid #e4e7eb;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
    text-align: left;
}

h1 {
    font-size: 36px;
    color: #333;
    margin-bottom: 20px;
}

p {
    font-size: 18px;
    margin: 10px 0;
}

.options {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.option {
    margin: 0 10px;
    padding: 10px 20px;
    cursor: pointer;
    background-color: #f39c12;
    color: #fff;
    border: 1px solid transparent;
    border-radius: 5px;
    font-size: 20px;
    transition: background-color 0.3s ease, border-color 0.3s ease;
}

.option:hover {
    background-color: #d35400;
}

button {
    margin-top: 40px;
    padding: 5px 30px;
    cursor: pointer;
    background-color: #3498db;
    color: #fff;
    border: 1px solid transparent;
    border-radius: 5px;
    font-weight: bold;
    font-size: 21px;
    transition: background-color 0.3s ease, border-color 0.3s ease;
}

button:hover {
    background-color: #2980b9;
}

.score {
    margin-top: 40px;
    font-weight: bold;
    font-size: 28px;
    color: #27ae60;
}

.timer {
    margin-top: 20px;
    font-size: 24px;
    color: #333;
}

.result {
    margin-top: 20px;
    font-size: 24px;
    color: red;
}

.correct {
    color: green;
}

.incorrect {
    color: red;
}
JavaScript
// App.js

import React from 'react';
import Game from './Game.js';
import './App.css';

function App() {
    return (
        <div className="container">
            <div className="box">
                <h1>Math Sprint Game</h1>
                <Game />
            </div>
        </div>
    );
}

export default App;
JavaScript
// Game.js

import React, { useState } from 'react';
import Timer from './Timer.js';
import Question from './Question.js';

const Game = () => {
    const [score, setScore] = useState(0);
    const [gameOver, setGameOver] = useState(false);

    const handleAnswer = (isCorrect) => {
        if (isCorrect) {
            setScore(score + 1);
        }
    };

    const handleTimeOver = () => {
        setGameOver(true);
    };

    const restartGame = () => {
        setScore(0);
        setGameOver(false);
    };

    return (
        <div>
            {!gameOver ? (
                <>
                    <Timer onTimeOver={handleTimeOver} />
                    <Question onAnswer={handleAnswer}
                        timeOver={gameOver} />
                    <p>Score: {score}</p>
                </>
            ) : (
                <>
                    <p>Time's up! Your final score is {score}.</p>
                    <button onClick={restartGame}>
                        Restart Game
                    </button>
                </>
            )}
        </div>
    );
};

export default Game;
JavaScript
// Timer.js

import React, {
    useState,
    useEffect
} from 'react';

const Timer = ({ onTimeOver }) => {
    const [timeLeft, setTimeLeft] = useState(15);

    useEffect(() => {
        const timer = setInterval(() => {
            if (timeLeft > 0) {
                setTimeLeft(timeLeft - 1);
            } else {
                clearInterval(timer);
                onTimeOver();
            }
        }, 1000);

        return () => clearInterval(timer);
    }, [timeLeft, onTimeOver]);

    return <div>Time Left: {timeLeft} seconds</div>;
};

export default Timer;
JavaScript
// Qestion.js

import React, { useState } from 'react';

const Question = ({ onAnswer, timeOver }) => {
    const [num1, setNum1] = useState(Math.ceil(Math.random() * 10));
    const [num2, setNum2] = useState(Math.ceil(Math.random() * 10));
    const [operator, setOperator] = useState('+');
    const [userAnswer, setUserAnswer] = useState('');
    const [isCorrect, setIsCorrect] = useState(null);

    const generateQuestion = () => {
        setNum1(Math.ceil(Math.random() * 10));
        setNum2(Math.ceil(Math.random() * 10));
        const operators = ['+', '-', '*', '/'];
        const randomOperator = operators[Math.floor(Math.random() * operators.length)];
        setOperator(randomOperator);
        setUserAnswer('');
    };

    const checkAnswer = () => {
        let correctAnswer;
        switch (operator) {
            case '+':
                correctAnswer = num1 + num2;
                break;
            case '-':
                correctAnswer = num1 - num2;
                break;
            case '*':
                correctAnswer = num1 * num2;
                break;
            case '/':
                correctAnswer = num1 / num2;
                break;
            default:
                correctAnswer = num1 + num2;
                break;
        }
        if (parseFloat(userAnswer) === correctAnswer) {
            setIsCorrect(true);
            onAnswer(true);
        } else {
            setIsCorrect(false);
            onAnswer(false);
        }
        generateQuestion();
    };

    return (
        <div>
            {timeOver ? (
                <p>Time's up! Game Over</p>
            ) : (
                <>
                    <p>{num1} {operator} {num2} = </p>
                    <input
                        type="text"
                        value={userAnswer}
                        onChange={
                            (e) => setUserAnswer(e.target.value)}
                    />
                    <button onClick={checkAnswer}>Submit</button>
                    {isCorrect !== null && (
                        <p>
                            {isCorrect ? 'Correct!' : 'Incorrect!'}
                        </p>
                    )}
                </>
            )}
        </div>
    );
};

export default Question;

Start your application using the following commad.

npm start

Output: Open web-browser and type the following URL http://localhost:3000/

bandicam2024-03-2203-56-57-170-ezgifcom-video-to-gif-converter



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads