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
Enter a number (0 to 100)
THE HTML
With that, let us start by creating the “game interface”. Which is actually nothing more than just a few lines of HTML.
NUMBER GUESSING GAME HTML INTERFACE
<div id="guess-wrap">
<h2>Enter a number (1 to 100)</h2>
<input id="guess-num" type="number" required min="0" max="100" value="0"/>
<button id="guess-btn">Make a Guess</button>
<div id="guess-txt"></div>
</div>
That’s right, there are only a few components here.
<input id="guess-num" type="number">
Number field to input the number.<button id="guess-btn">
“Make a guess” and “reset game” button.<div id="guess-txt">
Used to display hints, if the number is too high or too low.
THE JAVASCRIPT
Lastly, let us walk through the mechanics of the game, the Javascript.
A) GAME PROPERTIES
// (A) PROPERTIES
// (A1) HTML ELEMENTS
hnum : null, // number input field
hbtn : null, // guess/reset button
htxt : null, // response text field
// (A2) FLAGS
min : 0, // min allowed number
max : 0, // max allowed number
jackpot : 0, // the correct number
guesses : 0, // total nunmber of guesses made;
First, here are the properties of the game.
- (A1) Just 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) INITIALIZE
// (B) INITIALIZE
init : () => {
// (B1) GET HTML ELEMENTS
guess.hnum = document.getElementById("guess-num");
guess.hbtn = document.getElementById("guess-btn");
guess.htxt = document.getElementById("guess-txt");
// (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);
guess.init()
will run on page load, this should be pretty self-explanatory – Get the HTML elements, and also the min/max allowed number.
C) RESET GAME
// (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.hbtn.innerHTML = "Make a Guess";
guess.hbtn.onclick = guess.check;
},
Next, guess.reset()
is used to restart the game – Generate a new random “Jackpot” number, and reset the HTML interface.
D) CHECK NUMBER
// (D) MAKE A GUESS
check : () => {
// (D1) GET CHOSEN NUMBER + RESET CSS
var num = +guess.hnum.value;
guess.guesses++;
guess.htxt.classList.remove("high");
guess.htxt.classList.remove("low");
// (D2) HIT!
if (num==guess.jackpot) {
guess.htxt.innerHTML = "Nailed it! Total guesses made - " + guess.guesses;
guess.htxt.classList.add("hit");
guess.hnum.readOnly = true;
guess.hbtn.innerHTML = "Reset";
guess.hbtn.onclick = guess.reset;
}
// (D3) MISS - GIVE HINTS
else {
// (D3-1) HIGHER OR LOWER?
let difference = num - guess.jackpot, text = "";
if (difference>0) {
text = "high";
guess.htxt.classList.add("high");
} else {
text = "low";
guess.htxt.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.htxt.innerHTML = text;
}
}
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).
USEFUL 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
- Arrow Function – CanIUse
This game does not use a lot of advanced features, will work on most modern browsers.
LINKS & REFERENCES
- Javascript BlackJack – Code Boxx
- Javascript MineSweeper – Code Boxx
- Javascript Hangman – Code Boxx
- Javascript Quiz – Code Boxx
- Javascript Memory Game – Code Boxx
- Javascript Number Guessing Game – Code Boxx
- Javascript Tic-Tac-Toe – Code Boxx
- Javascript Rock Paper Scissors Game – Code Boxx
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!