Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Typing Game using React
Next article icon

Math Sprint Game using React

Last Updated : 22 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
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:

  • NPM & NodeJS
  • ReactJS
  • HTML, CSS, and JavaScript

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


Next Article
Typing Game using React

Y

yadavjiwkmb
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • ReactJS-Projects

Similar Reads

  • Typing Game using React
    React Typing Game is a fun and interactive web application built using React. It tests and improves the user's typing speed and accuracy by presenting sentences for the user to type within a specified time limit. The game provides real-time feedback by highlighting any mistakes made by the user, mak
    4 min read
  • PacMan game using React
    Let's make a Pacman game using React for a fun and nostalgic web experience. We'll include classic features like the maze, pellets, and ghosts, and learn some cool React stuff along the way. The game will be easy to play with arrow keys, and we'll add extras like keeping score and power pellets. It'
    7 min read
  • Shopping Cart app using React
    In this article, we will create an Interactive and Responsive Shopping Cart Project Application using the famous JavaScript FrontEnd library ReactJS. We have named or Application as "GeeksforGeeks Shopping Cart". The application or project which we have developed mainly focuses on the functional com
    9 min read
  • Hangman game using React
    React provides an excellent platform for creating interactive and engaging web applications. In this tutorial, you will be guided to build a classic Hangman game using React. Hangman is a word-guessing game that is not only entertaining but also a great way to practice your React skills. Preview of
    5 min read
  • Math Sprint Game in VueJS
    The Math Sprint Game is a simple web-based game designed to help users practice basic arithmetic operations such as addition and subtraction in a fun and interactive way. It generates random math problems for the users to solve within the limited time frame testing their mental math skills and agili
    3 min read
  • Memory Game from scratch using React
    In this article, we will create a Memory game using ReactJS. A memory game is a famous game in which a pair of cards are placed in front of a player with their face down. The two pairs are always going to have the same content. The player has the choice to select any two cards at a time and check if
    6 min read
  • Tenzies Game using ReactJS
    In this article, we are going to implement Tenzied Games using React JS. Tenzies is a fast-paced and fun game where players have to race to roll a specific combination with a set of ten dice. As we are building this game with ReactJS, we are using the functional components to build the application,
    7 min read
  • Paint App using ReactJS
    In this article, we will be building a simple paint application that lets you draw just like in MS-Paint. Through this article, we will learn how to implement and work with canvas in React.js. Our app contains two sections, one for drawing and the other is a menu where the user can customize the bru
    4 min read
  • Scientific Calculator using React
    A scientific calculator is a tool, this project will be developed using REACT which performs basic and advanced calculations. In this project, our goal is to develop a web-based calculator using React. This calculator will have the capability to handle a range of functions. Preview of final output:
    5 min read
  • Tic Tac Toe Game Using Typescript
    In this tutorial, We are going to create an interactive tic-tac-toe game in which two users can play against each other and the winner will be displayed to the winning user. What We’re Going to CreateWe’ll build a Tic Tac Toe game focusing on event handling, DOM manipulation, and core game logic con
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences