Simple Javascript Number Guessing Game (Free Download)

Welcome to a tutorial on how to create a simple Javascript number guessing game. So you have mastered the basics of Javascript and want to test out your newfound code ninja powers? Maybe take the first step into game development?

Well, this guide may not be what some of you guys are expecting – There is no graphics and no artificial intelligence programming here. But it does walk you through how to put the basics together to create a simple “hello world” game. Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

 

 

DOWNLOAD & DEMO

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

NUMBER GUESSING GAME DEMO

Guesses – 0

 

 

JAVASCRIPT NUMBER GUESSING GAME

With that, let us now get into more details on how the number guessing game works.

 

PART 1) HTML INTERFACE

guess.html
<form id="guess-wrap" onsubmit="return false;">
  <input id="guess-num" type="number" required min="0" max="100" value="0">
  <div id="guess-txt">
    <div id="guess-tries">Guesses - <i>0</i></div>
    <div id="guess-hint"></div>
  </div>
  <input id="guess-btn" type="submit" value="Make a Guess (0 to 100)">
</form>

That’s right, there are only a few components here.

  • <input id="guess-num"> Number field to input the number.
  • <div id="guess-tries"> The number of guesses so far.
  • <div id="guess-hint"> Used to display hints, if the number is too high or too low.
  • <input id="guess-btn"> “Make a guess” and “reset game” button.

 

 

PART 2) GAME INIT & PROPERTIES

guess.js
var guess = {
  // (A) PROPERTIES
  // (A1) HTML ELEMENTS
  hform : null,  // number guess form
  hnum : null,   // number input field
  htries : null, // number of tries
  hhint : null,  // hint
  hbtn : null,   // guess/reset button
 
  // (A2) FLAGS
  min : 0,     // min allowed number
  max : 0,     // max allowed number
  jackpot : 0, // the correct number
  guesses : 0, // total nunmber of guesses made
 
  // (B) INITIALIZE
  init : () => {
    // (B1) GET HTML ELEMENTS
    guess.hform = document.getElementById("guess-wrap");
    guess.hnum = document.getElementById("guess-num");
    guess.htries = document.querySelector("#guess-tries i");
    guess.hhint = document.getElementById("guess-hint");
    guess.hbtn = document.getElementById("guess-btn");
 
    // (B2) MIN/MAX NUMBER
    guess.min = Math.ceil(guess.hnum.min);
    guess.max = Math.floor(guess.hnum.max);
 
    // (B3) RESET GAME
    guess.reset();
  },
  // ...
};
window.addEventListener("load", guess.init);

Not going to explain the Javascript line by line, but a quick summary.

  • The entire game mechanics is contained within the var guess = {} object.
  • (A) A whole bunch of game flags and properties.
    • (A1) References back to the HTML elements.
    • (A2) Game flags – The min/max allowed number, the current “Jackpot” number, and the total number of guesses.
  • (B) On window load, init() will run. Pretty self-explanatory – Get all the HTML elements and reset the game.

 

 

PART 3) RESET GAME

guess.js
// (C) RESET GAME
reset : () => {
  // (C1) RESET FLAGS
  guess.guesses = 0;
  // credits: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
  guess.jackpot = Math.floor(Math.random() * (guess.max - guess.min + 1)) + guess.min;
  console.log("Jackpot - " + guess.jackpot); // for the cheaters
 
  // (C2) RESET HTML
  guess.hnum.value = guess.min;
  guess.hnum.readOnly = false;
  guess.htries.innerHTML = 0;
  guess.hhint.innerHTML = "";
  guess.hhint.className = "";
  guess.hbtn.value = `Make a Guess (${guess.min} to ${guess.max})`;
  guess.hform.onsubmit = () => guess.check();
  return false;
},

Next, guess.reset() is used to restart the game – Generate a new random “Jackpot” number, and reset the HTML interface.

 

 

PART 4) CHECK NUMBER

guess.js
// (D) MAKE A GUESS
check : () => {
  // (D1) GET CHOSEN NUMBER + RESET CSS
  var num = +guess.hnum.value;
  guess.guesses++;
  guess.htries.innerHTML = guess.guesses;
  guess.hhint.classList.remove("high");
  guess.hhint.classList.remove("low");
 
  // (D2) HIT!
  if (num==guess.jackpot) {
    guess.hhint.innerHTML = "Nailed it!";
    guess.hhint.classList.add("hit");
    guess.hnum.readOnly = true;
    guess.hbtn.value = "Reset";
    guess.hform.onsubmit = () => guess.reset();
  }
 
  // (D3) MISS - GIVE HINTS
  else {
    // (D3-1) HIGHER OR LOWER?
    let difference = num - guess.jackpot, text = "";
    if (difference>0) {
      text = "high";
      guess.hhint.classList.add("high");
    } else {
      text = "low";
      guess.hhint.classList.add("low");
    }
 
    // (D3-2) TOO MUCH OR CLOSE?
    difference = Math.abs(difference);
    if (difference>20) {
      text = "Too " + text;
    } else if (difference>=10) {
      text = "Slightly " + text;
    } else {
      text = "A little " + text;
    }
 
    // (D3-3) INTERFACE UPDATE
    guess.hhint.innerHTML = text;
  }
  return false;
}

Lastly, guess.check() runs whenever the player enters a number. Seemingly confusing at first, but trace through the code – It simply checks against the “Jackpot” number and gives hints on whether the guess is too high/low… Or if it is a hit (win).

 

EXTRA BITS & LINKS

That’s all for this project, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECKS

This game does not use a lot of advanced features, will work on most modern browsers.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you take a step forward, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

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