By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > How To Make Number Guessing Game JavaScript
JavaScript

How To Make Number Guessing Game JavaScript

Admin
Last updated: 2022/11/25 at 4:58 AM
Admin
Share
12 Min Read
Number Guessing Game JavaScript

Hello Guys 👋 In this post, We will learn how to make Number Guessing Game JavaScript. In the Number guessing game basically, we have to guess a number between 1 to 100. When we enter any number between 1 to 100. If a guessed number is higher than the actual number then show a message YOUR GUESS IS TOO HIGH and if a number is lower then show a message YOUR GUESS IS TOO LOW. If we number is correct then show a message YOU GUESSED CORRECTLY! and the score is increased and also we have 5 lifeLine in this game. If lifeLine is zero then the game is over. Also, we store high scores in local storage.

Contents
👉 Create a ðŸ“‚index.html👉 Now Create a ðŸ“‚style.css👉 Create  ðŸ“‚index.js FileRandom Number GenerateShow Guessed NumbersCheck Is Game OverSave HighScoreShow HighScoreCheck HighScoreContinue ButtonRetry ButtonNumber Guessing Game JavaScript(Source Code)

In this project, we will use HTML, CSS, and basic Vanilla Javascript. In this project, you will learn new things like local storage, DOM manipulation, etc. This project our main focus is javascript.

You can see the Demo Here Number Guessing Game JavaScript

👉 Create a ðŸ“‚index.html

Here we are making attractive UI

Number Guessing game javascript
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Number Guessing Game in JavaScript</title>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" integrity="sha512-PgQMlq+nqFLV4ylk1gwUOgm6CtIIXkKwaIHp/PAIWHzig/lKZSEGKEysh0TCVbHJXCLN7WetD8TFecIky75ZfQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  </head>
  <body>
    <div class="game-wrapper">
      <div class="game-data">
        <h5 class="feedback-label"></h5>
        <div class="score-data">
          <h5 class="score-label">Score:<span class="score"> 0</span></h5>
          <h5 class="score-label">High Score:<span class="high-score"> 0</span></h5>
        </div>
        <div class="lives-data">
            <i class="fas fa-heart heart"></i>
          <span class="lives-count"> 5</span>
        </div>
        <div class="hidden-number-wrapper">
          <div class="hidden-number-wrapper-inner">
            <h5 class="hidden-number-label">?</h5>
          </div>
        </div>
      </div>
      <div class="game-controls">
        <input type="text" class="guess" placeholder="Enter your guess">
        <button class="btn btn-blue play">Play</button>
        <button class="btn btn-orange continue" disabled>Continue</button>
      </div>
      <div class="numbers-guess">
       <h5> Guessed numbers are: <span class="guessed-number"></span></h5>
      </div>
    </div>

    <div class="modal">
      <h5 class="game-over">Game over</h5>
      <p>Would you like to continue?</p>
      <button class="btn btn-blue retry">Retry</button>
    </div>


    <!-- Scripts -->
    <script src="index.js"></script>
  </body>
</html>

👉 Now Create a ðŸ“‚style.css

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
}

body {
  font-family: sans-serif;
  background-color: #212a37;
  color: #fff;
  font-size: 1.6rem;
  height: 100vh;
  display: grid;
  place-content: center;
  letter-spacing: 2px;
  text-transform: uppercase;
}

span {
  display: inline-block;
}

.game-wrapper {
  background-color: #101829;
  width: 40rem;
  border-radius: 4px;
  padding: 1.5rem;
}

.game-data {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 2.5rem 1rem;
}

.feedback-label {
  background-color: #1d293b;
  padding: 2rem 1rem;
  grid-column: 1/-1;
  text-align: center;
  line-height: 0;
}

.score-data {
  grid-column: 1/3;
  display: flex;
  flex-direction: column;
}

.score-label {
  margin-bottom: 0.5rem;
}

