Welcome to a tutorial on how to create a Hangman game with Javascript. So you are interested in learning how to create a game with Javascript, or maybe just forced to do so in a school project. đ Well, although it does require quite some time, it really isnât that difficult to create one â This guide will walk you through how to do it, step-by-step. Read on to find out!
Â
TABLE OF CONTENTS
Â
Â
JAVASCRIPT HANGMAN
All right, let us now get into the mechanics of the Javascript Hangman game.
Â
HANGMAN DEMO
Â
Â
HOW TO PLAY (HANGMAN GAME RULES)
Not going to judge the people who donât know Hangman, here are the quick rules:
- Hangman is a simple game about guessing a randomly chosen word.
- The player gets to choose an alphabet every round.
- If the alphabet does not exist in the chosen word, the player will receive one strike.
- After receiving a certain number of strikes, the player loses the game.
- The player will win the game if he/she/it correctly guesses the word.
Â
STEP 1) GAME INTERFACE (HTML LAYOUT)
<div id="hangman-wrap">
<!-- (A) LEFT : HANGMAN & LIVES -->
<div id="hangman-left">
<!-- (A1) HANGMAN IMAGE -->
<img id="hangman-img" src="hangman.png">
<!-- (A2) REMAINING LIVES -->
<div id="hangman-lives-w">
REMAIN: <span id="hangman-lives"></span>
</div>
</div>
<!-- (B) RIGHT : GAME INTERFACE -->
<div id="hangman-right">
<!-- (B1) CURRENT WORD(S) -->
<div id="hangman-words"></div>
<!-- (B2) AVAILABLE CHARACTERS -->
<div id="hangman-char"></div>
<!-- (B3) RESET -->
<input type="button" value="Reset" id="hangman-reset" disabled>
</div>
</div>
Not an award-winning design, but it works.
- The game is contained within
<div id="hangman-wrap">
, and it is split into<div id="hangman-left">
and<div id="hangman-right">
- On the left:
<img id="hangman-img">
The hangman image. We start withopacity: 0
and progressively move it up toopacity: 1
as the player gets more strikes.<span id="hangman-lives">
The number of âremaining livesâ.
- On the right:
<div id="hangman-words">
Blanks of the current word, and we reveal them as the player picks the correct alphabet.<div id="hangman-char">
All the available alphabets (A to Z).<input id="hangman-reset">
The reset button.
Â
Â
STEP 2) GAME FLAGS & PROPERTIES
// (A) GAME SETTINGS
// the number of "lives"
guesses : 5,
// available words for guessing
dictionary : ["impress", "incapable", "satisfaction", "develop", "determine"],
// (B) FLAGS
word : null, // current chosen word
wordlen : 0, // word length
rights : 0, // current number of correct words
wrongs : 0, // current number of wrong guesses
// (C) HTML ELEMENTS
hImg : null, // hangman iamge
hWord : null, // current word
hChar : null, // available characters
hLives : null, // lives left
We start with defining all the game properties in Javascript. These should be pretty self-explanatory â The number of âlivesâ, dictionary, flags for the current chosen word, number of strikes, HTML elements, etcâŠ
Â
STEP 3) GAME INITIALIZE
// (D) INIT
init : () => {
// (D1) GET HTML ELEMENTS
hangman.hImg = document.getElementById("hangman-img");
hangman.hWord = document.getElementById("hangman-words");
hangman.hChar = document.getElementById("hangman-char");
hangman.hLives = document.getElementById("hangman-lives");
// (D2) GENERATE AVAILABLE CHARACTERS (A-Z)
for (var i=65; i<91; i++) {
let charnow = document.createElement("input");
charnow.type = "button";
charnow.value = String.fromCharCode(i);
charnow.disabled = true;
charnow.onclick = () => hangman.check(charnow);
hangman.hChar.appendChild(charnow);
}
// (D3) START GAME
let rst = document.getElementById("hangman-reset");
rst.onclick = hangman.reset;
rst.disabled = false;
hangman.reset();
}
window.addEventListener("DOMContentLoaded", hangman.init);
hangman.init()
is the first thing we call on window load to initialize the game. Not going to explain line-by-line, but all this essentially does is to set up the HTML.
Â
Â
STEP 4) GAME START/RESTART
// (E) HELPER - TOGGLE ENABLE/DISABLE ALL AVAILABLE CHARACTERS
toggle : disable => {
let all = hangman.hChar.getElementsByTagName("input");
for (var i of all) { i.disabled = disable; }
},
 // (F) START/RESET THE GAME
