Search
Close this search box.
Search
Close this search box.

Creating Math Game Using HTML, CSS & JavaScript

Math Game

Table of Contents

Introduction

Hi there, coders! Welcome to the blog for cssiseasy. We’re going to use HTML, CSS, and JavaScript to build a math game today. In order to solve equations and win the math game, the player must enter the correct number or operator. The user hits “Submit” to send their feedback after finishing.

Also, Read – Email Validation Using JavaScript

A result screen appears as soon as the user presses the submit button. A restart button and the outcome will be shown on the result screen.

Game

These assignments vary in difficulty from easy to hard. All JavaScript skill levels can benefit from this playlist. Therefore, this playlist contains something for every level of JavaScript developer, from novice to expert.

Project Details:
Step 1: Using HTML (Hypertext Markup Language), we can create a structure with a list of important features and components that will help in the construction of the math game project.

Step 2: After that, we’ll style or design the math game project using CSS (Cascading Style Sheets) to add the proper padding and alignment.

Step 3: Lastly, we will add user-side functionality to the JavaScript math game projects using JavaScript (JS).

I hope you now have a better understanding of the JavaScript math game project.

Math Game Html Code

				
					<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Math Game</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <h3>Fill In The Blank With Correct Number Or Operator</h3>
      <div id="question"></div>
      <button id="submit-btn">Submit</button>
      <p id="error-msg">Some Demo Error Message</p>
    </div>
    <div class="controls-container">
      <p id="result"></p>
      <button id="start-btn">Start Game</button>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>
				
			

To build a container for our math quiz, we’ll use a div tag inside the body element along with the container class. The header will then be set to a h3 using the <h3> tag selector, indicating the h3. Lastly, the div element containing the ID question will be used to construct a div container inside the body tag for the quiz questions. We will now use the submit button to build the start and submit buttons for our math quiz.

First, we will design the project’s framework for the arithmetic game. We’ve used all the required components and functionalities to create the structure, as you can see in the code above.Now let’s learn how to apply styles and rearrange tags in the CSS section using coding.

Html Code Output:-

HTML Output

CSS Code for Math Game

				
					* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #f4c531;
}
.container {
  background-color: #ffffff;
  width: 90%;
  max-width: 31.25em;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  padding: 5em 3em;
  border-radius: 0.5em;
}
.container h3 {
  font-size: 1.2em;
  color: #23234c;
  text-align: center;
  font-weight: 500;
  line-height: 1.8em;
}
.container #submit-btn {
  font-size: 1.2em;
  font-weight: 500;
  display: block;
  margin: 0 auto;
  background-color: #f4c531;
  border-radius: 0.3em;
  border: none;
  outline: none;
  cursor: pointer;
  color: #23234c;
  padding: 0.6em 2em;
}
#error-msg {
  text-align: center;
  margin-top: 1em;
  background-color: #ffdde0;
  color: #d62f2f;
  padding: 0.2em 0;
}
.container #question {
  background-color: #eeedf1;
  font-size: 2em;
  font-weight: 600;
  color: #23234c;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 1.4em 0 1em 0;
  padding: 1em 0;
}
.container input {
  font-size: 1em;
  font-weight: 600;
  width: 2.35em;
  color: #23234c;
  text-align: center;
  padding: 0 0.2em;
  border: none;
  background-color: transparent;
  border-bottom: 0.12em solid #23234c;
  margin: 0 0.25em;
}
.container input:focus {
  border-color: #f4c531;
  outline: none;
}
/*Hide Number Arrows*/
.container input[type="number"] {
  -moz-appearance: textfield;
}
.container input[type="number"]::-webkit-outer-spin-button,
.container input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
.controls-container {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background-color: #f4c531;
  height: 100%;
  width: 100%;
  top: 0;
}
#start-btn {
  font-size: 1.2em;
  font-weight: 500;
  background-color: #ffffff;
  color: #23234c;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 0.8em 1.8em;
  border-radius: 0.3em;
}
#result {
  margin-bottom: 1em;
  font-size: 1.5em;
  color: #23234c;
}
#result span {
  font-weight: 600;
}

