Simple Hangman Game In Javascript – Free Code Download

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!

ⓘ 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 How It Works Useful Bits
The End

 

 

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.

 

HANGMAN DEMO

REMAIN:

 

 

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-BY-STEP HANGMAN

All right, let us now get into the mechanics of the Javascript Hangman game.

 

STEP 1) GAME INTERFACE (HTML LAYOUT)

hangman.html
<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 with opacity: 0 and progressively move it up to opacity: 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 alphabets.
    • <div id="hangman-char"> All the available alphabets (A to Z).
    • <input id="hangman-reset"> The reset button.

 

 

STEP 2) GAME FLAGS & PROPERTIES

hangman.js
// (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

hangman.js
// (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

hangman.js
// (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, reset the game interface.

 

 

STEP 5) PICK AN ALPHABET

hangman.js
// (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) {
    // Reveal words
    for (var hit of hits) {
      document.getElementById("hangword-" + hit).innerHTML = char.value;
    }
    // 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 {
    // Update hangman
    hangman.wrongs++;
    var livesleft = hangman.guesses - hangman.wrongs;
    hangman.hLives.innerHTML = livesleft;
    hangman.hImg.style.opacity = (1 - (livesleft/hangman.guesses)).toFixed(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”.

 

 

USEFUL 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

(A) Game Settings
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.
(B) Game Flags
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.
(C) HTML Elements
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!

2 thoughts on “Simple Hangman Game In Javascript – Free Code Download”

Leave a Comment

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