hangman game JavaScript from scratch

Welcome to my blog, In this article, we will make a Hangman Game javascript from scratch in HTML, CSS, JavaScript and I build another format of this Game click to view. Hangman game is a word guessing game javascript pick a random word and play tries to guess it.

Current Video Link:
Javascript Hangman Game

If you want to watch more videos subscribe my YouTube channel click here

We make a Funny Hangman Game in three steps : HTML,CSS and JavaScript.

Hangman Game HTML

First, we will create an index.html and create a basic static structure of Game-like add some button Hint, Play Again, how many lives you have to win the Game see HTML portion below:

Firstly we create an index.html file and add some HTML element they have complete the basic structure of the page let we about the HTML we take wrapper main outer div and add some tag like h1 and h2 tag for the game title and how to play a game and all keyboard buttons in the buttons div catagroyName showing the which type of the guess word is coming and mylives div take lives means how many lives you have left to win the game. Hangman game has a clue feature if you not game the accurate word then you can take the clue and the last one is stickman div inside have drawn a hangman automatic when your guess word is wrong after that hint and play again button you can take a hint and start the game again.

<div class="wrapper">
   <h1>Hangman</h1>
   <h2>Vanilla JavaScript Hangman Game</h2>
   <p>Use the alphabet below to guess the word, or click hint to get a clue. </p>
</div>
<div class="wrapper">
   <div id="buttons">
   </div>
   <p id="catagoryName"></p>
   <div id="hold">
   </div>
   <p id="mylives"></p>
   <p id="clue">Clue -</p>
   <canvas id="stickman">This Text will show if the Browser does NOT support HTML5 Canvas tag</canvas>
   <div class="container">
      <button id="hint">Hint</button>
      <button id="reset">Play again</button>
   </div>
</div>

Now the HTML portion is complete and starts work on the styling part of the Hangman Game bottom has a complete CSS directly copy and paste in your style.css

Hangman Game CSS

body {
   background: #000;
   font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
   color: #fff;
   height: 100%;
   text-align: center;
   font-size: 18px;
}
 .wrappper {
   width: 100%;
   margin: 0 auto;
}
 .wrappper:after {
   content: "";
   display: table;
   clear: both;
}
 canvas {
   color: #fff;
   border: #fff dashed 2px;
   padding: 15px;
}

The background design portion is done now styling a text portion like all heading tags that are used in the Game and apply CSS effects like before, active, hover, and after effect on text and a small part of media queries. I think you have to know CSS and have no explained the CSS portion completely. but if you have any queries you can ask.

h1, h2, h3 {
   font-family: 'Roboto', sans-serif;
   font-weight: 100;
   text-transform: uppercase;
   margin: 5px 0;
}
 h1 {
   font-size: 2.6em;
}
 h2 {
   font-size: 1.6em;
}
 p {
   font-size: 1.6em;
}
 #alphabet {
   margin: 15px auto;
   padding: 0;
   max-width: 900px;
}
 #alphabet:after {
   content: "";
   display: table;
   clear: both;
}
 #alphabet li {
   float: left;
   margin: 0 10px 10px 0;
   list-style: none;
   width: 35px;
   height: 30px;
   padding-top: 10px;
   background: #fff;
   color: #000;
   font-weight:700;
   cursor: pointer;
   -moz-border-radius: 5px;
   -webkit-border-radius: 5px;
   border-radius: 5px;
   -khtml-border-radius: 5px;
   border: solid 1px #fff;
}
 #alphabet li:hover {
   background: #c1d72e;
   border: solid 1px #fff;
   color: #fff;
}
 #my-word {
   margin: 0;
   display: block;
   padding: 0;
   display: block;
}
 #my-word li {
   position: relative;
   list-style: none;
   margin: 0;
   display: inline-block;
   padding: 0 10px;
   font-size: 1.6em;
}
 .active {
   opacity: 0.4;
   filter: alpha(opacity=40);
   -moz-transition: all 1s ease-in;
   -moz-transition: all 0.3s ease-in-out;
   -webkit-transition: all 0.3s ease-in-out;
   cursor: default;
}
 .active:hover {
   -moz-transition: all 1s ease-in;
   -moz-transition: all 0.3s ease-in-out;
   -webkit-transition: all 0.3s ease-in-out;
   opacity: 0.4;
   filter: alpha(opacity=40);
   -moz-transition: all 1s ease-in;
   -moz-transition: all 0.3s ease-in-out;
   -webkit-transition: all 0.3s ease-in-out;
}
 #mylives {
   font-size: 1.6em;
   text-align: center;
   display: block;
}
 button {
   -moz-border-radius: 5px;
   -webkit-border-radius: 5px;
   border-radius: 5px;
   -khtml-border-radius: 5px;
   background: #000;
   color: #fff;
   border: solid 1px #fff;
   text-decoration: none;
   cursor: pointer;
   font-size: 1.2em;
   padding: 18px 10px;
   width: 180px;
   margin: 10px;
   outline: none;
}
 button:hover {
   -webkit-transition: all 0.3s ease-in-out;
   -moz-transition: all 0.3s ease-in-out;
   transition: all 0.3s ease-in-out;
   background: #fff;
   border: solid 1px #fff;
   color: #c1d72e;
}
 @media (max-width: 767px) {
   #alphabet {
     padding: 0 0 0 15px;
  }
}
 @media (max-width: 480px) {
   #alphabet {
     padding: 0 0 0 25px;
  }
}