.hide {
  display: none;
}
				
			

Step 1:

Set padding and margin to zero using the universal selection (*). Next, set box-sizing to “border-box” using the box-sizing property. Additionally, we’ll use the font-family property to change the font family to “Poppins”.

We’ll set the game page’s background color to yellow using the body tag selector.

				
					* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #f4c531;
}
				
			

Step 2:

We’ll change the container’s width to 90% and its background color to white using the class selector (container) and the background-color property. We are going to translate it by -50% from all sides using the transform feature. We’ll add a border radius of 0.5 rem using the border-radius feature.

HTML Code Project for Math Games: 

We will now style our operator’s component parts. The font-size property will be used to set the font size to 1.2 em, the color property will be used to make the heading black, and the font-weight property will be used to make the font weight 500.

				
					.container {
  background-color: #ffffff;
  width: 90%;
  max-width: 31.25em;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  padding: 5em 3em;
  border-radius: 0.5em;
}
.container h3 {
  font-size: 1.2em;
  color: #23234c;
  text-align: center;
  font-weight: 500;
  line-height: 1.8em;
}
.container #submit-btn {
  font-size: 1.2em;
  font-weight: 500;
  display: block;
  margin: 0 auto;
  background-color: #f4c531;
  border-radius: 0.3em;
  border: none;
  outline: none;
  cursor: pointer;
  color: #23234c;
  padding: 0.6em 2em;
}
#error-msg {
  text-align: center;
  margin-top: 1em;
  background-color: #ffdde0;
  color: #d62f2f;
  padding: 0.2em 0;
}
.container #question {
  background-color: #eeedf1;
  font-size: 2em;
  font-weight: 600;
  color: #23234c;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 1.4em 0 1em 0;
  padding: 1em 0;
}
.container input {
  font-size: 1em;
  font-weight: 600;
  width: 2.35em;
  color: #23234c;
  text-align: center;
  padding: 0 0.2em;
  border: none;
  background-color: transparent;
  border-bottom: 0.12em solid #23234c;
  margin: 0 0.25em;
}
.container input:focus {
  border-color: #f4c531;
  outline: none;
}
				
			

Step 3:

The ID selector will now be used to specify the text size, background color, padding, and margin of our button when we apply styles to our results, buttons, and display. We’ll add these important styles to our buttons and result display to improve user experience.

				
					#start-btn {
  font-size: 1.2em;
  font-weight: 500;
  background-color: #ffffff;
  color: #23234c;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 0.8em 1.8em;
  border-radius: 0.3em;
}
#result {
  margin-bottom: 1em;
  font-size: 1.5em;
  color: #23234c;
}
#result span {
  font-weight: 600;
}

.hide {
  display: none;
}
				
			

The CSS code comes next. As was already said, we styled the math game project’s structure and rearranged it to make sure it was positioned correctly and wasn’t interfered with by the wrong CSS elements. After structuring the homepage using HTML and styling it with CSS, it’s time to add functionality to our JavaScript math game project.

CSS Code Output:-

CSS Output

JavaScript Code for Math Game:-

				
					let operators = ["+", "-", "*"];
const startBtn = document.getElementById("start-btn");
const question = document.getElementById("question");
const controls = document.querySelector(".controls-container");
const result = document.getElementById("result");
const submitBtn = document.getElementById("submit-btn");
const errorMessage = document.getElementById("error-msg");
let answerValue;
let operatorQuestion;

//Random Value Generator
const randomValue = (min, max) => Math.floor(Math.random() * (max - min)) + min;

