Create Guess the Number game using JavaScript

In this tutorial, you will learn to Create a Guess the Number game using JavaScript.
We can do it by some JavaScript method or function.

Creating Guess the Number game using JavaScript

let’s learn this with code explanation.

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);

1.Html elements retrieval :First we are accessing html elements from the DOM using “document.getElementById()”. It initializes variables to track the game state , including the answer, the number of guesses ,guessed numbers array.

2.The play function is called when the user submits a guess either by pressing Enter or clicking the “Check “ button. validates if the guess is within the valid range(1 to 100) and is a number .if not it displays a alert message . if the guess is right is displays a success message .

3.The “init()” function initializes the game when the page loads or when the user clicks the restart button .it generates a new random number as answer.

4.Even listeners are setup to handle key presses ,button clicks and triggering appropriate game actions

5.a load even listener on the window calls the “init()” function when the page loads.

Leave a Comment

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

Scroll to Top