.lives-data {
  grid-column: 3/-1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.heart {
  font-size: 2.6rem;
  margin-right: 0.5rem;
  color: #c92626;
}

.hidden-number-wrapper {
  display: flex;
  grid-column: 1/-1;
  padding: 0 0 2.5rem;
}

.hidden-number-wrapper-inner {
  width: 10rem;
  height: 10rem;
  border: 1rem solid #5bb1fc;
  border-radius: 50%;
  display: flex;
  margin: auto;
  box-shadow: 0 0 0.7rem #5bb1fc;
}

.hidden-number-label {
  margin: auto;
  font-size: 1.8rem;
}

.game-controls {
  display: flex;
  padding: 1rem 0;
}

.game-controls > *:not(:last-child) {
  margin-right: 1rem;
}

.guess {
  border-radius: 4px;
  border: none;
  outline: none;
  background-color: #1d293b;
  color: #fff;
  padding: 1rem;
}

.btn {
  border: none;
  border-radius: 4px;
  color: #fff;
  width: 100%;
  height: 3.5rem;
  cursor: pointer;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 1rem;
}

.btn.btn-blue {
  background-color: #5bb1fc;
  box-shadow: 0 0 0.7rem #5bb1fc, 0 4px #2d57bb;
}

.btn.btn-orange {
  background-color: #f59555;
  box-shadow: 0 0 0.7rem #f59555, 0 4px #e25521;
}

.btn:active {
  transform: translateY(2px);
}

.btn.btn-blue:active {
  box-shadow: 0 0 0.7rem #5bb1fc, 0 2px #2d57bb;
}

.btn.btn-orange:active {
  box-shadow: 0 0 0.7rem #f59555, 0 2px #e25521;
}

.btn:disabled {
  opacity: 0.5;
  cursor: default;
}

.modal {
  width: 100%;
  height: 100vh;
  background-color: #212a37;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transform: scale(0);
  z-index: 9999;
  transition: opacity 0.5s;
  display: grid;
  place-content: center;
  gap: 1.5rem 0;
  text-align: center;
}

.modal.active {
  opacity: 1;
  transform: scale(1);
}
.game-over {
  font-size: 6rem;
}
.numbers-guess{
  margin-top: 20px;
  opacity: 0;
}

💡 Now It’s time For Javascript Code 😎.

👉 Create  ðŸ“‚index.js File

The first thing I did was to create references to the necessary HTML elements.

const numberLabel = document.querySelector(".hidden-number-label");
const playBtn = document.querySelector(".play");
const continueBtn = document.querySelector(".continue");
const inputGuessNumber = document.querySelector(".guess");
const message = document.querySelector(".feedback-label");
const scoreLabel = document.querySelector(".score");
const highScoreLabel = document.querySelector(".high-score");
const livesCountLabel = document.querySelector(".lives-count");
const gameOver = document.querySelector(".modal");
const game = document.querySelector(".game-wrapper");
const retry = document.querySelector(".retry");
const numbersGuess = document.querySelector(".numbers-guess");
const guessdNumbersLabel = document.querySelector(".guessed-number");

var guessedNumbers = [];
var score = 0;
var lifLine = 5;

Here we take blank array guessedNumbers for storing guessed numbers in an array. A score variable for storing scores and in a lifeline variable store a 5. When the user guesses a wrong number then the lifeline is decreased. And when the lifeline is zero then the game is over.

Random Number Generate
function randomNumberGenerate() {
  return Math.floor(Math.random() * 100) + 1;
}

The random() function is used to generate a random number between 0 (inclusive) and 1 (exclusive). This generated number is then multiplied by 100 and added 1 to generate numbers from 1 – 100. The floor() function is used to return the number to the nearest integer (downwards). The value will not be rounded if the passed argument is an integer.

Show Guessed Numbers
function showGuessedNumbers(guessedNumbers) {
  numbersGuess.style.opacity = 1;
  guessdNumbersLabel.innerHTML = guessedNumbers;
}

In showGuessedNumbers() function, we need to pass an argument guessedNumbers. When the user guesses a wrong number. Then the number is stored in the guessedNumbers array and shown in guessdNumbersLabel. Here if the user guesses the wrong number then we show the number guesses div.

Check Is Game Over
function checkIsGameOver(lifLine) {
  if (lifLine === 0) {
    gameOver.style.opacity = 1;
    gameOver.style.transform = "scale(1)";
    game.style.opacity = 0;
  }
}

Here checkIsGameOver() function take argument lifeline. Here when the user guesses a wrong number then the lifeline is decreased. If lifeline is zero then the game is over so here lifeline is zero then game over model opacity is 1 and game wrapper opacity is 0.

Save HighScore
function saveHighScore(score) {
  localStorage.setItem("highscore", score);
}

saveHighScore() function for save high score in local storage. Here saveHighScore() function take one argument score. The setItem() method sets the value of the specified Storage Object item.

Show HighScore
function showHighScore() {
  const highScore = localStorage.getItem("highscore");
  console.log("highscore", highScore);
  console.log("highscore", typeof highScore);
  if (highScore == null) {
    highScoreLabel.innerHTML = 0;
  } else {
    highScoreLabel.innerHTML = highScore;
  }
}

showHighScore() function for showing high score. In this function, we first get the high score value from local storage using getItem() method. Here getItem() method returns a value of the specified Storage Object item. Here we check when the high score value is null then showing in highScoreLabel is zero otherwise shows a high score number. Let me explain when we first time we call this function then we haven’t any high score value means the high score value is null. After when the user plays the game and corrects guess a number then we assign score value in high score variable.

Check HighScore
function checkHighScore(score) {
  const highScore = JSON.parse(localStorage.getItem("highscore"));
  if (score > highScore) {
    saveHighScore(score);
    showHighScore();
  }
}

Here checkHighScore() function check if the score is greater than the high score then we update the high score and show a high score.

👉 Here we defined all functions now. It’s time to add an event listener in the play button.

var answer = randomNumberGenerate();
playBtn.addEventListener("click", () => {
  const user_guess = inputGuessNumber.value;
  if (user_guess < 1 || user_guess > 100) {
    alert("Please Enter A Number Between 1 to 100.");
  } else {
    if (user_guess < answer) {
      message.innerHTML = "Your guess is too low";
      lifLine--;
      checkIsGameOver(lifLine);
      livesCountLabel.innerHTML = lifLine;
      guessedNumbers.push(user_guess);
      showGuessedNumbers(guessedNumbers);
    } else if (user_guess > answer) {
      message.innerHTML = "Your guess is too high";
      lifLine--;
      checkIsGameOver(lifLine);
      livesCountLabel.innerHTML = lifLine;
      guessedNumbers.push(user_guess);
      showGuessedNumbers(guessedNumbers);
    } else if (user_guess == answer) {
      message.innerHTML = "You Guessed correctly!";
      numberLabel.innerHTML = user_guess;
      playBtn.disabled = true;
      continueBtn.disabled = false;
      score++;
      scoreLabel.innerHTML = score;
      checkHighScore(score);
    }
  }
  inputGuessNumber.value = "";
});

Here we store a random number in the answer variable. Now we add the event listener in playBtn. In the event listener function, we store user guessed number in the user_guess variable. And check condition if the user enters zero and greater than 100 then we show an alert message.

Now we check the condition if user_guess is lower than the answer. Then show message Your guess is too low and also lifeline is decreased. And pass lifeline in checkIsGameOver() function. Where check if lifeline is zero then the game is over. After show guess numbers. Also similar in user_guess is higher than answer.

When the user guesses the right answer then show the message You Guessed correctly. After we disabled the play button and enabled the continue button so the user can play again. Here we also checkHighScore() function for update high score value.

Continue Button
continueBtn.addEventListener("click", () => {
  answer = randomNumberGenerate();
  console.log("answer contimue", answer);
  playBtn.disabled = false;
  continueBtn.disabled = true;
  numberLabel.innerHTML = "?";
  guessedNumbers = [];
  numbersGuess.style.opacity = 0;
  guessdNumbersLabel.innerHTML = "";
});

Now we add an event listener in the continue button for play again. Here we generate a new random number and store it in the answer variable. After enable the play button and disabled the continue button and also reset guessed numbers.

Retry Button
retry.addEventListener("click", () => {
  gameOver.style.opacity = 0;
  gameOver.style.transform = "scale(0)";
  game.style.opacity = 1;
  message.innerHTML = "";
  lifLine = 5;
  score = 0;
  guessedNumbers = [];
  livesCountLabel.innerHTML = lifLine;
  scoreLabel.innerHTML = score;
  numbersGuess.style.opacity = 0;
  guessdNumbersLabel.innerHTML = "";
  showHighScore();
});

In this function reset all values like a lifeline, score, etc.

Number Guessing Game JavaScript(Source Code)

Get Source Code

👉 watch the video Number Guessing Game Javascript

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

TAGGED: Number Guessing Game JavaScript
Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Posted by Admin
Follow:
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
Previous Article random hex color generator in javascript How to Make Random Hex Color Generator In JavaScript
Next Article digital clock in javascript How to Make a Simple Digital Clock In JavaScript
32 Comments 32 Comments
  • Pingback: How to Make a Simple Digital Clock In JavaScript - rocoderes
  • Pingback: How to Make Number Memorising Game In JavaScript - rocoderes
  • Pingback: How To Make Christmas Website Design - rocoderes
  • Pingback: How to Make Automatic Image Slider in JavaScript - rocoderes
  • Pingback: How to Make a Flying Helicopter with HTML, CSS - rocoderes
  • Pingback: How To Make Signup Form In HTML, CSS And JavaScript - rocoderes
  • Pingback: How to Make Responsive Login Form In HTML & CSS - rocoderes
  • Pingback: How to Make Animated Registration Form in HTML - rocoderes
  • Pingback: How to Make Responsive Registration Form in HTML - rocoderes
  • Pingback: How to Make Sliding Login and Registration Form In HTML - rocoderes
  • Pingback: How To Make Animated Pricing Card Using HTML & CSS - rocoderes
  • Pingback: How To Make Responsive Pricing Table Card Using HTML & CSS - rocoderes
  • Pingback: How To Make Responsive Testimonials Section Using Only HTML & CSS - rocoderes
  • Pingback: How To Make Chemical Reaction With CSS Animation - rocoderes
  • Pingback: How To Make Skeleton Loading Animation With CSS & JS - rocoderes
  • Pingback: How To Make Ball Animation With CSS Keyframes - rocoderes
  • Pingback: HOW TO MAKE JUMPING SQUARE ANIMATION WITH HTML AND CSS - rocoderes
  • Pingback: How To Make Pokémon Game Using HTML CSS JavaScript - rocoderes
  • Pingback: HOW TO MAKE 3D SWING WITH HTML AND CSS - rocoderes
  • Pingback: How To Make iPhone 12 3D Cube with JavaScript - rocoderes
  • Pingback: How To Make Random Joke Generator Using JavaScript Fetch API - rocoderes
  • Pingback: HOW TO MAKE BICYCLE USING HTML AND CSS - rocoderes
  • Pingback: How To Make Whack-A-Mole Game Using HTML CSS & JavaScript - rocoderes
  • Pingback: How To Make Star Rating Using HTML, CSS & JavaScript - rocoderes
  • Pingback: How To Make Custom Cursor with HTML, CSS and JavaScript - rocoderes
  • Pingback: How To Make Dark/Light Theme Switcher in CSS and JavaScript? - rocoderes
  • Pingback: How To Make Client-Side Form Validation Using JavaScript - rocoderes
  • Pingback: HOW TO MAKE 3D POP UP CARD USING CSS ANIMATION - rocoderes
  • Pingback: How To Make Responsive Services Box With Flip Animation - rocoderes
  • Pingback: How To Make Slide Puzzle Game in JavaScript - rocoderes
  • Pingback: How To Make Calendar With Dark Mode Using JavaScript - rocoderes
  • Pingback: How To Make a Stopwatch In JavaScript 2022 - rocoderes

Leave a Reply Cancel reply

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

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?