HomeJavascriptGuess The Number Game Javascript

Guess The Number Game Javascript

Hi everyone. Welcome to another new tutorial by Coding Artist. In this tutorial, we take a look at how to build the ‘Guess the Number’ game. To build this project we need HTML, CSS, and Javascript. Get ready to learn something fun and exciting today. Do not forget to check out this playlist [here] which includes numerous projects based on HTML, CSS, and Javascript to improve your skills.

Video Tutorial:

If you are interested to learn by watching a video tutorial rather than reading a blog post you can check out the video down below. Also, subscribe to my YouTube channel where I post new tutorials every alternate day.

 

Project Folder Structure:

Let us explore the project folder structure. The project folder consists of 3 files. The HTML file creates the elements required to build the structure and layout of our project. Next, the CSS file styles the elements that we have created with CSS. And Finally, Javascript adds functionality to our project.

HTML:

We begin with the HTML code. Copy the code below and paste it into your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Guess The Number Game</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div id="game">
        <h3>
          I am thinking of a number between 1-100.<br />
          Can you guess it?
        </h3>
        <div class="input-wrapper">
          <input type="number" placeholder="00" id="guess" />
          <button id="check-btn">Guess</button>
        </div>
        <p id="no-of-guesses">No. Of Guesses: 0</p>
        <p id="guessed-nums">Guessed Numbers are: None</p>
      </div>
      <button id="restart">Restart</button>
      <div class="result">
        <div id="hint"></div>
      </div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we style our game using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #3c6fff;
}
.container {
  width: min(90%, 31.25em);
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  background-color: #ffffff;
  padding: 4em 2em;
  border-radius: 0.5em;
  box-shadow: -1.5em -1.5em #202020;
  text-align: center;
}
h3 {
  font-size: 1.2em;
  font-weight: 500;
  line-height: 2em;
  color: #303030;
}
.input-wrapper {
  width: 70%;
  display: grid;
  grid-template-columns: 2fr 3fr;
  gap: 1em;
  margin: 3em auto 1.5em auto;
}
input[type="number"] {
  width: 100%;
  padding: 1em;
  font-size: 1.2em;
  text-align: center;
  border: 2px solid #adaeae;
  border-radius: 0.3em;
  outline: none;
  appearance: text-field;
  -moz-appearance: textfield;
}
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
input[type="number"]:focus {
  border-color: #3c6fff;
}
button {
  font-size: 1em;
  background-color: #3c6fff;
  color: #ffffff;
  border: none;
  outline: none;
  border-radius: 0.5em;
  font-weight: 500;
  cursor: pointer;
}
#restart {
  margin: 0 auto 0 auto;
  padding: 0.8em 1em;
  display: none;
}
.result {
  margin-top: 1em;
}
p {
  font-size: 1em;
  font-weight: 400;
  color: #565b70;
  word-break: break-all;
}
.error,
.success {
  padding: 0.5em 0;
  border-radius: 0.3em;
  margin-bottom: 1em;
  animation: pop 0.4s forwards;
  transform: scale(0);
}
.error {
  background-color: #ffcbcb;
  color: #ff3e3e;
}
.success {
  background-color: #b9ffd5;
  color: #05c451;
}
@keyframes pop {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(1);
  }
}

Javascript:

Finally, we add functionality using Javascript. Once again copy the code below and paste it into your script file

First, we begin with references to HTML elements. When the window loads we call the “init” function which sets a random number and initializes the count for the number of guesses and an array for storing the guesses, which are then displayed on our webpage. When the user clicks the check button or if the user presses the “Enter” key we call the “play” function which first checks for invalid input then adds the guess to the guesses array and increments the guess count. Further, we check if the user’s guess is equal to the answer or not. If not we check whether the guess is high or low and display the associated message with the number of guesses and the guess. If the answer is similar to the solution then we display the win message and stop execution. Finally, we define a function for the “Restart” button to restart the game.

const hint = document.getElementById("hint");
const noOfGuessesRef = document.getElementById("no-of-guesses");
const guessedNumsRef = document.getElementById("guessed-nums");
const restartButton = document.getElementById("restart");
const game = document.getElementById("game");
const guessInput = document.getElementById("guess");
const checkButton = document.getElementById("check-btn");

let answer, noOfGuesses, guessedNumsArr;

const play = () => {
  const userGuess = guessInput.value;
  if (userGuess < 1 || userGuess > 100 || isNaN(userGuess)) {
    alert("Please enter a valid number between 1 and 100.");
    return;
  }
  guessedNumsArr.push(userGuess);
  noOfGuesses += 1;
  if (userGuess != answer) {
    if (userGuess < answer) {
      hint.innerHTML = "Too low. Try Again!";
    } else {
      hint.innerHTML = "Too high. Try Again!";
    }
    noOfGuessesRef.innerHTML = `<span>No. Of Guesses:</span> ${noOfGuesses}`;
    guessedNumsRef.innerHTML = `<span>Guessed Numbers are: </span>${guessedNumsArr.join(
      ","
    )}`;
    hint.classList.remove("error");
    setTimeout(() => {
      hint.classList.add("error");
    }, 10);
  } else {
    hint.innerHTML = `Congratulations!<br>The number was <span>${answer}</span>.<br>You guessed the number in <span>${noOfGuesses} </span>tries.`;
    hint.classList.add("success");
    game.style.display = "none";
    restartButton.style.display = "block";
  }
};

const init = () => {
  console.log("Game Started");
  answer = Math.floor(Math.random() * 100) + 1;
  console.log(answer);
  noOfGuesses = 0;
  guessedNumsArr = [];
  noOfGuessesRef.innerHTML = "No. Of Guesses: 0";
  guessedNumsRef.innerHTML = "Guessed Numbers are: None";
  guessInput.value = "";
  hint.classList.remove("success", "error");
};

guessInput.addEventListener("keydown", (event) => {
  if (event.keyCode === 13) {
    event.preventDefault();
    play();
  }
});

restartButton.addEventListener("click", () => {
  game.style.display = "grid";
  restartButton.style.display = "none";
  hint.innerHTML = "";
  hint.classList.remove("success");
  init();
});

checkButton.addEventListener("click", play);
window.addEventListener("load", init);

Go ahead and customize the project the way you like. If you have any queries, suggestions or feedback comment them below. Download the source code by clicking on the ‘ Download Code’ button below.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

fourteen − ten =

Most Popular