Hangman Game styling portion has done now working on javascript file.

Hangman Game JS

I have explain all the javascript function that we have used in the Game I am write all of functions in window.load

firstly we take all of the alphabets in the array and define some variables that have a need in the Game and get all of the required elements from the HTML now create a ul element and iterate all of the alphabets and generate a list item (li) on each iteration and set the id’s of each li after that append in ul and the main thing is remember that all of the functions are mention in window.load function inside.

window.onload = function () {

  var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
        't', 'u', 'v', 'w', 'x', 'y', 'z'];
  
  var categories;         // Array of topics
  var chosenCategory;     // Selected catagory
  var getHint ;          // Word getHint
  var word ;              // Selected word
  var guess ;             // Geuss
  var geusses = [ ];      // Stored geusses
  var lives ;             // Lives
  var counter ;           // Count correct geusses
  var space;              // Number of spaces in word '-'

  // Get elements
  var showLives = document.getElementById("mylives");
  var showCatagory = document.getElementById("scatagory");
  var getHint = document.getElementById("hint");
  var showClue = document.getElementById("clue");



  // create alphabet ul
  var buttons = function () {
    myButtons = document.getElementById('buttons');
    letters = document.createElement('ul');

    for (var i = 0; i < alphabet.length; i++) {
      letters.id = 'alphabet';
      list = document.createElement('li');
      list.id = 'letter';
      list.innerHTML = alphabet[i];
      check();
      myButtons.appendChild(letters);
      letters.appendChild(list);
    }
  }
}

so now we discuss the category function what is the working of this selectCat function. the function checks the value of random generated word that has to belong to which type of the category like films, football and sets it in the catagoryName ID div. the selectCat function does a little bit easier for the user can guess the word in a particular category.

now we discuss the next function the result function generates dashes here user enters the character and the length of dashes is equal to the random word length. the working of the comments function is to check how many lives you have left. if you lives less than 1 then Game Over and if you guess the word in given lives then you Win the Game.

  // Select Catagory
  var selectCat = function () {
    if (chosenCategory === categories[0]) {
      catagoryName.innerHTML = "The Chosen Category Is Premier League Football Teams";
    } else if (chosenCategory === categories[1]) {
      catagoryName.innerHTML = "The Chosen Category Is Films";
    } else if (chosenCategory === categories[2]) {
      catagoryName.innerHTML = "The Chosen Category Is Cities";
    }
  }

  // Create geusses ul
   result = function () {
    wordHolder = document.getElementById('hold');
    correct = document.createElement('ul');

    for (var i = 0; i < word.length; i++) {
      correct.setAttribute('id', 'my-word');
      guess = document.createElement('li');
      guess.setAttribute('class', 'guess');
      if (word[i] === "-") {
        guess.innerHTML = "-";
        space = 1;
      } else {
        guess.innerHTML = "_";
      }

      geusses.push(guess);
      wordHolder.appendChild(correct);
      correct.appendChild(guess);
    }
  }
  
  // Show lives
   comments = function () {
    showLives.innerHTML = "You have " + lives + " lives";
    if (lives < 1) {
      showLives.innerHTML = "Game Over";
    }
    for (var i = 0; i < geusses.length; i++) {
      if (counter + space === geusses.length) {
        showLives.innerHTML = "You Win!";
      }
    }
  }