const questionGenerator = () => {
  //Two random values between 1 and 20
  let [num1, num2] = [randomValue(1, 20), randomValue(1, 20)];

  //For getting random operator
  let randomOperator = operators[Math.floor(Math.random() * operators.length)];

  if (randomOperator == "-" && num2 > num1) {
    [num1, num2] = [num2, num1];
  }

  //Solve equation
  let solution = eval(`${num1}${randomOperator}${num2}`);

  //For placing the input at random position
  //(1 for num1, 2 for num2, 3 for operator, anything else(4) for solution)
  let randomVar = randomValue(1, 5);

  if (randomVar == 1) {
    answerValue = num1;
    question.innerHTML = `<input type="number" id="inputValue" placeholder="?"\> ${randomOperator} ${num2} = ${solution}`;
  } else if (randomVar == 2) {
    answerValue = num2;
    question.innerHTML = `${num1} ${randomOperator}<input type="number" id="inputValue" placeholder="?"\> = ${solution}`;
  } else if (randomVar == 3) {
    answerValue = randomOperator;
    operatorQuestion = true;
    question.innerHTML = `${num1} <input type="text" id="inputValue" placeholder="?"\> ${num2} = ${solution}`;
  } else {
    answerValue = solution;
    question.innerHTML = `${num1} ${randomOperator} ${num2} = <input type="number" id="inputValue" placeholder="?"\>`;
  }

  //User Input Check
  submitBtn.addEventListener("click", () => {
    errorMessage.classList.add("hide");
    let userInput = document.getElementById("inputValue").value;
    //If user input is not empty
    if (userInput) {
      //If the user guessed correct answer
      if (userInput == answerValue) {
        stopGame(`Yippie!! <span>Correct</span> Answer`);
      }
      //If user inputs operator other than +,-,*
      else if (operatorQuestion && !operators.includes(userInput)) {
        errorMessage.classList.remove("hide");
        errorMessage.innerHTML = "Please enter a valid operator";
      }
      //If user guessed wrong answer
      else {
        stopGame(`Opps!! <span>Wrong</span> Answer`);
      }
    }
    //If user input is empty
    else {
      errorMessage.classList.remove("hide");
      errorMessage.innerHTML = "Input Cannot Be Empty";
    }
  });
};

//Start Game
startBtn.addEventListener("click", () => {
  operatorQuestion = false;
  answerValue = "";
  errorMessage.innerHTML = "";
  errorMessage.classList.add("hide");
  //Controls and buttons visibility
  controls.classList.add("hide");
  startBtn.classList.add("hide");
  questionGenerator();
});

//Stop Game
const stopGame = (resultText) => {
  result.innerHTML = resultText;
  startBtn.innerText = "Restart";
  controls.classList.remove("hide");
  startBtn.classList.remove("hide");
};
				
			

We will first construct a set of operators using the let keyword, and then we will use document.answerValue and operatorValue are two more variables that we’ll generate using the getElementById attribute to pick all HTML elements. They will be used in our math game.

We’ll now ask the user to guess a number after obtaining a random value between 1 and 20 using the Math.random function. Should the estimated number coincide with the value, the function will assess and determine if the solution is accurate or not. In addition to creating a function to launch the game and display whether the answer is incorrect, we’ll also include an event listener to allow estimates to be entered into our function in order to submit an estimated amount.

We have introduced logical and programmed additions in accordance with the criteria with certain conditions in the project’s final step, JavaScript. In the continuous part, we’ve incorporated a question generator that will continuously generate questions based on user activity. Let’s look at the completed HTML, CSS, and JavaScript (source code) math game project.

Final Output

See the Pen Math Game by Harsh Sawant (@harshh9) on CodePen.

Code by: Harsh Sawant

Project Link – Codepen

Written by: cssiseasy

We have successfully used HTML, CSS, and JavaScript (source code) to develop our arithmetic game. This project is free to use for your own purposes, and the link to the code pen is included with the lines of code that correspond to the code.

Facebook
Twitter
LinkedIn
Telegram
Email
WhatsApp

1 thought on “Creating Math Game Using HTML, CSS & JavaScript”

  1. Pingback: Use JavaScript to Set the Cursor Position in the Input

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top