Simple Javascript Number Guessing Game – Free Code Download

Welcome to a tutorial on how to create a simple Javascript number guessing game. So you have mastered the basics of Javascript and is interested to test out your new-found 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 HTML & CSS The Javascript
The End

 

 

DOWNLOAD & DEMO

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

 

SOURCE 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.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer 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.

 

NUMBER GUESS DEMO

Enter a number (0 to 100)

 

THE HTML & CSS

Let us start by creating the “game interface”, which is actually nothing more than just a few lines of HTML and CSS.

 

THE SCRIPT

guess.html
<form id="guess-form">
  <h1>
    Enter a number
  </h1>
  <input id="guess-num" type="number" required min="0" max="100" value="0"/>
  <input id="guess-btn" type="submit" value="Make a Guess"/>
  <div id="guess-txt"></div>
</form>
  • This is nothing but a simple HTML form.
  • A required number input field… Of course. 🙄
  • The submit button is kind of optional, as pressing enter will submit the form as well.
  • The <div> is used to display hints – If the number you input is too high or too low.

 

 

CSS COSMETICS

guess.css
#guess-form, #guess-form input {
  font-family: arial, sans-serif;
}
#guess-form {
  padding: 10px;
  max-width: 320px;
}
#guess-form input {
  box-sizing: border-box;
  width: 100%;
  margin: 10px;
  padding: 10px;
}
#guess-form input[type=submit] {
  background: #9F2222;
  border: 0;
  color: #fff;
  cursor: pointer;
  font-weight: bold;
  font-size: 1em;
}
#guess-txt {
  margin: 10px;
  padding: 10px;
  text-align: center;
}
#guess-txt.high {
  background: #DEFBE8;
}
#guess-txt.hit {
  background: #D8FFBD;
}
#guess-txt.low {
  background: #FBE4DE;
}

Just some simple cosmetics to make things look better. Feel free to change the styles however you like.

 

 

THE JAVASCRIPT

Finally, we will complete the puzzle with Javascript, which does most of the heavy lifting work.

 

THE SCRIPT

guess.js
var guess = {
  /* [ALL THE PLAYERS] */
  form : null, // holds the form itself
  field : null, // holds the number input field
  min : 0, // min allowed number
  max : 0, // max allowed number
  button : null, // holds the submit button
  txt : null, // holds the response text field
  jackpot : 0, // the correct number
  guesses : 0, // total nunmber of guesses made

  /* [CHECK GIVEN NUMBER] */
  check : function (evt) {
    // Hit or miss?
    var num = parseInt(guess.field.value);
    guess.guesses++;
    guess.txt.classList.remove("high");
    guess.txt.classList.remove("low");

    // Hit - Update interface
    if (num==guess.jackpot) {
      guess.txt.innerHTML = "Nailed it! Total guesses made - " + guess.guesses;
      guess.txt.classList.add("hit");
      guess.field.readOnly = true;
      guess.button.value = "Reset";
      guess.form.removeEventListener("submit", guess.check);
      guess.form.addEventListener("submit", guess.reset);
    }

    // Miss - Give some hints
    else  {
      var difference = num - guess.jackpot,
          text = "";

      // High or low?
      if (difference>0) {
        text = "high";
        guess.txt.classList.add("high");
      } else {
        text = "low";
        guess.txt.classList.add("low");
      }

      // 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;
      }

      // Interface update
      guess.txt.innerHTML = text;
    }

    // Stop the form from submitting
    evt.preventDefault();
    evt.stopPropagation();
    return false;
  },

  /* [RESET THE GAME] */
  reset : function (evt) {
    guess.guesses = 0;
    guess.txt.innerHTML = "";
    guess.txt.classList.remove("hit");
    guess.field.readOnly = false;
    guess.field.value = 0;
    guess.button.value = "Make a Guess";
    guess.form.removeEventListener("submit", guess.reset);
    guess.form.addEventListener("submit", guess.check);

    // Generate the random jackpot number
    // Credits to 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;

    // For the cheaters
    console.log("Jackpot - " + guess.jackpot);

    // Stop the form from submitting
    evt.preventDefault();
    evt.stopPropagation();
    return false;
  }
};

/* [INIT] */
window.addEventListener("load", function(){
  // Get the HTML elements
  guess.form = document.getElementById("guess-form");
  guess.field = document.getElementById("guess-num");
  guess.min = Math.ceil(guess.field.min);
  guess.max = Math.floor(guess.field.max);
  guess.button = document.getElementById("guess-btn");
  guess.txt = document.getElementById("guess-txt");

  // Attach on submit event
  guess.form.addEventListener("submit", guess.check);

  // Generate the random jackpot number
  // Credits to 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;

  // For the cheaters
  console.log("Jackpot - " + guess.jackpot);
});

 

 

THE EXPLANATION

Holy cow, this sure looks like a whole bunch of confusion. But as you can see, the entire game is contained within the var guess object, and let us break it down piece-by-piece.

 

PROPERTIES

guess.form Contains the HTML form.
guess.field Contains the HTML number input field.
guess.max The maximum allowed number input.
guess.min The minimum allowed number input.
guess.button Contains the HTML submit button.
guess.txt Contains the HTML text feedback.
guess.jackpot The jackpot number.
guess.guesses The number of guesses made so far.

 

FUNCTIONS

guess.check Fired after the user enters a number and submits the form. Checks if the given number matches the jackpot.
guess.reset Used to reset the current game – Creates a new random Jackpot number, and resets the interface.

 

THE QUICK OVERVIEW

  • When the window is fully loaded, various form elements will be adapted into the properties of var guess.
  • A random jackpot number will be generated based on the min and max properties set on the number field.
  • guess.check will be attached to handle the form submission.
  • guess.check is actually pretty straightforward – It simply gets the input number, matches it against the current jackpot, and display the hints.
  • If it is a hit, the interface will “locked” and the submit event will be changed to guess.reset instead.
  • As you can guess, guess.reset simply resets the number of guesses made, generate a new random jackpot number, and reset the interface.

 

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 *