the code of bottom block used for draw a hangman.

   // Animate man
  var animate = function () {
    var drawMe = lives ;
    drawArray[drawMe]();
  }

 // Hangman
  canvas =  function(){

    myStickman = document.getElementById("stickman");
    context = myStickman.getContext('2d');
    context.beginPath();
    context.strokeStyle = "#fff";
    context.lineWidth = 2;
  };
  
    head = function(){
      myStickman = document.getElementById("stickman");
      context = myStickman.getContext('2d');
      context.beginPath();
      context.arc(60, 25, 10, 0, Math.PI*2, true);
      context.stroke();
    }
    
  draw = function($pathFromx, $pathFromy, $pathTox, $pathToy) {
    
    context.moveTo($pathFromx, $pathFromy);
    context.lineTo($pathTox, $pathToy);
    context.stroke(); 
}

   frame1 = function() {
     draw (0, 150, 150, 150);
   };
   
   frame2 = function() {
     draw (10, 0, 10, 600);
   };
  
   frame3 = function() {
     draw (0, 5, 70, 5);
   };
  
   frame4 = function() {
     draw (60, 5, 60, 15);
   };
  
   torso = function() {
     draw (60, 36, 60, 70);
   };
  
   rightArm = function() {
     draw (60, 46, 100, 50);
   };
  
   leftArm = function() {
     draw (60, 46, 20, 50);
   };
  
   rightLeg = function() {
     draw (60, 70, 100, 100);
   };
  
   leftLeg = function() {
     draw (60, 70, 20, 100);
   };
  
  drawArray = [rightLeg, leftLeg, rightArm, leftArm,  torso,  head, frame4, frame3, frame2, frame1]; 

so the working of check function, when you click on any alphabet in the list. If the character, is right then fill in dashes and disabled the current alphabet. If your clicked character is wrong then -1 in your lives now we move on next function and the play() function I think it clear on the function name what is the working of this. when refreshing the page play() function call then all of the functions come back to initial state and the last one is the reset function to reset the game.

 // OnClick Function
  check = function () {
    list.onclick = function () {
      var geuss = (this.innerHTML);
      this.setAttribute("class", "active");
      this.onclick = null;
      for (var i = 0; i < word.length; i++) {
        if (word[i] === geuss) {
          geusses[i].innerHTML = geuss;
          counter += 1;
        } 
      }
      var j = (word.indexOf(geuss));
      if (j === -1) {
        lives -= 1;
        comments();
        animate();
      } else {
        comments();
      }
    }
  }
  
    
  // Play
  play = function () {
    categories = [
        ["everton", "liverpool", "swansea", "chelsea", "hull", "manchester-city", "newcastle-united"],
        ["alien", "dirty-harry", "gladiator", "finding-nemo", "jaws"],
        ["manchester", "milan", "madrid", "amsterdam", "prague"]
    ];

    chosenCategory = categories[Math.floor(Math.random() * categories.length)];
    word = chosenCategory[Math.floor(Math.random() * chosenCategory.length)];
    word = word.replace(/\s/g, "-");
    console.log(word);
    buttons();

    geusses = [ ];
    lives = 10;
    counter = 0;
    space = 0;
    result();
    comments();
    selectCat();
    canvas();
  }

  play();
  
  // Hint

    hint.onclick = function() {

      hints = [
        ["Based in Mersyside", "Based in Mersyside", "First Welsh team to reach the Premier Leauge", "Owned by A russian Billionaire", "Once managed by Phil Brown", "2013 FA Cup runners up", "Gazza's first club"],
        ["Science-Fiction horror film", "1971 American action film", "Historical drama", "Anamated Fish", "Giant great white shark"],
        ["Northern city in the UK", "Home of AC and Inter", "Spanish capital", "Netherlands capital", "Czech Republic capital"]
    ];

    var catagoryIndex = categories.indexOf(chosenCategory);
    var hintIndex = chosenCategory.indexOf(word);
    showClue.innerHTML = "Clue: - " +  hints [catagoryIndex][hintIndex];
  };

   // Reset

  document.getElementById('reset').onclick = function() {
    correct.parentNode.removeChild(correct);
    letters.parentNode.removeChild(letters);
    showClue.innerHTML = "";
    context.clearRect(0, 0, 400, 400);
    play();
  }

so the HTML, CSS, AND JAVASCRIPT portion is completed if you like the article share it with your friends. if you have any question or query related to the article and have any suggestions please leave in the comment box.

Thanks for reading the Article.

Leave a Reply

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