Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

3 Steps Simple Hangman Game in Javascript

INTRODUCTION
THE CLASSIC GAME

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 end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!

NAVIGATION
TABLE OF CONTENTS

Prelude
How to Play

Step 1
The HTML

Step 2
The CSS

Step 3
The Javascript

Extra
Download & More

Closing
What’s Next?

PRELUDE
HOW TO PLAY

Before we start with the code, here is a quick section on how to play Hangman… Yep, pretty sure not all people know to play. Do feel free to skip this section if you already know how.

HANGMAN GAME RULES

  • Hangman is a simple game that revolves around 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 all the alphabets.

STEP 1
THE HTML

Now that we are done with the basic rules, let us start by building the basic interface of the game in HTML.

THE SCRIPT

hangman.html


  
    
      Simple Hangman Javascript
    
Lives Left:

THE EXPLANATION

Yep, this is not an award-winning design, but it works. There are a few sections to the HTML:

  • The entire game is contained within hangman-wrap.
  • To the left, we have the hangman image hangman-img. In this simple version, we will simply start with an opacity of 0, and progressively move it up as the player gets more strikes.
  • Do feel free to change this to your own image, or even draw the “traditional” stickman figure.
  • To the top right, we draw the blanks of the chosen random word and reveal them as the player picks the correct alphabets.
  • In the middle right are the available alphabets to choose from.
  • Finally, the “lives left” and a reset button on the bottom right.

STEP 2
THE CSS

Next, we move on with some cosmetics, the CSS.

THE SCRIPT

hangman.css
/* [ENTIRE HANGMAN WRAPPER] */
#hangman-wrap {
  display: flex;
  flex-direction: row;
  max-width: 800px;
  margin: 0 auto;
}

/* [LEFT - IMAGE] */
#hangman-left {
  width: 40%;
  background: #ccc;
}
#hangman-img {
  transition: all 1s;
  opacity: 0;
}

/* [RIGHT - GAME INTERFACE] */
#hangman-right {
  width: 60%;
  padding: 10px;
  background: #aaa;
}
#hangman-words span {
  display: inline-block;
  margin: 5px;
  font-size: 2em;
}
#hangman-char input[type=button] {
  font-size: 1.3em;
  padding: 5px;
}
#hangman-bottom {
  padding: 5px;
}

/* [DOES NOT MATTER] */
html, body {
  font-family: arial, sans-serif;
  padding: 0;
  margin: 0;
}

This should be pretty straightforward – Nothing but some skeleton CSS code. Please feel free to upgrade and change it as you see fit.

STEP 3
THE JAVASCRIPT

Finally, we complete the game with Javascript, which will do all the heavy lifting work.

THE SCRIPT

hangman.js
var hangman = {
  /* [GAME SETTINGS] */
  // Total number of allowed guesses before hanging
  guesses : 6, 
  // Available words for guessing
  // You might want to dynamically load this
  dictionary : ["impress", "incapable", "satisfaction", "develop", "determine"], 

  /* [FLAGS] */
  // Current chosen word
  word : null,
  // Word length
  wordlen : 0,
  // Current number of correct words
  rights : 0,
  // Current number of wrong guesses
  wrongs : 0,
  // HTML reference to hangman IMG
  elImg : null,
  // HTML reference to words DIV
  elWord : null,
  // HTML reference to characters DIV
  elChar : null,
  // HTML reference to lives left
  elLives : null,

  init : function () {
  // init() : game initialization

    // Get HTML elements
    hangman.elImg = document.getElementById("hangman-img");
    hangman.elWord = document.getElementById("hangman-words");
    hangman.elChar = document.getElementById("hangman-char");
    hangman.elLives = document.getElementById("hangman-lives");

    // - @TODO -
    // The dictionary can get pretty massive...
    // You might want to dynamically load more dictionaries from a file via AJAX.

    // Generate available characters
    var charwrap = document.getElementById("hangman-char");
    for (var i=65; i= 0) {
      index = hangman.word.indexOf(this.value, index);
      if (index == -1) { break; }
      else { 
        hits.push(index);
        index++;
      }
    }

    // Show the hits + calculate score
    if (hits.length > 0) {
      // Reveal words
      for (var hit of hits) {
        document.getElementById("hangword-" + hit).innerHTML = this.value;
      }

      // All hit - WIN!
      hangman.rights += hits.length;
      if (hangman.rights == hangman.wordlen) {
        hangman.toggle(true);
        alert("YOU WIN!");
      }
    } else {
      // Wrong - strike life off & show hangman
      hangman.wrongs++;
      var livesleft = hangman.guesses - hangman.wrongs;
      hangman.elLives.innerHTML = livesleft;
      hangman.elImg.style.opacity = (1 - (livesleft/hangman.guesses)).toFixed(2);

      // Run out of guesses - LOSE!
      if (hangman.wrongs == hangman.guesses) {
        hangman.toggle(true);
        alert("YOU LOSE!");
      }
    }

    // Disable selected character
    this.disabled = true;
  }
};

window.addEventListener("load", hangman.init);

THE EXPLANATION

Holy smokes. That is a lot of code, but keep calm and look carefully. There are only 4 functions, and let us walk through it section-by-section.

GAME SETTINGS

For a start, var hangman is the object that will drive the entire game, in case if you have not noticed… Right at the top, we have 2 properties that are used as the game setting.

PropertyDescription
guessesThe number of guesses that the player can make… Before losing.
dictionaryA word will be randomly chosen from this array at every round of the game.

GAME FLAGS

Moving on, we have some flags that will keep track of the game progress.

PropertyDescription
wordThe current chosen random word.
wordlenLength of the chosen word.
rightsThe number of correct alphabets guessed.
wrongsThe number of strikes received.
elImgHTML reference to hangman image.
elWordHTML reference to the word container.
elCharHTML reference to the choose alphabet container.
elLivesHTML reference to the “number of lives remaining”.

GAME MECHANICS

FunctionDescription
initFired on window load. Initializes the game and builds the interface.
toggleHelper function – Toggle enable/disable choose alphabet buttons.
resetReset the game.
checkFired when the player chooses an alphabet.

Yep, the script may look difficult, but there are only 4 functions involved. Rather than repeating through the code line-by-line (read that on your own if you are interested), here is a quick summary of how it runs:

  • When the window is fully loaded, hangman.init will fire up, and builds the necessary mechanics – Get the HTML references, create the alphabet buttons, then start the game by choosing a random word.
  • As the player chooses an alphabet, hangman.check will run, update the game interface, and keep track of the current score.
  • Finally, as the player win (or lose) the game, clicking on the reset button hangman.reset will choose another word and reset the entire game.

EXTRA
DOWNLOAD & MORE

That’s all for the code, and here is the download link as promised – Plus a small extra that may be useful to you.

ROCK PAPER SCISSORS

If you are interested in learning more about creating simple classic games, do check out my other guide:

3 Steps Simple Javascript Rock Paper Scissors Game

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.
 

CLOSING
WHAT’S NEXT?

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

The post 3 Steps Simple Hangman Game in Javascript appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

3 Steps Simple Hangman Game in Javascript

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×