reset : () => {
// (F1) RESET STATS
hangman.rights = 0;
hangman.wrongs = 0;
hangman.hLives.innerHTML = hangman.guesses;
hangman.hImg.style.opacity = 0;
// (F2) CHOOSE A RANDOM WORD FROM THE DICTIONARY
hangman.word = hangman.dictionary[Math.floor(Math.random() * Math.floor(hangman.dictionary.length))];
hangman.word = hangman.word.toUpperCase();
hangman.wordlen = hangman.word.length;
// CHEAT!
// console.log(hangman.word);
// (F3) DRAW THE BLANKS
hangman.hWord.innerHTML = "";
for (var i=0; i<hangman.word.length; i++) {
var charnow = document.createElement("span");
charnow.innerHTML = "_";
charnow.id = "hangword-" + i;
hangman.hWord.appendChild(charnow);
}
// (F4) ENABLE ALL CHARACTERS
hangman.toggle(false);
}
After the HTML setup is complete, hangman.reset()
will deal with starting/restarting the game. It looks confusing at first, but trace through slowly â It is very straightforward. Reset all the game flags, pick another word, and reset the game interface.
Â
Â
STEP 5) PICK AN ALPHABET
// (G) CHECK IF SELECTED CHARACTER IS IN THE CURRENT WORD
check : char => {
// (G1) CHECK FOR HITS
var index = 0, hits = [];
while (index >= 0) {
index = hangman.word.indexOf(char.value, index);
if (index == -1) { break; }
else {
hits.push(index);
index++;
}
}
// (G2) CORRECT - SHOW THE HITS
if (hits.length > 0) {
// (G2-1) REVEAL WORDS
for (var hit of hits) {
document.getElementById("hangword-" + hit).innerHTML = char.value;
}
// (G2-2) ALL HIT - WIN!
hangman.rights += hits.length;
if (hangman.rights == hangman.wordlen) {
hangman.toggle(true);
alert("YOU WIN!");
}
}
// (G3) WRONG - MINUS LIFE & SHOW HANGMAN
else {
// (G3-1) UPDATE HANGMAN
hangman.wrongs++;
var livesleft = hangman.guesses - hangman.wrongs;
hangman.hLives.innerHTML = livesleft;
hangman.hImg.style.opacity = (1 - (livesleft/hangman.guesses)).toFixed(2);
// (G3-2) RUN OUT OF GUESSES - LOSE!
if (hangman.wrongs == hangman.guesses) {
hangman.toggle(true);
alert("YOU LOSE!");
}
}
// (G4) DISABLE SELECTED CHARACTER
char.disabled = true;
}
Lastly, we have hangman.check()
. This is fired when the player picks an alphabet â We then check if the chosen alphabet is in the current word, update the score accordingly. If the player guessed the entire word, thatâs a win. If not, the player loses on ârunning out of livesâ.
Â
Â
DOWNLOAD & NOTES
Here is the download link to the example code, so you donât have to copy-paste everything.
Â
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
Â
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on âdownload zipâ or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
Â
EXTRA BITS & LINKS
Thatâs all for the code, and here are a few small extras that may be useful to you.
Â
JAVASCRIPT SUMMARY
GAME PROPERTIES
Property | Description |
guesses | The number of guesses that the player can make before losing. |
dictionary | A word will be randomly chosen from this array at every round of the game. |
Property | Description |
word | The current chosen random word. |
wordlen | Length of the chosen word. |
rights | The number of correct alphabets guessed. |
wrongs | The number of strikes received. |
Property | Description |
hImg | HTML reference to hangman image. |
hWord | HTML reference to the word container. |
hChar | HTML reference to the choose alphabet container. |
hLives | HTML reference to the ânumber of lives remainingâ. |
GAME MECHANICS
Function | Description |
init() | Fired on window load. Initializes the game and builds the interface. |
toggle() | Helper function â Toggle enable/disable choose alphabet buttons. |
reset() | Reset the game. |
check() | Fired when the player chooses an alphabet. |
Â
SIMPLE JAVASCRIPT GAMES
If you are interested in learning more about creating simple classic games, do check out my other guides:
Â
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
How do i add a start button that initates a start before game starts
Really? Donât skip the basics.
<input type="button" onclick="hangman.init()"/>